Nested Conditionals
By using an if/else
statement, we produce two branches for our code to
follow. We can add more branches to our program flow by combining conditionals.
Let’s see how this works by solving the following problem:
Write a program that:
- Prompts the user to enter a whole number.
- If the number is odd, print nothing.
- If the number is even, print “EVEN!” If the number is also positive, print “POSITIVE”.
Our first attempt at a solution might look like this:
|
|
Console Output
Enter a whole number: 7
POSITIVE
When we enter 7
in the prompt, we want the program to print nothing. However,
we see the output POSITIVE
. The code doesn’t work as we want. Why not?
Written this way, the two conditionals are separate from each other. The result
from one has no influence on the other. Checking entry
as even or odd works
fine on its own. However, the second check gets carried out whether or not
entry%2 == 0
is True
or False
. Remember, the if
condition
does not apply after the first unindented line.
We want to check if entry
is positive only if the number is even. To do
this, we need to put the second conditional inside the first. This code
structure is called a nested conditional. The result of the first
conditional determines whether or not to consider the second.
Notice that when we put one conditional inside another, the body of the nested
conditional is indented by two levels rather than one. In Python, the indentation
of an if
statement determines if it is nested. For an if
statement to run inside another, it must be indented more than the outer conditional.
The correct solution looks like this:
entry = int(input("Enter a whole number: "))
if entry%2 == 0:
print("EVEN!")
if entry > 0:
print("POSITIVE")
Now, run the two different blocks of code in your IDE. You will see that the correctly nested version of the code will only output POSITIVE if the original if condition evaluates as True.
Nesting Also Works With else
In the examples above, we left out the else
clauses from the conditionals. Here is how we could add the else
clauses back in.
|
|
In Python, the amount of indentation tells us exactly which else
clause belongs to which if
statement.
Check Your Understanding
What is printed when the following code runs?
|
|
- The code won’t run due to invalid syntax.
- odd
- even
- The code runs but doesn’t print anything.
What is printed when the following code runs?
|
|
- Both of you agree!
- You two need to work this out.
- Stop arguing and work it out.
- Clean your bathroom anyway!