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"
1 more section

Create a free account to access all sections and animations.

Create free accountAlready have an account? Sign in