# 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:

What value for weight will result in an error complaining that price is not defined?

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.

csp-12-6-1: What is the total for 12 items that weigh 3 pounds?
• $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-6-2: What is printed when the following code executes?

  1 2 3 4 5 6 7 8 9 10 11 12 score = 93 if score >= 90: grade = "A" if score >= 80: grade = "B" if score >= 70: grade = "C" if score >= 60: grade = "D" if score < 60: grade = "E" print(grade) 
• 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-6-3: Which of the following is true about the code below?

 1 2 3 4 5 6 x = 3 if (x > 2): x = x * 2; if (x > 4): x = 0; print(x) 
• 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.

Note

Discuss topics in this section with classmates.