Python Control Flow — Explain Like I'm 5
The Traffic Light of Programming
Imagine you’re a robot following a recipe. Most of the time, you do step 1, then step 2, then step 3 — in order. But sometimes the recipe says “if the onions are burnt, throw them out and start over.” Or “stir the sauce until it thickens.”
Those decision-making moments are control flow — code that says “don’t just keep going in a straight line, check something first and decide what to do.”
Decisions: “If This, Do That”
The most basic decision in Python:
temperature = 35
if temperature > 30:
print("It's hot! Wear sunscreen.")
Python checks: is temperature greater than 30? Yes (it’s 35), so it runs the indented line. If the temperature was 20, that line would be skipped entirely.
You can add an “otherwise”:
if temperature > 30:
print("It's hot!")
else:
print("Bring a jacket.")
And “otherwise, check this other thing”:
if temperature > 30:
print("Hot day")
elif temperature > 15:
print("Nice day")
else:
print("Cold day")
Python checks conditions in order and runs the first one that’s true, then skips the rest.
Repetition: Doing the Same Thing Many Times
Sometimes you want to do something 100 times, or once for every item on a list. You don’t want to write the same line 100 times — that’s what loops are for.
for number in [1, 2, 3, 4, 5]:
print(number)
This prints each number, one at a time. Python goes through the list, sets number to each item, and runs the indented code for each one.
You can also repeat something while a condition is true:
lives = 3
while lives > 0:
print("You're still in the game!")
lives = lives - 1
This keeps printing until lives runs out.
The Safety Rule
Every while loop needs to eventually become false, or it runs forever. Programmers call that an “infinite loop” and it freezes your program. Always make sure something in the loop will eventually make the condition false.
One Thing to Remember
Control flow is how your code makes decisions (
if) and repeats tasks (for,while). Without it, a program can only do things in one fixed order — which isn’t very useful.
See Also
- Python Async Await Async/await helps one Python program juggle many waiting jobs at once, like a chef who keeps multiple pots moving without standing still.
- Python Basics Python is the programming language that reads like plain English — here's why millions of beginners (and experts) choose it first.
- Python Booleans Make Booleans click with one clear analogy you can reuse whenever Python feels confusing.
- Python Break Continue Make Break Continue click with one clear analogy you can reuse whenever Python feels confusing.
- Python Closures See how Python functions can remember private information, even after the outer function has already finished.