Course 3.2Lesson 3 of 5
A decision can sit inside another decision. The inner if is asked only when the outer condition is True, and it needs one more level of indent. Nested decisions give different messages for different reasons, but they quickly become hard to read. The same logic can often be written flat with and and elif. Choose the form that is easier to read, test every branch, and avoid going deeper than two levels.
Try the code and the simulations beside the lesson.
After this lesson you can
if inside another and keep the indents right,and and elif, andSometimes the second question makes sense only after the first answer. At a club door, the guard first asks about your age. Only if you are old enough does the guard look for a ticket. Python does the same, with an if inside an if.
age >= 18? It is True for 20.has_ticket? It is True.Welcome in.Look at the indents. The inner if is indented by four spaces under the outer if. The lines of the inner block are indented by eight. The else of the inner if lines up with the inner if, and the else of the outer if lines up with the outer if. The indent tells Python which else belongs to which if.
A good way to check: draw a vertical line down from each if. The else that belongs to it must touch the same line.
Each end of the tree is one print(). There are three ends, so three tests reach every one of them.
A nested decision is often possible to write flat, using and and elif.
Which one is better? There is no rule. Use the one that is clearer to read.
A word of advice: if you notice a third level of if inside if inside if, stop. Something is wrong. Try to make it flat, or split the code into functions (Chapter 12).
With two questions there are four combinations, and each should be tested.
| Age | Ticket? | Expected output |
|---|---|---|
| 20 | yes | Welcome in. |
| 20 | no | You are old enough, but you need a ticket. |
| 15 | yes | You are too young. |
| 15 | no | You are too young. |
The last two rows give the same answer. That is fine, but they show an important thing: the ticket does not change the answer when the person is too young.
else to the wrong if.age >= 18 in the outer if, you do not need to ask it again in the inner one.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
if is asked only when the outer condition is True. It has one more indent.else belongs to which if.and and elif. Choose the clearer one.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.