Python BOOLEAN LOGIC (needed for if-statements and loops): 7 practice problems
PREREQUISITE 1 of the free Python for AI course. Read the short theory, then solve the problems below with instant tests. Python runs in your browser.
▶ Practise BOOLEAN LOGIC (needed for if-statements and loops) nowAll topicsTheory: BOOLEAN LOGIC (needed for if-statements and loops) in Python
THEORY
------
* bool has exactly two values: True and False (capitalised!). bool is a subclass of int:
True == 1, False == 0, so True + True == 2.
* COMPARISON operators produce bools: == != < > <= >=
5 == 5.0 -> True "a" < "b" -> True (alphabetical by Unicode code point)
CHAINING: 0 <= x <= 100 means (0 <= x) and (x <= 100)
* LOGICAL operators:
and True only if BOTH are true
or True if AT LEAST ONE is true
not flips
Precedence: not > and > or so `not a or b and c` == `(not a) or (b and c)`
Truth tables (memorise for the viva):
A B | A and B | A or B
T T | T | T
T F | F | T
F T | F | T
F F | F | F
* SHORT-CIRCUIT evaluation: Python stops as soon as the answer is known.
x != 0 and 10 / x > 1 # safe: division never runs when x == 0
`and`/`or` return one of the OPERANDS, not necessarily True/False:
"" or "Guest" -> "Guest" 0 and 5 -> 0 3 and 5 -> 5
* TRUTHINESS: these are "falsy": False, None, 0, 0.0, "", [], {}, set(), ().
Everything else is "truthy". bool([]) -> False, bool("0") -> True (non-empty string!)
* XOR (exactly one is true): a != b (for bools) or a ^ b
* De Morgan's laws: not (a and b) == (not a) or (not b)
not (a or b) == (not a) and (not b)
7 BOOLEAN LOGIC (needed for if-statements and loops) practice problems
1. Leap Year — combined conditions (classic viva question!)
Easy2 ways to solve📤 OUTPUT: return a bool (True / False), e.g. True. Use `return`, not print().
Leap if divisible by 4, EXCEPT centuries, which must be divisible by 400.
is_leap_year(2024) -> True is_leap_year(1900) -> False is_leap_year(2000) -> True
Ways: one boolean expression with and/or · nested if statements
Solve “Leap Year — combined conditions (classic viva question!)” in your browser →2. Sensor Range Check — chained comparison
Easy2 ways to solve📤 OUTPUT: return a bool (True / False), e.g. True. Use `return`, not print().
Real world: Is the temperature reading inside the safe range (inclusive)?
in_range(25, 18, 30) -> True in_range(31, 18, 30) -> False
Solve “Sensor Range Check — chained comparison” in your browser →3. Exactly One Switch On — XOR
Easy3 ways to solve📤 OUTPUT: return a bool (True / False), e.g. True. Use `return`, not print().
Real world: A staircase light controlled by two switches is on when EXACTLY one is up.
exactly_one(True, False) -> True exactly_one(True, True) -> False
Solve “Exactly One Switch On — XOR” in your browser →4. Default Username — short-circuit `or`
Easy2 ways to solve📤 OUTPUT: return a str (text), e.g. 'Asha'. Use `return`, not print().
Real world: Show "Guest" when the user hasn't set a name (empty string or None).
display_name("Asha") -> "Asha" display_name("") -> "Guest" display_name(None) -> "Guest"
Try it in ONE expression with `or`.
Solve “Default Username — short-circuit `or`” in your browser →5. Predict the Output — return a list of your PREDICTED values (as literals):
Easy1 way to solve📤 OUTPUT: return a list of your predicted values, e.g. [True, False, ...]. Use `return`, not print().
[True and False or True, not True == False, bool("False"), bool(0.0),
3 and 0, 0 or "" or "x", not (False or True), 1 < 2 < 3 > 2, None or 0]
Do NOT type the expressions themselves — work them out.
Solve “Predict the Output — return a list of your PREDICTED values (as literals):” in your browser →6. Card Fraud Rules Engine — interview at a bank's risk team
Project1 way to solve📤 OUTPUT: return a tuple, e.g. ('allow', []). Use `return`, not print().
Interviewer: "Every card payment passes through our rules before it's approved. Write the engine."
Collect flags IN THIS ORDER:
"high_amount" (amount > 50000), "foreign" (country != home_country),
"night" (hour < 5 or hour >= 23), "new_device" (new_device is True)
decision: "block" if high_amount AND (foreign OR new_device)
"review" else if 2 or more flags
"allow" otherwise
Return (decision, flags)
fraud_check(60000, "US", "IN", 14, False) -> ("block", ["high_amount", "foreign"])
Solve “Card Fraud Rules Engine — interview at a bank's risk team” in your browser →7. Stage 2 — the Comparison & Logic Unit
Compiler1 way to solve📤 OUTPUT: return the result: a bool for comparisons, one of the operands for and/or. Use `return`, not print().
op is one of == != < <= > >= and or. "and"/"or" behave EXACTLY like Python's
(they return one of the operands: 0 and 5 -> 0, 0 or "x" -> "x").
Unknown op -> raise ValueError(f"unknown operator {op}")
Solve “Stage 2 — the Comparison & Logic Unit” in your browser →← HOW A PROGRAM WORKS: values, variables, arithmetic, print Data types & type casting →