Practice with if¶
The program below is broken in a subtle way. For one value of weight
, the price
will not be set to any value, so the calculation of total
will fail with an error that something is not defined
. This is why professional programmers will assign some value to a variable like price
at the beginning of the program, so that errors like this won’t happen. Can you figure out the value of weight
that will result in an error? Modify the code below to try different values for weight.
Try different values for weight
in the above code and then answer the question below:
It is certainly possible to have multiple if
statements, and each one can match (or not match) the data. Imagine a more complicated price scheme, where the price is based on the weight, but there is also a 10% discount for buying more then 10 items.
- $3.45
- This would be the answer without the 10% discount for buying 10 or more items
- $3.11
- Python doesn't automatically round up
- $3.105
- This is the actual result. But, can you pay $3.105?
- $3.10
- Python doesn't automatically change $3.105 to $3.10.
csp-12-7-4: What is the total for 12 items that weigh 3 pounds?
- A
- Notice that each of the first 4 statements start with an if. What is the value of grade when it is printed?
- B
- Each of the first 4 if statements will execute.
- C
- Copy this code to an activecode window and run it.
- D
- Each of the first 4 if statements will be executed. So grade will be set to A, then B then C and finally D.
- E
- This will only be true when score is less than 60.
csp-12-7-5: What is printed when the following code executes?
1score = 93
2if score >= 90:
3 grade = "A"
4if score >= 80:
5 grade = "B"
6if score >= 70:
7 grade = "C"
8if score >= 60:
9 grade = "D"
10if score < 60:
11 grade = "E"
12print(grade)
- x will always equal 0 after this code executes for any value of x
- If x was set to 1 originally, then it would still equal 1.
- if x is greater than 2, the value in x will be doubled after this code executes
- What happens in the original when x is greater than 2?
- if x is greater than 2, x will equal 0 after this code executes
- If x is greater than 2, it will be set to 0.
csp-12-7-6: Which of the following is true about the code below?
1x = 3
2if (x > 2):
3 x = x * 2;
4if (x > 4):
5 x = 0;
6print(x)