for Loops and range
Going through items one at a time, and counting.
5 minute read
Big idea
A for loop takes the items of a sequence one at a time. With range(), it's the easy way to repeat something a fixed number of times.
Looping over a string
for variable in sequence:
# runs once per item
for letter in "code":
print(letter.upper())output
C
O
D
ERun and edit it in the app.
Each round, letter refers to the next character. No counter to set up, no index to update, nothing to forget.
Watch it
range: counting
range makes a sequence of numbers to loop over:
range(5)→ 0, 1, 2, 3, 4 (five numbers, starting at 0)range(2, 6)→ 2, 3, 4, 5 (stops before 6)range(0, 20, 5)→ 0, 5, 10, 15 (a step of 5)range(5, 0, -1)→ 5, 4, 3, 2, 1 (counting down)
The stop number is never included — the same rule as slicing.
n = 7
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70Run and edit it in the app.
Adding things up
A loop plus a running total is one of the most common patterns in all of programming:
total = 0
for i in range(1, 101):
total += i
print(total)What does it print? Show the answer
5050Run and edit it in the app.
Off by one
for i in range(1, 5):
print(i)output
1
2
3
4
5Run and edit it in the app.
range(1, 5) stops before 5. To include 5, use range(1, 6).
Loops inside loops
A loop body can contain another loop. The inner loop runs completely for each round of the outer one:
for row in range(1, 5):
print("*" * row)output
*
**
***
****Run and edit it in the app.
for or while?
- You know the items or the count →
for. - You're waiting for something to happen →
while.
Which numbers does range(3, 9, 2) produce?
Think of it like
Dealing cards: "for each player at the table, deal one card." You don't count players by hand — you just go round until everyone has had a turn.
Key terms
- for loop — Runs its block once for each item in a sequence.
- range(start, stop, step) — A sequence of numbers;
stopisn't included. - Loop variable — The name that refers to the current item, like
i.
Check yourself
What does range(4) produce?
What does for c in "hi": print(c) print?
How do you count down from 5 to 1?