4.6. Nested conditionalsΒΆ
One conditional can also be nested within another. We could have written the three-branch example like this:
- No
- This is a legal nested if-else statement. The inner if-else statement is contained completely within the body of the outer else-block.
- Yes
- This is a legal nested if-else statement. The inner if-else statement is contained completely within the body of the outer else-block.
Q-2: Will the following code cause an error?
x = -10
if x < 0:
print("The negative number ", x, " is not valid here.")
else:
if x > 0:
print(x, " is a positive number")
else:
print(x," is 0")
The outer conditional contains two branches. The first branch contains a
simple statement. The second branch contains another if
statement, which has two branches of its own. Those two branches are
both simple statements, although they could have been conditional
statements as well.
Although the indentation of the statements makes the structure apparent, nested conditionals become difficult to read very quickly. In general, it is a good idea to avoid them when you can.
Logical operators often provide a way to simplify nested conditional statements. For example, we can rewrite the following code using a single conditional:
The first print
statement is executed only if we make it past
both conditionals, so we can get the same effect with the
and
operator:
- I only
- You can not use a Boolean expression after an else.
- II only
- Yes, II will give the same result.
- III only
- No, III will not give the same result. The first if statement will be true, but the second will be false, so the else part will execute.
- II and III
- No, Although II is correct III will not give the same result. Try it.
- I, II, and III
- No, in I you can not have a Boolean expression after an else.
Q-5: Which of I, II, and III below gives the same result as the following nested if?
# nested if-else statement
x = -10
if x < 0:
print("The negative number ", x, " is not valid here.")
else:
if x > 0:
print(x, " is a positive number")
else:
print(x, " is 0")
I.
if x < 0:
print("The negative number ", x, " is not valid here.")
else x > 0:
print(x, " is a positive number")
else:
print(x, " is 0")
II.
if x < 0:
print("The negative number ", x, " is not valid here.")
elif x > 0:
print(x, " is a positive number")
else:
print(x, " is 0")
III.
if x < 0:
print("The negative number ", x, " is not valid here.")
if x > 0:
print(x, " is a positive number")
else:
print(x, " is 0")
- True
- Yes, it is possible to use elif statements within nested if-else statements, just make sure you are keeping track of all the branches.
- False
- Try again. You can have multiple branches within each branch of an if-else statement.
Q-6: True or False? You can use elif
statements within nested if-else statements.