Conditionals#


Conditional statements let you execute code conditionally based on some condition; they are similar in nature to the while loop but only run at most once.

In Python, the keywords to control these conditionals are if , elif (read “else if”) and else . For those that know Java, these keywords exactly match the semantics of Java’s if , else if and else keywords.

A conditional block is an if block optionally followed by any number of elif blocks optionally followed by at most one else block.

x = 14
if x < 10:
    print('A')
elif x >= 13:
    print('B')
elif x > 20:
    print('Not possible')
else:
    print('C')

This code prints B because the first if test fails ( x < 10 is False ) and then the second test succeeds ( x >= 13 is True ) so we enter the second body.

Two questions you should consider (you should think about these questions before expanding the output to see the answer!):

  • What values of x enter the else statement?

  • Why is it not possible to enter the third block (the second elif block)?