Skip to main content

Control Flow

Conditional Statements

Complete lesson for Conditional Statements using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Python data structures and OOP where relevant.

L1

Basics — Conditional Statements

Section: Control Flow. Branch with if/elif/else, nested decisions, ternary expressions, and structural pattern matching.

if / elif / else

  • if condition: runs its suite when the condition is truthy.
  • elif chains alternatives; the first matching branch wins.
  • else runs when no prior branch matched; it is optional.
  • Colon and indented suite are required; empty suites use pass.
score = 82
if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
elif score >= 60:
    grade = "C"
else:
    grade = "D"
print(grade)
# Output:
# B

Syntax: if, if-else, elif ladder & nested if

Decision statements choose different Python blocks when a condition is truthy. Each form below shows the syntax and a short example. Indentation and the trailing colon define each suite.

if

Syntax

if condition:
    # statements

Example

age = 20
if age >= 18:
    print("adult")
# Output:
# adult

if-else

Syntax

if condition:
    # true branch
else:
    # false branch

Example

n = 7
if n % 2 == 0:
    print("even")
else:
    print("odd")
# Output:
# odd

elif ladder

Syntax

if condition_1:
    # ...
elif condition_2:
    # ...
else:
    # ...

Example

score = 82
if score >= 90:
    grade = "A"
elif score >= 75:
    grade = "B"
else:
    grade = "C"
print(grade)
# Output:
# B

nested if

Syntax

if condition_1:
    if condition_2:
        # both true

Example

logged_in = True
has_items = True
if logged_in:
    if has_items:
        print("checkout")
# Output:
# checkout
  • if: run a block only when the condition is true.
  • if-else: choose between two opposite outcomes.
  • elif ladder: check multiple ordered conditions (grades, fares).
  • nested if: a second check that depends on the first (login then checkout).

Boolean conditions

  • Conditions are expressions: comparisons, and/or/not, membership, or any object’s truthiness.
  • Keep conditions readable; extract complex checks into named booleans.
  • Prefer positive conditions when nesting becomes deep.
  • Avoid assignment with = in conditions; use := only when the walrus helps.
age = 20
has_id = True
if age >= 18 and has_id:
    print("allowed")
else:
    print("denied")
# Output:
# allowed

Nested conditionals

  • An if suite may contain another if — nest only when necessary.
  • Deep nesting is a smell; flatten with elif, early continues, or helper functions later.
  • Align else with the correct if — indentation decides pairing.
  • Comment rare branches so future readers know they are intentional.
temp = 36
if temp >= 30:
    if temp >= 40:
        print("extreme heat")
    else:
        print("hot")
else:
    print("mild or cold")
# Output:
# hot

Conditional expression (ternary)

  • Syntax: value_if_true if condition else value_if_false.
  • It is an expression — usable inside print, assignment, return.
  • Keep it short; nested ternaries become unreadable fast.
  • Not a full replacement for if blocks with multiple statements.
n = 4
parity = "even" if n % 2 == 0 else "odd"
print(parity)
print("yes" if n > 0 else "no")
# Output:
# even
# yes

Truthy checks without comparisons

  • if items: runs when the list is non-empty.
  • if name: fails for empty strings.
  • Use explicit if x is None: when None must be distinguished from other falsy values.
  • Be careful with numbers: if count: is false for 0, which may or may not be intended.
items = [1]
name = ""
if items:
    print("has items")
if not name:
    print("missing name")
# Output:
# has items
# missing name

match / case basics (3.10+)

  • match subject: compares against case patterns in order.
  • Literal patterns match equality: case 200:.
  • Wildcard _ matches anything and should be last if used as default.
  • case suites do not fall through — unlike C switch.
status = 404
match status:
    case 200:
        msg = "ok"
    case 404:
        msg = "not found"
    case _:
        msg = "other"
print(msg)
# Output:
# not found

Python match / case — structural pattern matching

From Python 3.10, match / case branches on a subject’s value or shape. Patterns are tried in order; the first match runs and stops — there is no fall-through like C switch. Use case _ as a default.

Python match case infographic: how match tries case patterns in order with no fall-through, example matching HTTP status codes with literals, or-patterns, and wildcard default, plus tip cards for literal, or-pattern, and case underscore.
Python match / case — literals, or-patterns, and _ default
  • Literals: case 200: matches equality.
  • Or-patterns: case 401 | 403: share one branch.
  • Wildcard: case _: catches everything left (put last).
  • vs if: use match for discrete values/shapes; keep if for simple true/false checks.

match with capture and guards

  • Capture patterns bind names: case [x, y]:.
  • Guards add if conditions: case n if n > 0:.
  • Sequence and mapping patterns destructure structures.
  • Prefer match when branching on shape; prefer if for simple boolean thresholds.
point = (0, 5)
match point:
    case (0, 0):
        print("origin")
    case (0, y):
        print("y-axis", y)
    case (x, 0):
        print("x-axis", x)
    case (x, y):
        print("point", x, y)
# Output:
# y-axis 5

Guard clauses style

  • Handle invalid cases first and return/skip early (in functions) to keep the happy path unindented.
  • In scripts without functions yet, print and structure with if not ok: ... else: ....
  • Clear error messages in the guard branch help debugging.
  • This style reduces nested pyramids of doom.
username = "ada"
if not username:
    print("empty")
elif len(username) < 3:
    print("too short")
else:
    print("ok", username)
# Output:
# ok ada

Choosing if vs match

  • Use if/elif for numeric ranges and combined boolean logic.
  • Use match for discrete literals, enums, and structured data shapes.
  • Do not rewrite every if into match — pick the clearer tool.
  • Both can coexist in one function when appropriate.
SituationPrefer
score >= 90 thresholdsif / elif
HTTP status codesmatch literals
(x, y) point kindsmatch sequence
flag1 and flag2if with and
L2

Advanced — Conditional Statements

Pattern matching details

  • Or-patterns: case 401 | 403: share a branch.
  • AS-patterns bind the whole subject: case [x, y] as point:.
  • Class patterns match attributes (useful with dataclasses later).
  • Patterns are not arbitrary expressions — learn the pattern grammar from PEP 634.
code = 403
match code:
    case 401 | 403:
        print("auth problem")
    case 404:
        print("missing")
    case _:
        print("other")
# Output:
# auth problem

Avoiding boolean traps

  • Do not write if x == True:; use if x: or if x is True: only when you need exact True.
  • Do not compare to None with == in style guides that prefer is.
  • When checking containers, decide if None and [] should share a branch.
  • Log the actual value when a branch is surprising during debugging.

Decision tables

  • Complex rules can map keys to results with dicts instead of long elif chains.
  • Example: actions.get(command, default).
  • Combine dict dispatch with small functions for scalable CLIs.
  • Still validate unknown keys explicitly when security matters.
op = "square"
n = 6
actions = {
    "double": n * 2,
    "square": n * n,
    "negate": -n,
}
print(actions.get(op, "unknown"))
# Output:
# 36

Exhaustiveness mindset

  • When matching enums or status codes, include _ or ensure all cases are covered.
  • Type checkers can warn on non-exhaustive matches with certain patterns.
  • Failing loudly on unexpected values beats silent wrong else behavior.
  • In libraries, raise ValueError for unexpected categories.
L3

Tricky Interview Points

Q1) What is the syntax of an if statement?

Answer if condition: followed by an indented suite; optional elif/else branches.

Q2) Does Python have a switch statement?

Answer Historically no. Python 3.10 added match/case for structural pattern matching, which covers many switch use cases and more.

Q3) What is a ternary conditional expression?

Answer a if condition else b evaluates to a when condition is true, otherwise b.

Q4) How do you write multiple alternatives?

Answer Use elif chains, match cases, or dict dispatch depending on clarity.

Q5) What is a guard in match?

Answer An if clause after a pattern, e.g. case n if n > 0:, that must also succeed.

Q6) Do match cases fall through?

Answer No. Only one case body runs. Use or-patterns for shared bodies.

Q7) How do you check for an empty list?

Answer if not my_list: or if len(my_list) == 0:. The first is idiomatic.

Q8) What happens if no branch matches and there is no else?

Answer Execution continues after the if/match; nothing special runs.

Q9) Why avoid nested ternaries?

Answer They are hard to read and easy to mis-parenthesize; use normal if/elif instead.

Q10) How do you match a sequence of length 2?

Answer case (x, y): or case [x, y]: depending on the subject type/pattern rules.

Q11) What is the wildcard pattern?

Answer case _: matches anything without binding a name; typically used as a default.

Q12) When is dict dispatch better than elif?

Answer When mapping discrete keys to values/callables and the mapping may grow or be configured.

L4

Simple Programs

Grade ladder

for score in [95, 82, 67, 50]:
    if score >= 90:
        g = "A"
    elif score >= 75:
        g = "B"
    elif score >= 60:
        g = "C"
    else:
        g = "D"
    print(score, g)
# Output:
# 95 A
# 82 B
# 67 C
# 50 D

Ternary labeling

for n in range(-1, 3):
    label = "pos" if n > 0 else "zero" if n == 0 else "neg"
    print(n, label)
# Output:
# -1 neg
# 0 zero
# 1 pos
# 2 pos

match HTTP-like codes

for status in [200, 301, 404, 500]:
    match status:
        case 200:
            print(status, "OK")
        case 301 | 302:
            print(status, "redirect")
        case 404:
            print(status, "missing")
        case _:
            print(status, "error")
# Output:
# 200 OK
# 301 redirect
# 404 missing
# 500 error

match points

points = [(0, 0), (0, 3), (2, 0), (4, 5)]
for p in points:
    match p:
        case (0, 0):
            print(p, "origin")
        case (0, y):
            print(p, "y", y)
        case (x, 0):
            print(p, "x", x)
        case (x, y) if x == y:
            print(p, "diagonal")
        case (x, y):
            print(p, "point")
# Output:
# (0, 0) origin
# (0, 3) y 3
# (2, 0) x 2
# (4, 5) point

Guard-style validation

samples = ["", "ab", "ada"]
for username in samples:
    if not username:
        print("empty")
        continue
    if len(username) < 3:
        print(username, "too short")
        continue
    print(username, "ok")
# Output:
# empty
# ab too short
# ada ok

Dict dispatch calculator

def apply(op, a, b):
    ops = {
        "add": a + b,
        "sub": a - b,
        "mul": a * b,
        "div": a / b if b != 0 else None,
    }
    return ops.get(op, "unknown")

print(apply("add", 9, 4))
print(apply("div", 9, 0))
print(apply("pow", 2, 3))
# Output:
# 13
# None
# unknown
L5

Problem Solving Tricks

  • Name intermediate booleans: is_adult = age >= 18 before the if.
  • Put the happy path last after guard clauses for readable scripts/functions.
  • Use match or-patterns instead of duplicating case bodies.
  • Keep ternary expressions on one line under ~40 characters of logic.
  • For ranges, elif ladders beat nested if pyramids.
  • In match, put specific patterns before _.
  • Use continue/break in loops with guards to avoid deep nesting.
  • When teaching, draw a flowchart of branches before coding.
  • Fail fast on unexpected categories with an explicit final else/case _ that errors.
L6

Practice Programs List

  1. Write a BMI category classifier with if/elif/else for fixed height/weight constants.
  2. Convert a day number 1–7 into a weekday name using match.
  3. Rewrite a nested if into guard-style with early prints.
  4. Use a ternary to choose "pass"/"fail" from a score.
  5. Match a list of length 0, 1, 2, and longer with sequence patterns.
  6. Implement rock-paper-scissors outcome using match on a tuple (you, cpu).
  7. Build dict dispatch for four string commands and a default.
  8. Show a case with a guard case n if n % 2 == 0:.
  9. Intentionally omit else and observe what prints when no condition matches.
  10. Refactor messy nested ternaries into elif; compare readability.
  11. Write conditions distinguishing None, 0, and "" with separate messages.