for Loops and range()
You will repeat work over collections and number ranges with for loops.
Looping through items
for item in collection:
print(item)
for letter in 'cat':
print(letter)
colors = ['red', 'blue']
for color in colors:
print(color)
The first loop gives letter one character at a time. The second loop gives color each list item in order.
Range enumerate and zip
for number in range(2, 8, 2):
print(number)
for index, fruit in enumerate(['pear', 'plum'], start=1):
print(index, fruit)
for name, score in zip(['Ana', 'Bo'], [9, 7]):
print(name, score)
range(2, 8, 2) starts at 2, stops before 8, and steps by 2. enumerate() adds a position, while zip() pairs items from two collections until the shorter one ends.
Nested loops and else
for row in range(3):
line = ''
for column in range(row + 1):
line += '*'
print(line)
else:
print('Pattern complete')
For each row, the inner loop adds the right number of stars to line. The else block runs after the outer loop finishes normally. It does not run if that loop ends with break.
Key points
- A for loop visits items one at a time.
- range(start, stop, step) excludes the stop value.
- Use enumerate() when you also need positions.
- Use zip() to loop over paired collections.
- Nested loops repeat one loop inside another.
Worked example
Print the 7-times table rows for a school wall chart — one row per day of practice.
for day in range(1, 4):
print(day, "x 7 =", day * 7)
How it works, step by step
- range(1, 4) produces 1, 2, 3 — it stops BEFORE 4.
- Each pass binds day to the next number.
- The body computes and prints that day's row.
References & Further Reading
Related entries from PyLabs's own reference library.
- range() (Make a sequence of evenly spaced integers.)
- enumerate() (Pair each item with a counter.)
- zip() (Pair items from two or more iterables.)
Practice exercise
Not passed yetUse range(1, 6) in a for loop to print the numbers 1 through 5, one per line.
Expected output:
1
2
3
4
5
# Write your code below
Check yourself
for Loops and range() quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.