11.4. Using Multiple if statements¶
You can use more than one
if statement in your code. Here’s an example of a calculation
that uses two
if statements. Let’s compute the total cost of an item where the price
is based on the weight of the item. If the item weighs less than 1 pound then the price is
1.45 a pound. If the item weighs 1 pound or more the price is 1.15 a pound.
The program below is an attempt to do that. But it is broken in a subtle way.
For one value of
price will not be set to any value, so the calculation
total will fail with an error that something
is not defined. Edit the code and change the first line so that
weight has a different value.
Run it again and see what changes. Try it in the codelens as well to see how the different
values for weight changes the lines of code that are executed. Can you figure out the value
weight that will result in an error?
So how can we fix the bug? One way would be to change the second if to use
>= so that there
the program handles every situation correctly.
Another way we could solve the problem would be to set a
price as a default, to assume
that the weight if 1 or more. Then, we use an
if to change change it only if the weight
turns out to be less than 1.
Check your understanding
The following program should calculate the total price, but the lines are mixed up. The price is based on the weight. Items that weigh less than 2 pounds should cost 1.5. Items that weigh more than 2 pounds should cost 1.3. Drag the blocks from the left and place them in the correct order on the right. Be sure to also indent correctly!