Nested conditional statement
In "if" blocks and "otherwise" may include any other statements, including other
nested conditional statements; the word
else
refers to the nearest previous
if
.
Example
if A > 10:
if A > 100:
print("You have a lot of money.")
else:
print("You have enough money.")
else:
print("You don't have enough money.")
Bold indicates a conditional statement that is inside another
if
statement, which is why it is called a
nested conditional statement. With nested conditional statements, you can implement multiple choices, not just two.
You can also use a nested operator after the word
else
.
Example
if A < 10:
print("You don't have enough money.")
else:
if A > 100:
print("You have a lot of money.")
else:
print("You have enough money.")
In this case, if after
else
one more condition needs to be checked, then instead of the
if
operator, you can use "
cascading" branching with the keyword
elif
(short for
else - if
).
Example
if A < 10:
print("You don't have enough money.")
elif A > 100:
print("You have a lot of money.")
else:
print("You have enough money.")
Pay attention to the indentation in all examples. When using a cascade condition, all
if-elif-else
keywords are at the same level.
With a large number of checks written using a cascading condition, for example, in the
if-elif-elif-...
chain, the first true condition is triggered.