Sign in

Intro to Computer Science / Unit 5: Conditionals and Boolean Logic

5.5 Nested Conditionals and Tracing

3 practice questionsNot yet reviewed

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 A then B, because each if is tested on its own.
  • If the second if were changed to elif, only A would 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?
With n = 12, the code is: if n % 2 == 0: print "even", else: print "odd". What is printed?
A programmer writes if score = 10: and gets an error. What is the problem?

Ready for more? Take the Unit 5 test.