for i in ...:range() — counting from here to there, with a step
You would never hand-write "1, 2, 3, ... 100". Neither should your code. A for loop runs the same block once for every item in a sequence.
for i in range(5):
print("Hello!")
# Prints "Hello!" five times — no copy-paste.
for loop, part by part
Four pieces: the keyword for, a loop variable, the keyword in, and something to loop over. The colon and indentation mark the body.
for i in range(3):
print(i)
# Output:
# 0
# 1
# 2
i takes each value in turn — first 0, then 1, then 2. You pick the name; i is just convention.
range()Starts at 0, stops before 5.
From 2, stops before 6.
Counts up by 2 each time.
range always stops one short of the stop value. To count 1 through n, write range(1, n + 1).
Set up a variable before the loop, then update it inside the loop. After the loop ends, it holds the answer.
total = 0 # 1. set up BEFORE the loop
for i in range(1, 6): # i = 1, 2, 3, 4, 5
total = total + i # 2. update INSIDE the loop
print(total) # 3. use it AFTER → 15
0 → 1 → 3 → 6 → 10 → 15.total += i is a shortcut for the same thing.
The loop variable isn't just for show — you can do math with it on every pass.
n = 7
for i in range(1, 4): # i = 1, 2, 3
print(f"{n} x {i} = {n * i}")
# Output:
# 7 x 1 = 7
# 7 x 2 = 14
# 7 x 3 = 21
Each trip through the loop produces exactly one line. Ten trips, ten lines. This is how you print a table, a menu, or a countdown.
for i in range(3, 0, -1): # 3, 2, 1 — step DOWN
print(f"{i}...")
print("Lift off!")
# 3...
# 2...
# 1...
# Lift off!
A loop, a range, and an accumulator — the exact recipe for today's Problem 1.
def sum_to_n(n):
total = 0 # initialise the accumulator
for i in range(1, n + 1): # 1, 2, ..., n
total += i # add each number
return total
print(sum_to_n(5)) # → 15
for · range(1, n+1) · accumulator · return — all of today in one function.
range(1, n) stops at n-1. To include n, write range(1, n + 1).range(5) is 0,1,2,3,4 — there is no 5.total = 0 before the loop → NameError. (For products, start at 1, not 0!)
sum_to_n(n) returns 1+2+...+n using a for loop + accumulator. No formula — that's the whole point.
times_table(n) prints lines 1–10 like 7 x 3 = 21.
students/<your-username>/D07_loops_and_tables.py. Full brief in lab/module_1_foundations/D07_loops_and_tables/problem.md. PR before 12:00.
for loop and count with range() in all three forms.
while loops + break / continue on Day 8.