Lesson 9 · 9 of 20
For loops and range() · Python
Loop over letters and numbers with for and range() in Python: a times table, Olympic years, a running total and break to stop early.

for runs its block once for each item of a sequence. A string is a sequence of letters, so for letter in "PYTHON": goes round six times, once per letter. end=" " makes print() finish with a space instead of a new line, and the empty print() afterwards closes the line.
range() produces numbers. range(1, 6) gives 1, 2, 3, 4 and 5: the end is not included. With it you can print the 7 times table without writing the same print() five times.
A third number sets the step: range(2024, 2036, 4) counts in fours and gives the years of the Summer Olympics.
A very common pattern is accumulating: total starts at 0 and each round adds n to it. When the loop ends, it holds the sum from 1 to 100: 5050.
break leaves the loop at once. The last for could go up to 99, but it stops as soon as it finds the first number that is a multiple of both 6 and 8: 24.
Code · main.py
# for repeats a block once for each item of a sequence.for letter in "PYTHON": print(letter, end=" ") # end=" " stays on the same lineprint()# range(1, 6) gives 1, 2, 3, 4, 5 (the end is not included).number = 7for i in range(1, 6): print(f"{number} x {i} = {number * i}")# range(start, stop, step): the Summer Olympics, every 4 years.for year in range(2024, 2036, 4): print("Olympic year:", year)# Add up as you go.total = 0for n in range(1, 101): total += nprint("1 + 2 + ... + 100 =", total)# break leaves the loop as soon as it finds what it wants.for n in range(1, 100): if n % 6 == 0 and n % 8 == 0: print("First number divisible by 6 and 8:", n) breakOutput · python3 main.py
P Y T H O N 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 Olympic year: 2024 Olympic year: 2028 Olympic year: 2032 1 + 2 + ... + 100 = 5050 First number divisible by 6 and 8: 24
Key points
for x in sequence:goes round once per item.range(a, b)goes fromatob - 1;range(n)from 0 ton - 1.range(a, b, step)jumps bystep.breakends the loop early.- Use
forwhen you know how many rounds; usewhilewhen it depends on a condition.
Exercise
Print the 9 times table from 1 to 10 and, separately, add up only the even numbers from 1 to 100 using range() with a step of 2.