lesson 18 Conditional Logic · beginner
An if inside an if
The inner if runs only when the outer test is already true.
You'll be able to
- Indent a second if under the first
- Give the inner if its own else
- See that the inner test is skipped when the outer test is false
The idea
Sometimes the second question only matters after the first one is true. A return is only worth checking for condition if it is still inside the return window. Put that second if indented under the first.
The inner else belongs to the inner if. It must line up with that inner if, not with the outer one. and can ask both questions at once, but then you get only one answer for "no". Nesting lets each "no" say something different.
Run each example to see what it prints. Running examples doesn't count toward progress.
example-1.py · Packed, and expensive enough
price = 20 status = "packed" if price >= 15: if status == "packed": print("Ship") else: print("Pack first") else: print("Add more")
example-2.py · A ticket, then an age limit
tickets = 1 age = 15 if tickets > 0: if age >= 17: print("Enjoy the film") else: print("An adult must come too") else: print("Buy a ticket first") print("Next customer")
Review
- The inner if runs only when the outer test is true.
- An else lines up with the if it belongs to.
- Nested ifs can give each "no" its own answer, which one combined test can't. Next: values that count as true or false by themselves.
Practise this