Intro to Computer Science / Unit 5: Conditionals and Boolean Logic
5.5 Nested Conditionals and Tracing
Notes
Conditionals can be nested (one inside another), and several separate if statements are all checked, unlike an if/elif chain.
x = 8
if x > 5:
print("A")
if x > 7:
print("B")
else:
print("C")
- This prints
AthenB, because eachifis tested on its own. - If the second
ifwere changed toelif, onlyAwould print. - Trace by writing down variable values and checking each condition in order.
- Common mistakes: using
=instead of==, forgetting the colon, and wrong indentation.
Practice
What does the code above print if
x = 6?6 > 5 prints A. 6 > 7 is False so the else prints C.
With
n = 12, the code is: if n % 2 == 0: print "even", else: print "odd". What is printed?12 % 2 is 0, so the condition is True.
A programmer writes
if score = 10: and gets an error. What is the problem?Use == for comparison in a condition.
Ready for more? Take the Unit 5 test.