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.
Edit the code above 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.
In this second version, we set a price
as a default, then change it only
on the special condition. Does it work the same as the above example?
-
csp-12-3-1: Are there values for weight that make the two programs above print different results when the same weight is used in both programs?
- No, they're always the same.
- The end result is the same.
- Yes, they're different if the weight is exactly 1 pound.
- If the weight is exactly 1 pound the price will be 1.15 in both programs.
- Yes, they're different if the weight is under 1 pound.
- If the weight is under 1 pound the price will be 1.45 in both programs.
- Yes, they're different if the weight is over 1 pound.
- If the weight is over 1 pound the price will be 1.15 in both programs.
Mixed up programs
csp-12-3-3: csp-12-3-2: 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! Click on Check Me to see if you are right. You will be told if any of the lines are in the wrong order or have the wrong indention.weight = 0.5
num_items = 5
if weight < 2:
---
price = 1.50
---
if weight >= 2:
---
price = 1.30
---
total = weight * price
---
print(weight)
print(price)
print(total)
Write the code to calculate and print the cost of a 14 mile cab ride. If the distance traveled is less than or equal to 12 miles the cost is $2.00 a mile, and if the distance traveled is more than 12 miles the cost is $1.50 a mile.