11.5. Using if and else¶
The first program we saw on the last page is a bit repetitive. It compares
weight
to the number 1 twice, once to see if it is below that number,
once to see if it is not below that number:
1if weight < 1:
2 price = 1.45
3if weight >= 1:
4 price = 1.15
In situations like this, where there are exactly two mutually exclusive options (we either
have to do one or the other), there is an easier way to write the logic.
That is to use else
. else
provides a way to say “if the condition for the preceding
if was False, do this”. The body of the else - the code that will be executed if the if’s test
fails - is indented after the else.
Using an if
with an else
makes sure that either the if
block is executed or the
else
block is executed, but never both.
We never have to use an else
. We can always write two seperate if
statements. But
using else
can help avoid bugs where there is a “gap” between the two options like we saw on
the previous page.
Mixed up programs
The following program should print out “x is even” if the remainder of x divided by 2 is 0
and “x is odd” otherwise, but the code is mixed up. Remember that the %
symbol gives
the remainder after the first number is divided by the second number. Drag the blocks from
the left and place them in the correct order on the right. Be sure to also indent correctly!
The following function should calculate the shipping cost for an order. Orders over $50 ship free. Otherwise, it is $5 base shipping plus $0.75 per pound. Drag the blocks from the left and place them in the correct order on the right. Be sure to also indent correctly!