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.
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.