Nested Conditions
A block of code can contain any code, even another if statement. An if inside the block of another if is called a nested condition. It's useful when one question only makes sense after another. At the movies, for example, we first check whether the visitor has a ticket, and only then how old they are:
has_ticket = True
age = 15
if has_ticket:
if age >= 18:
print("Enjoy the movie")
else:
print("Sorry, this movie is for adults only")
else:
print("Please buy a ticket first")This prints:
Sorry, this movie is for adults onlyThe inner if statement runs only when has_ticket is true. Its blocks are indented by 4 more spaces, 8 in total, and each else is indented as much as the if it belongs to. That's how Python knows that the first else belongs to if age >= 18 and the second one to if has_ticket.
Nested conditions can often be rewritten with and and elif. This code does the same:
has_ticket = True
age = 15
if has_ticket and age >= 18:
print("Enjoy the movie")
elif has_ticket:
print("Sorry, this movie is for adults only")
else:
print("Please buy a ticket first")This prints:
Sorry, this movie is for adults onlyThe program gets to elif has_ticket only when the first condition is false. With a ticket, that means the visitor is under 18. Neither way is wrong: pick the one that's easier to read. When neither if has an else, a single if with and usually reads better: instead of if has_ticket: with if age >= 18: inside it, write if has_ticket and age >= 18:. It does the same, with one level of indentation less.
Instructions
- 1
A student passes the exam with 50 points or more, and with 75 or more passes with distinction. In the block of
if points >= 50:, write a nestedifstatement with the conditionpoints >= 75that printsPassed with distinction, and give it anelsebranch that printsPassed. You can reuse the lineprint("Passed"): move it into the innerelseand indent it by 4 more spaces. - 2
Change
pointsto82and run the program. It should printPassed with distinction.