Decisions and loops
for loops and range
Goal: Iterate over ranges and sequences · 9 min
A for loop goes through the elements of a sequence one by one:
for letter in "abc":
print(letter)
range produces number sequences:
range(5)→ 0, 1, 2, 3, 4 (5 is excluded)range(2, 6)→ 2, 3, 4, 5range(10, 0, -3)→ 10, 7, 4, 1
Use for when you know what to iterate over; use while when you repeat until a condition changes.
Worked example: Multiplication table row
- range(1, 6) gives 1 … 5.
- Each value is multiplied by 7.
- end=" " keeps everything on one line.
for i in range(1, 6):
print(i * 7, end=" ")Output:
7 14 21 28 35