if
then if
vs. if/elif
statements
As we learned in the previous section, an if
statement followed by an elif
are parts of the same control structure.
if logical_expression:
# do something if logical_expression is True
elif logical_expression2:
# do something if logical_expression is False
# and also logical_expression2 is True
This might lead us to ask–what is the difference between an if/elif
statement versus having two if
statements in a row?
Let’s take a look at some examples.
# TODO: run this code!
# What is the output?
x = 100
y = 50
# ONE control statement
if x > 7:
print("x greater than y")
elif x % y == 0:
print("x is divisible by y")
# TODO: run this code!
# What is the output?
x = 100
y = 50
# TWO control statements
if x > 7:
print("x greater than y")
if x % y == 0:
print("x is divisible by y")
# TODO: write your own experiments to compare the output of
# multiple if statements versus an if/else statement
We can compare the two by denoting them as follows:
if/elif
# ONE control statement
if logical_expression:
# do something if logical_expression is True
elif logical_expression2:
# do something if logical_expression is False
# and also logical_expression2 is True
if
then if
# First control statement
if logical_expression:
# do something if logical_expression is True
# SECOND control statment
if logical_expression2:
# do something if logical_expression2 is True
This is a common source of bugs in the programs we write that use conditionals!
Rule of thumb: If you only want one of a set of outcomes, use one if/elif/else
control structure. If you want 0 or more of a set of outcomes, use multiple if/elif/else
control structures.