Control Flow
Lesson 2 of 8
2Control Flow
The big pictureHow a program makes decisions with conditions and repeats work with loops, when while beats for, and the off-by-one traps.
What the picture shows: The variable i takes 0, then 1, then 2, and for each value the condition asks its question and the answer lights up: even or odd.
Map of this part
The concepts in order, click any one to jump to it:
Two ways into the same idea
A program without conditions is a train on one track. A condition is a junction: "if the signal is red, stop; otherwise go on". A loop is a roundabout that sends the train round again: "repeat ten times" or "keep going while there are passengers". With these two pieces a program can do anything.
if/elif/else choose a branch by a boolean. for walks a known collection such as range(10), and while repeats while a condition holds and can loop forever if it never changes. Watch for off-by-one errors: range(1, 10) excludes 10. break leaves the loop and continue skips one turn.
Before You Start
📦The variable
You know how to keep a value under a name and print it.
⚖️True or false
Any comparison like 5 > 3 answers yes or no.
The Core Idea
So far a program runs its lines top to bottom. Here you learn how it decides and how it repeats, with three small examples.
1Let the program decide
if means exactly that. After it comes a condition, then a colon, then the lines that run when the condition holds. The indentation before print is not decoration; it tells Python that line belongs to the condition.
temperature = 31
if temperature > 30:
print("hot")
else:
print("mild")
else runs when the condition does not hold. Change 31 to 20 and run again to see the other branch.
2Repeat a known number of times
for repeats the indented lines. range(1, 4) gives the numbers 1 to 3; the last number is left out. On each round number takes the next value.
for number in range(1, 4):
print("round", number)
print("loop finished")
The final line is not indented, so it sits outside the loop and runs once after the loop ends.
3Add up while repeating
The most common pattern in all of programming: a variable that starts at zero and a loop that adds to it each round. Here we add prices.
total = 0
for price in [12, 8, 30]:
total = total + price
print("total so far:", total)
print("final:", total)
Follow how total changes after each round. That is tracing, the best way to understand any loop: write the variable values for each round by hand.
if or for line, or the indentation on the line after it. The message is SyntaxError or IndentationError, and both mean the shape is incomplete, not the logic.How It Works, Step by Step: How Python runs a for loop
It works out range(3), giving 0, then 1, then 2.
It puts the first value into the variable i.
It runs the indented lines under the loop, including the condition.
It goes back to the top with the next value until the values run out.
Going deeper
Control flow is what makes a program "think" instead of always executing the same lines in the same order: making decisions with conditions, and repeating work with loops.
Diagram 3, Python checks conditions in order from top to bottom, executes only the first block whose condition is true, then completely ignores the rest.
if / elif / else
A chain of mutually exclusive decisions: only one branch executes. elif means "if the previous condition wasn't met, try this one".
while
Repeats as long as the condition is true, the number of iterations is not known in advance. Common pitfall: forgetting to update the variable causes an infinite loop.
for + range()
Repeats a known number of times or walks through elements of a sequence. range(a, b) includes a and excludes b.
| while | for | |
|---|---|---|
| When to use it | Unknown iteration count (waiting for an event) | Known iteration count or traversing a sequence |
| Common pitfall | Infinite loop if you forget to update the condition | An off-by-one error with range |
## Example: classifying a student's grade (if/elif/else)
score = 82
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(grade) # B
## Example: multiplication table with a for + range loop
n = 4
for i in range(1, 6): # 1..5 (6 excluded)
print(f"{n} x {i} = {n * i}")
## Example: countdown with a while loop
countdown = 3
while countdown > 0:
print(countdown)
countdown -= 1 # without this line: infinite loop
print("Go!")
range(5) gives 0,1,2,3,4, five elements starting from zero. This is the most common off-by-one mistake for people coming from other languages.
Check your understanding: how many times does the statement print in for i in range(2, 10, 3): print(i)?
Three times: it prints 2, then 5, then 8 (each time adding the step of 3, stopping before reaching or exceeding 10).
Worked example
for n in range(1, 21):, inside it if n % 3 == 0: print("Fizz") and else: print(n). Note 21, not 20, because range stops before its last number.Myth vs Reality
| Myth | Reality |
|---|---|
| Every if needs an else. | else is optional; write it only when there is something to do when the condition fails. |
range(5) gives 1 to 5. | It gives 0 to 4: five numbers starting at zero and stopping before five. |
| while and for are the same, pick either. | for is for a known count or a collection to walk, while is for when you do not know when to stop. A while whose condition never changes never ends. |
Try it yourself
You write for i in range(3): then an indented print(i). What is printed?
range(3) starts at zero and stops before 3, giving 0, 1 and 2. Three numbers, but starting at zero, not one. You will meet this rule everywhere in Python: counting starts at zero.
Quick Review Flashcards
Check Your Understanding
How many times does for i in range(2, 6) run?
Four times: 2, 3, 4 and 5.
When do you pick while over for?
When you do not know the count beforehand, like "keep going until the user types quit".
What is elif for?
It checks a second condition only when the first fails, so only one branch of the chain runs.
Resources for this part
Sorted by kind: start with the official docs when you want the precise reference, or with an article or video when you want the explanation first.
Resources for this lesson
Grouped by type. Start with the official docs for precision, or an article or video for the explanation.
Official docs1
Tools2
Done with this lesson?
Sign in to save your progress.