Python Tutorial: Control Flow
Make your program smart. Teach it to make decisions with if, elif, and else.
Your program needs to make decisions
Every useful program makes decisions. Is the user old enough? Did they pass the exam? Is the item in stock?
`if`, `elif`, and `else` let your program choose between paths. Twelve steps.
What you'll learn in this Python control flow tutorial
This interactive Python tutorial has 11 hands-on exercises. Estimated time: 20 minutes.
- Making decisions — So far, your programs have been like a train on a straight track — they run the same code every single time.
- else — the backup plan — An `if` by itself only acts when the condition is True. But what happens when it's False?
- elif — more than two options — What if passing or failing isn't enough? You want letter grades.
- Comparison operators — Conditions compare things. Here are all the comparison operators:
- Nested if — decisions inside decisions — An `if` block can contain another `if` inside it. The inner check only runs when the outer condition is already True.
- Indentation is everything — Python uses indentation (spaces) to define which code belongs inside which block. Not curly braces. Not semicolons. **Sp…
- One-line if — the ternary — Sometimes you have a simple if/else that fits on one line. Python has a shortcut:
- pass — the intentional no-op — Python requires at least one statement inside every block. If you want a block that deliberately does nothing yet, use `…
- match — Python's switch — Python 3.10 added `match` — a clean way to handle many exact values without a long if/elif chain:
- Hunt the bugs — This program has **four** bugs. Hunt them all down:
- Build an age checker — No starter code — write this completely from scratch.
Python Control Flow concepts covered
- Your program needs to make decisions