02-09: Exercises — Boolean and None¶
Notes reference: 02-09: Boolean and None Types
Q1: bool arithmetic¶
True and False are subclasses of int. Predict and verify the output of:
Solution
Q2: Logical operators truth table¶
Fill in the results:
| A | B | A and B | A or B | not A |
|---|---|---|---|---|
| True | True | |||
| True | False | |||
| False | True | |||
| False | False |
Solution
for A in [True, False]:
for B in [True, False]:
print(f"{str(A):<5} {str(B):<5} | {str(A and B):<5} | {str(A or B):<5} | {str(not A):<5}")
True True | True | True | False
True False | False | True | False
False True | False | True | True
False False | False | False | True
Q3: Truthy and falsy¶
Classify each value as truthy or falsy:
0, "", " ", [], [0], None, 0.0, "False", False
Solution
values = [0, "", " ", [], [0], None, 0.0, "False", False]
for v in values:
print(repr(v), "→", bool(v))
0 → False
"" → False
" " → True (non-empty string!)
[] → False
[0] → True (non-empty list!)
None → False
0.0 → False
"False" → True (non-empty string!)
False → False
Q4: Short-circuit evaluation¶
Predict the output without running the code. Explain why no error occurs on line 2.
Solution
safe = False
No ZeroDivisionError because `and` short-circuits:
once (x != 0) evaluates to False, (1 / x > 0.5) is never evaluated.
Q5: or as default value¶
Write a one-liner that assigns "Guest" to display_name if username is an empty string, otherwise uses username.
Solution
username = ""
display_name = username or "Guest"
print(display_name) # Guest
username = "Jahid"
display_name = username or "Guest"
print(display_name) # Jahid
Q6: Comparison chaining¶
Check whether score = 85 is in the grade B range (80 ≤ score < 90) using a chained comparison.
Solution
Q7: None checks¶
Write code that sets result = None, then checks if it is None using the correct operator.
Solution
result = None
if result is None:
print("No result yet")
# Incorrect (but works) — avoid this:
# if result == None: ...
# Also correct — checking if it has a value:
if result is not None:
print("Result:", result)
else:
print("Result is absent")
Q8: bool() conversions¶
Use bool() to show that non-zero numbers are truthy and that all "empty" containers are falsy.
Solution
print(bool(42)) # True
print(bool(-1)) # True
print(bool(0)) # False
print(bool("hi")) # True
print(bool("")) # False
print(bool([1, 2])) # True
print(bool([])) # False
print(bool(None)) # False
⬅️ Previous: 02-08: Exercises — String Formatting ➡️ Next: 02-10: Exercises — Type Conversion