Programming with Python › Control Flow and Collections › Day 50
Day 50: Conditionals and Boolean Logic
After this lesson you will be able to write clear decision code in Python: produce booleans with comparison operators, combine them with and/or/not (using short-circuit evaluation deliberately), and choose a path with if/elif/else, the conditional expression, and guard clauses that keep logic flat and correct.
Hands-on lab for this lesson
Lab files on GitHub: https://github.com/ai-roadmap-365/ai-roadmap-365.github.io/tree/main/labs/sections/programming-with-python/day-050-conditionals-and-boolean-logic
- Get the hands-on files. Clone the labs repository once (you can reuse this clone for every lesson). This works on macOS, Linux, and Windows (PowerShell or WSL):
git clone https://github.com/ai-roadmap-365/ai-roadmap-365.github.io.git cd ai-roadmap-365.github.io - Open this lesson's lab. Move into the directory for this specific day. Every lab lives at the same predictable path — section / subsection / week / day:
cd labs/sections/programming-with-python/day-050-conditionals-and-boolean-logic - Read the lab guide. Open `README.md` in that directory. It lists the exact commands, what each does, the expected output, and how to check your work — read it before running anything.
- Run it and check your work. Follow the README's "How to run" section: run the example first to see the finished result, then complete the numbered exercises in `starter/`, then run the tests. The tests pass (exit 0) only when your work is correct.
bash tests/run_tests.sh # or the test command named in the lab README
You can also open the lab as a local page (works offline, shows the file tree and expected output).
Learning objectives
By the end of this lesson you will be able to:
- Define a boolean and list Python's falsy values, and explain why any value can serve as a condition through truthiness
- Use the six comparison operators and chained comparisons (e.g. 0.0 <= x <= 1.0) to produce booleans that read the way a mathematician would say them
- Combine booleans with and, or, and not, and explain short-circuit evaluation as both a speed and a correctness tool
- Write if/elif/else ladders whose branches are mutually exclusive and correctly ordered, and use the conditional (ternary) expression for two-way value choices
- Refactor deeply nested conditionals into flat guard clauses, and simplify negated conditions with De Morgan's laws
- Identify and avoid the common conditional bugs: = versus ==, unreachable branch order, comparing floats for exact equality, and is versus ==
- Connect readable boolean logic to AI practice — model-serving routes, data-cleaning rules, and agent control loops are all trees of conditions
Prerequisites
- Days 43-49 of this course: a working Python 3 install, variables and types, strings, numbers, input/output, reading error messages, and assembling a small program with functions and a main guard
- Comfort running a script from the terminal with python3 file.py and editing a text file
Why this matters
-
Every program branches, and the quality of its branching decides how readable it is.
-
Truthiness is Python-specific and catches everyone, especially where zero or an empty container is a legitimate value.
-
Short-circuit evaluation is not an optimisation detail. It is what makes
if x is not None and x.valuesafe. -
Deeply nested conditionals are the commonest readability failure in beginner code, and guard clauses fix it mechanically.
-
isand==differ, and using the wrong one produces bugs that pass in testing.
The idea in plain language
-
A condition is any expression, not just a comparison. Python asks whether it is truthy.
-
Comparisons chain —
0 <= x < 10reads as it looks and means what it reads. -
andandorstop early, and return one of their operands rather than a boolean. -
if/elif/elsepicks exactly one branch, and the first match wins. -
A guard clause handles the exceptional case and returns, leaving the main path unindented.
Historical background
-
Early languages branched with jumps, and a program’s flow could go anywhere.
-
Structured programming replaced that with blocks, so a reader could see the scope of a decision.
-
Python made blocks visible through indentation, which is unusual and deliberate: the layout cannot disagree with the logic.
-
Truthiness came from a pragmatic tradition — C treated zero as false — and Python extended it to empty containers.
-
elifexists becauseelse: if:nests, and a chain of a dozen conditions would march off the right of the screen. -
The ternary expression arrived late, in Python 2.5, and its unusual word order was chosen so the common value reads first.
What it is — and what it is not
A condition is:
- Any expression, evaluated for truthiness.
- Short-circuiting when combined with
andoror. - Exactly one branch taken, in an
if/elif/elsechain.
It is not:
-
Not restricted to booleans.
if items:is idiomatic and asks about emptiness. -
Not the same as
is. Identity and equality answer different questions — Day 44. -
Not returning a boolean, for
and/or. They return one of their operands, which is what makesx or defaultwork. -
Not a good place for complex logic. A condition that needs a comment wants a named function instead.
Why it was created and what problems it solves
-
Choosing between paths, which is what makes a program more than a sequence.
-
Readable emptiness tests.
if items:says what it means more directly than a length comparison. -
Safe compound conditions. Short-circuiting is what lets you check a precondition and use it in the same expression.
-
Flattening nesting. Guard clauses turn a pyramid of indentation into a list of rejections followed by the real work.
-
Avoiding repetition. A chain picks one branch, so the cases stay mutually exclusive by construction.
How it works
Booleans and truthiness
-
Falsy:
False,None, any zero, and any empty container —"",[],{},(),set(). -
Everything else is truthy, including
[0]and"0", which are not empty. -
if items:is the idiom for “if there is anything in it”. -
The sharp edge: a value that is present but zero fails that test. Write
if value is not None:when absent and empty must differ — Day 44’s rule.
Comparison operators
| Operator | Asks |
|---|---|
== / != | Equal value |
< <= > >= | Ordering |
is / is not | The same object — use only for None |
in / not in | Membership |
-
Comparisons chain:
0 <= x < 10is one expression, andxis evaluated once. -
That is not true in most languages, where it would parse as
(0 <= x) < 10and compare a boolean with a number. -
Never compare floats with
==— Day 46.
Logical operators and short-circuit evaluation
if user is not None and user.is_active: # safe
value = supplied or DEFAULT # DEFAULT when supplied is falsy
-
andstops at the first falsy operand;orstops at the first truthy one. -
Neither returns a boolean. They return the operand they stopped on, which is what makes
x or defaultan idiom. -
The order matters.
user.is_active and user is not Noneraises onNone, because the guard came second. -
orfor defaults has the truthiness trap:count or 10gives10whencountis0.
if / elif / else
-
The first true branch runs, and the rest are skipped.
-
elifis one keyword, not a nestedelse: if:, which keeps a long chain flat. -
elseis optional, and its absence means “otherwise do nothing”. -
Order the branches by likelihood where they are independent, and by specificity where they overlap.
The conditional expression
label = "empty" if not rows else f"{len(rows)} rows"
- The value comes first, then the condition, then the alternative.
- Use it when both branches produce a value for one name.
- Do not nest them. Two levels is already less readable than an
if.
Guard clauses instead of deep nesting
def process(order):
if order is None:
return None
if not order.items:
return None
if order.total <= 0:
return None
return summarise(order) # the real work, unindented
- Handle the exceptional cases first and return.
- The main path ends up at the lowest indentation, where the eye expects it.
- Each rejection is one line and can be read independently.
- The alternative is a pyramid whose closing braces you have to count back through to know which case you are in.
An everyday analogy
A doorman with a list.
| The door | The code |
|---|---|
| ”Are you on the list?” | A condition |
| Turning someone away immediately | A guard clause |
| Checking the list only if they have ID | Short-circuit evaluation |
| One queue, first match wins | if / elif |
| ”Anyone else, this way” | else |
| Someone with no bag at all | A falsy empty container |
-
The doorman rejects at the door, rather than escorting everyone inside and deciding later. That is a guard clause.
-
There is no point checking the list for someone with no identification, which is why the order of the two checks matters.
Examples in practice
-
if count:skipping a legitimate zero, which is truthiness in its most common failure. -
if x == None:whereis Nonewas meant, working by accident until a class defines__eq__. -
A five-level nested
ifthat a reader cannot hold in mind, flattened to four guard clauses. -
name or "anonymous"returning"anonymous"for an empty string, which may or may not be intended. -
A condition wrapped in a comment explaining it, which is the signal it should be a named function.
Implications: security, privacy, performance, scalability, and cost
-
Security: an authorisation check must not rely on truthiness.
if user:is true for any object;if user.is_admin:is the question. -
Fail closed. The
elsebranch of a permission decision should deny, so a new case is refused rather than allowed. -
Short-circuiting is a timing signal. Comparing secrets with
==returns early on the first differing byte — Day 26’s constant-time comparison. -
Performance: order compound conditions cheapest first, so the expensive one is often skipped.
-
A chain of twenty
elifs is linear. A dictionary lookup is not, and is usually clearer as well. -
Cost: unreadable branching is where bugs hide. Every nesting level roughly doubles the paths a reader must hold in mind.
Alternatives: free, open source, and commercial
| Approach | Where it fits |
|---|---|
if / elif / else | The default, for a handful of cases |
| A dictionary lookup | Mapping a value to a result, instead of a long chain |
match / case | Structural patterns, from Python 3.10 |
| Guard clauses | Validation, and any function with several rejections |
| A named predicate function | When the condition needs a comment to explain it |
| Polymorphism | When the branch is really “what kind of thing is this” |
-
Replace a long
elifchain that maps values to results with a dictionary. It is shorter, faster, and adding a case is one line rather than two. -
matchis for structure, not for replacing everyif. Use it when you are destructuring, not when you are comparing.
Comparison with related concepts
| Term | What it actually is |
|---|---|
| Truthy / falsy | How a non-boolean is judged in a condition |
| Short-circuit | Stopping evaluation once the answer is known |
| Chained comparison | a < b < c, evaluating b once |
| Guard clause | An early return handling an exceptional case |
| Ternary | A conditional that produces a value |
is vs == | Same object versus equal value |
When to use it — and when not to
-
Use
if items:for emptiness andis not Nonefor presence. They are different questions. -
Use guard clauses whenever a function has more than two levels of nesting.
-
Order compound conditions so the cheap or protective one comes first.
-
Use a dictionary rather than a long chain that maps values to results.
-
Do not use
==on floats, orison values. -
Do not nest ternaries.
-
Do not write a condition that needs a comment. Give it a name instead.
The AI connection
-
Truthiness bites hardest on arrays and tensors. An empty batch is falsy, and
if tensor:raises rather than answering, because the truth of many elements is ambiguous. -
Use
is Nonefor “not computed yet”, which is the commonest optional value in model code — a cached activation, an optional mask, a lazily built index. -
Short-circuit evaluation guards an expensive check:
if cheap_test and expensive_check()skips the second when the first fails. -
Guard clauses suit data validation, where most of the work is rejecting rows that cannot be processed.
-
A condition on a float is a comparison of approximations — Day 46’s rule, and
math.iscloseis the operator you actually want.
Knowledge check
quiz:
question: "A function uses `if quantity:` to check that a quantity was supplied. Orders with a quantity of 0 are silently skipped. What is the correct check?"
options:
- "`if quantity is not None:`, because 0 is falsy but is a legitimate supplied value"
- "`if quantity != False:`, to distinguish a numeric zero from a boolean"
- "`if len(str(quantity)):`, so any provided value is treated as present"
- "`if quantity >= 0:`, since quantities cannot be negative"
answer_index: 0
explanation: "Truthiness cannot distinguish absent from present-but-zero, because 0 and None are both falsy. When those two cases must behave differently, the test has to be about presence specifically, which is what `is not None` asks."
Hands-on exercise
Flatten a nested conditional and meet the truthiness trap. Worked through fully in the Day 50 lab directory.
| What you are doing | Command |
|---|---|
| Explore truthiness | bool(0), bool(""), bool([]), bool([0]) |
| Find the trap | if 0: versus if 0 is not None: |
| See short-circuiting | False and print("ran") — nothing prints |
See what or returns | 0 or "default" and "" or None |
| Chain a comparison | 0 <= x < 10 |
| Flatten with guards | Rewrite a 4-level nested function |
| Replace a chain | A 6-way elif becomes a dictionary lookup |
Expected output
False False False True
skipped
default None
True
[0]is truthy because the list is not empty, whatever is in it.0 or "default"returned the string, which is the trap when zero is a legitimate value.
Validate your work
- You found a case where
if x:andif x is not None:disagree - You demonstrated short-circuiting by putting a side effect on the right
- You showed that
and/orreturn an operand, not a boolean - You flattened a nested function into guard clauses
- You replaced an
elifchain with a dictionary -
bash tests/run_tests.shreports 0 failures
Troubleshooting
-
if x == True:behaves oddly. Compare truthiness directly withif x:, or identity withis Trueif you genuinely mean the object. -
A chained comparison surprises you.
a < b < cisa < b and b < c, withbevaluated once. -
orreturned something unexpected. It returns the first truthy operand, notTrue. -
The linter objects to
== None. It is right; useis None.
Common mistakes
- Truthiness where presence was meant.
- Guard checks in the wrong order, so the protective one runs second.
- Nesting four levels deep rather than returning early.
== True, which is both redundant and subtly different.
Practice assignment
-
Take a deeply nested function from your own code and flatten it with guard clauses, then compare the two side by side.
-
Find three places where
oris used for a default and decide, for each, whether zero or empty would be handled correctly. -
Convert an
elifchain of six or more branches into a dictionary lookup. -
Write the truthiness table from memory, then check it.
Extension challenge
-
Demonstrate short-circuiting with a side effect on the right-hand side, and use it to guard an expensive call.
-
Write a condition that is safe on
Noneand prove it raises when the two operands are reversed. -
Use
match/casefor a structural decision that anifchain handles awkwardly, and judge whether it earned its place. -
Measure a 50-way
elifchain against a dictionary lookup, and explain the shape of the difference.
Quiz
Q1. Which of the following is NOT one of Python's falsy values?
- The empty string ""
- The string "0"
- The integer 0
- The empty list []
Show answer
Answer: B. The string "0"
The falsy values are False, None, numeric zero (0 and 0.0), and every empty container ("", [], {}, (), set()). The string "0" is a non-empty string, so it is truthy — a classic trap when checking user input, because "0" passes an "if value:" test even though it looks like zero.
Q2. What does the expression `0.0 <= score <= 1.0` do?
- It compares 0.0 <= score, then compares the resulting boolean to 1.0
- It is a syntax error; Python does not allow two comparisons in one expression
- It is a chained comparison meaning score is between 0.0 and 1.0 inclusive, evaluating score once
- It only checks the lower bound and ignores the upper one
Show answer
Answer: C. It is a chained comparison meaning score is between 0.0 and 1.0 inclusive, evaluating score once
Python supports chained comparisons: `0.0 <= score <= 1.0` means exactly what it reads as — score is in the range 0.0 to 1.0 inclusive — and score is evaluated only once. It is more readable and less error-prone than writing `score >= 0.0 and score <= 1.0` by hand.
Q3. In the expression `user is not None and user.is_active`, why does the order of the two sides matter?
- It does not matter; `and` evaluates both sides regardless
- Python evaluates `and` from right to left, so the second side runs first
- The order only affects performance, never correctness
- Short-circuiting skips the second side when the first is False
Show answer
Answer: D. Short-circuiting skips the second side when the first is False
Because `and` short-circuits, if `user is not None` is False the whole expression is already False and `user.is_active` is never evaluated — which prevents an AttributeError when user is None. Swap the two sides and accessing `.is_active` on None would crash. Short-circuiting is a correctness tool, not just a speed trick.
Q4. What do the operators `and` and `or` actually return in Python?
- One of their operands, not necessarily a bool
- Always the literal value True or False
- The integer 1 for true and 0 for false
- A new boolean object created each time
Show answer
Answer: A. One of their operands, not necessarily a bool
`and` and `or` return one of their operands, not a fresh boolean. `"" or "default"` returns "default"; `"a" and "b"` returns "b". The result is still truthy or falsy, which is why it usually behaves like a boolean — and why `name or "anonymous"` is a common idiom for supplying a default.
Q5. Given `if score >= 0.5: category = "medium"` followed by `elif score >= 0.9: category = "high"`, what happens for score = 0.95?
- category becomes "high" because 0.95 >= 0.9
- category is "medium" — the first true branch wins
- Both branches run, so category ends up "high"
- Python raises an error about overlapping conditions
Show answer
Answer: B. category is "medium" — the first true branch wins
An if/elif ladder runs the block under the FIRST true condition and skips the rest. For 0.95 the first test `score >= 0.5` is already True, so category becomes "medium" and the `elif score >= 0.9` is never checked. The high branch is unreachable — a branch-ordering bug fixed by testing the most specific condition (>= 0.9) first.
Q6. Which rewrite of `not (verified and score >= 0.9)` is correct by De Morgan's laws?
- `not verified and score < 0.9`
- `verified or score >= 0.9`
- `not verified or score < 0.9`
- `not verified and score >= 0.9`
Show answer
Answer: C. `not verified or score < 0.9`
De Morgan's law says `not (A and B)` equals `not A or not B`. Here A is `verified` and B is `score >= 0.9`, so the result is `not verified or not (score >= 0.9)`, and `not (score >= 0.9)` is `score < 0.9`. The `and` becomes `or` and each part is negated.
Q7. What is the difference between the `if`/`else` statement and the conditional (ternary) expression `x if cond else y`?
- The ternary evaluates both branches and returns both values
- They are identical; the ternary is only shorter
- The ternary can run multiple statements in each branch
- The statement runs blocks; the ternary produces a value
Show answer
Answer: D. The statement runs blocks; the ternary produces a value
The `if`/`else` statement chooses which BLOCK of code runs; the ternary `x if cond else y` is an expression that evaluates to a single VALUE (either x or y). Use the ternary for a clean two-way value choice; use a full if when a branch does more than pick one value.
Q8. Why should you avoid testing floating-point numbers for exact equality, as in `if 0.1 + 0.2 == 0.3:`?
- 0.1 is not exact in binary, so the sum differs; use a tolerance
- Floats are always equal to each other, so the test is meaningless
- The `==` operator does not work on floats at all
- Float equality is banned by Python and raises an error
Show answer
Answer: A. 0.1 is not exact in binary, so the sum differs; use a tolerance
Numbers like 0.1 and 0.2 have no exact binary representation, so `0.1 + 0.2` is 0.30000000000000004, and `== 0.3` is False. Never test floats for exact equality; instead check that they are close enough, e.g. `abs(a - b) < 1e-9`.
Glossary
- boolean
- A value with exactly two possibilities, `True` or `False`, and Python's type (`bool`) for it. Named after George Boole, it is the smallest unit of a decision — a single yes or no — and every comparison produces one.
- truthy / falsy
- How Python treats any value when it is used as a condition. The falsy values are `False`, `None`, numeric zero (`0`, `0.0`), and every empty container (`""`, `[]`, `{}`, `()`, `set()`); everything else is truthy. This is why `if items:` means "if the list is non-empty."
- comparison operator
- An operator that compares two values and returns a boolean: `==` (equal), `!=` (not equal), `<`, `<=`, `>`, `>=`. Note that `==` compares values while `=` assigns a value to a name.
- logical operator (and / or / not)
- The operators that combine booleans: `A and B` is true only when both are true, `A or B` is true when at least one is, and `not A` flips true to false. In Python `and`/`or` return one of their operands, not a fresh boolean.
- short-circuit evaluation
- Python's lazy, left-to-right evaluation of `and`/`or` that stops as soon as the result is settled: `A and B` skips `B` when `A` is falsy, and `A or B` skips `B` when `A` is truthy. It is both a speed optimisation and a correctness tool (e.g. `x is not None and x.field`).
- conditional expression (ternary)
- A one-line expression, `value_if_true if condition else value_if_false`, that produces a single value based on a condition. Unlike an `if` statement (which runs blocks), the ternary yields a value you can assign or pass to a function.
- branch
- One of the alternative paths through a conditional — the block under an `if`, `elif`, or `else`. In an `if`/`elif`/`else` ladder the branches are mutually exclusive: the first whose condition is true runs, and the rest are skipped.
- guard clause
- A conditional near the top of a function that handles an exceptional case (invalid input, an early exit) immediately and returns or raises, so the main logic that follows never has to indent. Guard clauses keep decision code flat and readable instead of deeply nested.
- De Morgan's laws
- The rules for rewriting a negated combination of booleans: `not (A and B)` equals `not A or not B`, and `not (A or B)` equals `not A and not B`. They let you turn a confusing negated condition into an equivalent, clearer one.
- chained comparison
- Writing two comparisons in one expression, as in `0.0 <= score <= 1.0`, which means `score` is between 0.0 and 1.0 inclusive. Python evaluates the middle value once, making the form both readable and correct.
- if / elif / else
- Python's conditional statement. `if` runs a block when its condition is true; `elif` (else-if) tests another condition only when the previous ones were false; `else` catches everything remaining. Python takes the first true branch and skips the rest, so order matters.
- equality vs identity (== vs is)
- `==` tests whether two values are equal; `is` tests whether two names refer to the same object in memory (identity). Use `is` only for `None`, `True`, and `False` (e.g. `if x is None:`), and `==` for ordinary value comparisons.
Sources and further reading
- The Python Tutorial — More Control Flow Tools — Python Software Foundation (accessed 2026-07-13)
- Boolean Operations — Expressions reference — Python Software Foundation (accessed 2026-07-13)
- Automate the Boring Stuff with Python, 2nd Edition — Chapter 2: Flow Control — Al Sweigart (accessed 2026-07-13)
- Conditional Statements in Python — Real Python (accessed 2026-07-13)
- Boolean algebra — Wikipedia (accessed 2026-07-13)
Kept in this browser, no account needed. Your progress page turns the whole record into one link you can bookmark or open on another device.