Stewdent.eu
▾

For Loops

A for loop repeats a block of code a known number of times, or once for each item in a collection. It is the most common type of loop in Python.

Last updated: 31 January 2026

★★☆☆☆ Level 2computingprogrammingloopsforiteration4 min read

Report an error

A for loop repeats a block of code for each item in a sequence. Unlike a while loop — which runs until a condition changes — a for loop works through a collection of values one by one, automatically stopping when it runs out of items. This makes it ideal when you know exactly how many times you want to repeat.

Looping with range()

The built-in range() function generates a sequence of numbers, making it perfect for counting loops:

for i in range(5):
    print(i)

Output:

0
1
2
3
4

range(5) produces the numbers 0, 1, 2, 3, 4 — five numbers starting from zero. The loop variable i takes each value in turn.

Customising range()

range() accepts up to three arguments:

CallProduces
range(5)0, 1, 2, 3, 4
range(2, 8)2, 3, 4, 5, 6, 7
range(0, 10, 2)0, 2, 4, 6, 8
range(10, 0, -1)10, 9, 8, 7, 6, 5, 4, 3, 2, 1
# Count down from 5
for i in range(5, 0, -1):
    print(i)
print("Blast off!")
Note

The third argument to range() is the step — how much to add each time. A negative step lets you count backwards. range(start, stop, step) never includes the stop value itself.

Looping Over a List

A for loop can iterate directly over the items in a list — no range needed:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

The loop variable fruit automatically takes the value of each item in order.

Looping Over a String

Strings are also sequences, so you can loop through every character:

word = "hello"
for letter in word:
    print(letter)
Tip

Choose a meaningful name for your loop variable. If you are iterating over a list of students, call the variable student, not i or x. Your code will be much easier to read.

Accumulating Results

One of the most useful loop patterns is building up a result step by step:

numbers = [4, 7, 2, 9, 1]
total = 0
for num in numbers:
    total += num
print(f"Sum: {total}")   # Sum: 23

break and continue

  • break — exits the loop immediately.
  • continue — skips the rest of the current iteration and moves to the next one.
for i in range(10):
    if i == 6:
        break           # stop completely at 6
    if i % 2 == 0:
        continue        # skip even numbers
    print(i)
# Prints: 1 3 5
Warning

Overusing break and continue can make loops hard to follow. Use them only when they genuinely simplify the logic.

Practice Problems

What does range(1, 10, 3) produce? List all the values.

Show answer
1, 4, 7. The sequence starts at 1, adds 3 each time, and stops before reaching 10.

Write a for loop that prints the square of every number from 1 to 5.

Show answer
for i in range(1, 6): print(i ** 2) — this prints 1, 4, 9, 16, 25 on separate lines.