Programming with Python › Control Flow and Collections › Day 50

Day 50: Conditionals and Boolean Logic

Day 50 of 365 — 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.

Course
Programming with Python
Category
Control Flow and Collections
Reading time
≈ 40 min
Practical time
≈ 30 min
Lesson duration
1h 10m
Last verified
2026-07-13

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

  1. 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
  2. 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
  3. 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.
  4. 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:

Prerequisites

Why this matters


The idea in plain language


Historical background


What it is — and what it is not

A condition is:

It is not:


Why it was created and what problems it solves


How it works

Booleans and truthiness

Diagram: testing truthiness compared with testing for None

Comparison operators

Diagram: how Python evaluates a chained comparison

OperatorAsks
== / !=Equal value
< <= > >=Ordering
is / is notThe same object — use only for None
in / not inMembership

Logical operators and short-circuit evaluation

Diagram: how short-circuit evaluation makes a compound condition safe

Diagram: how comparison operators produce booleans that logical operators combine into a decision

if user is not None and user.is_active:   # safe
value = supplied or DEFAULT                # DEFAULT when supplied is falsy

if / elif / else

Diagram: how an if-elif-else chain selects a single branch

The conditional expression

Diagram: a conditional statement compared with a conditional expression

label = "empty" if not rows else f"{len(rows)} rows"

Guard clauses instead of deep nesting

Diagram: nested conditionals compared with guard clauses

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

An everyday analogy

A doorman with a list.

The doorThe code
”Are you on the list?”A condition
Turning someone away immediatelyA guard clause
Checking the list only if they have IDShort-circuit evaluation
One queue, first match winsif / elif
”Anyone else, this way”else
Someone with no bag at allA falsy empty container

Examples in practice

Flowchart: an if/elif/else path that classifies a model prediction into accept, review, or reject


Implications: security, privacy, performance, scalability, and cost

Diagram: failing open compared with failing closed in an authorisation check


Alternatives: free, open source, and commercial

Diagram: an elif chain compared with a dictionary lookup

ApproachWhere it fits
if / elif / elseThe default, for a handful of cases
A dictionary lookupMapping a value to a result, instead of a long chain
match / caseStructural patterns, from Python 3.10
Guard clausesValidation, and any function with several rejections
A named predicate functionWhen the condition needs a comment to explain it
PolymorphismWhen the branch is really “what kind of thing is this”

TermWhat it actually is
Truthy / falsyHow a non-boolean is judged in a condition
Short-circuitStopping evaluation once the answer is known
Chained comparisona < b < c, evaluating b once
Guard clauseAn early return handling an exceptional case
TernaryA conditional that produces a value
is vs ==Same object versus equal value

When to use it — and when not to

Diagram: a complex inline condition compared with a named predicate function


The AI connection

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 doingCommand
Explore truthinessbool(0), bool(""), bool([]), bool([0])
Find the trapif 0: versus if 0 is not None:
See short-circuitingFalse and print("ran") — nothing prints
See what or returns0 or "default" and "" or None
Chain a comparison0 <= x < 10
Flatten with guardsRewrite a 4-level nested function
Replace a chainA 6-way elif becomes a dictionary lookup

Expected output

False False False True
skipped
default None
True

Validate your work

Troubleshooting

Common mistakes


Practice assignment


Extension challenge


Quiz

Q1. Which of the following is NOT one of Python's falsy values?

  1. The empty string ""
  2. The string "0"
  3. The integer 0
  4. 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?

  1. It compares 0.0 <= score, then compares the resulting boolean to 1.0
  2. It is a syntax error; Python does not allow two comparisons in one expression
  3. It is a chained comparison meaning score is between 0.0 and 1.0 inclusive, evaluating score once
  4. 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?

  1. It does not matter; `and` evaluates both sides regardless
  2. Python evaluates `and` from right to left, so the second side runs first
  3. The order only affects performance, never correctness
  4. 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?

  1. One of their operands, not necessarily a bool
  2. Always the literal value True or False
  3. The integer 1 for true and 0 for false
  4. 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?

  1. category becomes "high" because 0.95 >= 0.9
  2. category is "medium" — the first true branch wins
  3. Both branches run, so category ends up "high"
  4. 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?

  1. `not verified and score < 0.9`
  2. `verified or score >= 0.9`
  3. `not verified or score < 0.9`
  4. `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`?

  1. The ternary evaluates both branches and returns both values
  2. They are identical; the ternary is only shorter
  3. The ternary can run multiple statements in each branch
  4. 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:`?

  1. 0.1 is not exact in binary, so the sum differs; use a tolerance
  2. Floats are always equal to each other, so the test is meaningless
  3. The `==` operator does not work on floats at all
  4. 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


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.