8. If—elif—else statements#
Sometimes you want greater control over the sequence of code execution, and that’s where control flow comes in.
Here we’ll work with the if
, elif
(else if), and else
constructs for conditional statements.
Conditional statements#
In Python, the general structure is like this:
if condition1:
do something only when condition1 is True
elif condition2:
otherwise, do something if condition2 is True (and condition1 was False)
else:
otherwise, do something
Note
if
is required, and the other two are optional.
Note
In MATLAB, control flow blocks have an end
to conclude. No need for that in Python!
Part 1#
Suppose you are buying apples at a supermarket. If you buy more than \(5\) apples, you get a \(10\%\) discount. Write a program computing the amount owed given the price per apple (assume it to be \(\$1\)) and the number of apples purchased.
n = 6 # number of apples purchased
price = 1 # price of one apple
if n > 5:
cost = 0.9 * price * n
else:
cost = price * n
""" this is a block comment, showing another solution
cost = price * n
if n > 5:
cost *= 0.9
"""
print(f"Amount owed for {n} apples: ${cost:.2f}")
Amount owed for 6 apples: $5.40
In the above, we used f-strings, which Enze thinks is one of the coolest things since sliced bread. 🍞
Part 2#
Suppose now the store offers a super discount of \(40\%\) if you buy more than \(20\) apples.
Modify the code in Part 1 to implement this new condition using the elif
statement.
Note that when programming conditional statements, we generally put equality conditions first, followed by bounded inequalities, and finally unbounded conditions.
n = 21 # number of apples purchased
price = 1 # price of one apple
if n > 5 and n <= 20:
cost = 0.9 * price * n
elif n > 20:
cost = 0.6 * price * n
else:
cost = price * n
print(f"Amount owed for {n} apples: ${cost:.2f}")
Amount owed for 21 apples: $12.60
Important
In Python, logical “and” uses the actual word and
instead of the symbols &&
as it’s commonly done in other languages.
Similarly, logical “or” uses the actual word or
.
Finally, please don’t confuse these keywords with the literal strings 'and'
and 'or'
!