if/elif/else
statements
if
statements have multiple ways that we can customize them (other than changing the logical expression): the second of these ways is by adding an elif
clause to our statement.
The syntax of if/elif/else
statements is:
Let’s take a look at our previous example code again.
Notice that for each branch in our if/elif/else
statement, we only take that branch if all of the previous conditional statements evaluated to False
.
Notice that “big number” is only printed out if the first test of number > 1000
was False
.
Order of testing/execution
For all if/elif/else
statements, the program always executes the tests from top to bottom and stops as soon as one test evaluates to True
.
Variations the structure of if/elif/else
Any combination of if/elif/else
together is considered one control statement. The requirements for each part of this control statement are as follows:
if
- there must always be 1 and only 1if
statement at the beginning of your selection statement followed by a logical expression.elif
- there may be 1 or moreelif
statements. They must contain logical expressions and they must follow theif
statement.else
- there may be 1 or 0else
statements. Theelse
statement can never contain a logical expression. (Implicitly, the logical expression here is that all of the previous logical expressions wereFalse
.)
At the bottom of this set of course notes are a series of different, valid variations on a single if/elif/else
statement.
Note that all of these examples are for only 1 control statement.
# TODO: run this code!
# we'll talk about this code in the modules section
# -- basically we're getting
# some random numbers so that the behavior of this code can change
# when you run it different times
import random
# random int from the list [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# just like the range() function that we use with for loops!
x = random.randrange(0, 10)
y = random.randrange(0, 10)
print("x is: " + str(x))
print("y is: " + str(y))
# if with more than 1 elif and an else
if x < y:
print("[x is less than y]")
elif y % 2 == 0:
print("[x is not less than y] and [y is even]")
elif y < 5:
print("[x is not less than y] and [y is not even] and [y is less than 5]")
elif x < 5:
print("[x is not less than y] and [y is not even] and [y is not less than 5] and [x is less than 5]")
else:
print("[x is not less than y] and [y is not even] and [y is not less than 5] and [x is not less than 5]")