These are the runnable exercises in Boolean Expressions in Python: Beginner to Expert. For the solutions to the exercises, see this notebook .
For each of the following questions, give the best answer. You can assume all code is indented/aligned correctly at the left even if it appears indented slightly in the question text.
1. The following Python code contains one or more errors. How would you correct them?
water_level = 5 if water_level > 3 print("Open flood gates") else print("Normal operations")
2. Which of the following is not a boolean expression, and why?
3. What does the following print?
noise_level = 2 heat_output_percent = 98 if noise_level > 4 or heat_output_percent 95: print("Call technician") else: print("Normal operation")
4. What does the following print:
to_be = True print(to_be and not to_be) print(to_be or not to_be)
5. What does the following print:
water_level = 3 time_of_day = "PM" heat_ouput_percent = 75 print(water_level > 5 and time_of_day == "PM" or heat_output_percent 90)
6. The following code works OK, but what if anything is wrong with it?
if (3 > 10) or (4.5 > 9): print("Gotcha!")
What is the value of obscure after the following code runs?
obscure = True and False or False or True
7. How might the following code be improved:
rebounds = None if rebounds != None: print("Got some rebounds!") else: print("No rebounds")
8. In the following code, which expressions are evaluated?
light_level = 10 decibel_level = 30 result = decibel_level > 50 or light_level == 10
A) decibel_level > 50
B) light_level == 10
D) Neither A nor B
9. Which of the following statements is false? There may be more than one.
A) An else clause must be preceded by an if clause. B) An if clause must be followed by an else clause. C) Usually, a Boolean expression contains one or more comparison operations. D) Boolean expressions can appear outside of an if statement. E) Boolean expressions must include a Boolean literal (i.e. one of the the keywords "True" or "False")
10. What is the error in the following code? How would you fix it?
water_level = 5 if water_level and water_level 3: print("Normal operations") else if water_level >= 3 and water_level 4.5: print("Call City Manager") else: print("Open flood gates and call City Manager")