Python 101Free
CONTROL FLOW

Conditionals

Choosing which branch of code to run.

SECTION 01

if, elif, else

An if statement runs its block when the condition is truthy. elif chains additional conditions, each tested only if all the previous ones were false. else is the catch-all that runs if none of the prior conditions matched.

Only one branch ever runs. Once a condition is true, Python skips the rest of the chain. This is why ordering matters: put the narrowest case first, the broadest last.

Python has no switch statement in the traditional sense. The match statement added in 3.10 covers some of that ground but for plain branching, an if / elif / else chain is what you write.

python
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"
SECTION 02

Guard clauses and ternary

Deeply nested if chains are hard to read. The guard clause pattern flips the logic: handle the failure cases up front with early returns, and let the happy path fall out at the bottom of the function with no extra indentation.

For very short branches, the conditional expression is more compact. x if cond else y evaluates to x when cond is true, otherwise y. It works inline in any expression, including function arguments and list comprehensions.

Use the ternary form for one-line value choices. Reach for guard clauses whenever a function has more than two levels of indentation. Both are about making the code's shape match the code's intent.

python
def discount(user):
    if not user:           # guard
        return 0
    if user.banned:        # guard
        return 0
    return user.tier * 5   # happy path, no nesting

label = "even" if n % 2 == 0 else "odd"
NEXT →
Loops