πŸ”
CodingπŸ”¬ Ages 11-13Beginner 11 min read

Python For Loops

Learn Python for loops: loop over lists and strings, use range() to count, build running totals with an accumulator, and choose the right loop. Runnable code, a worked example and a quiz.

Key takeaways

  • A for loop repeats a block of code once for each item in a sequence
  • The loop variable holds the current item on each pass through the loop
  • range(n) counts from 0 up to but not including n
  • range(start, stop, step) lets you control where counting begins, ends and how big each jump is
  • An accumulator variable, updated inside the loop, builds up a total or a result

Repeating without copy-paste

Computers are brilliant at doing the same thing over and over without getting bored. Suppose you want to print "Hello" five times. You could write five print lines, but what about a hundred times? A for loop lets you write the instruction once and tell Python how many times to repeat it.

If you've met loops and lists before, this lesson zooms in on the for loop specifically and the powerful range() function that drives it.

The shape of a for loop

A for loop walks through a sequence β€” a list, a string, or a range of numbers β€” and runs its body once for each item:

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

This prints:

apple
banana
cherry

Reading it line by line:

  • for fruit in [...]: starts the loop. fruit is the loop variable β€” a fresh name that holds one item at a time.
  • On the first pass fruit is "apple", on the second it's "banana", on the third it's "cherry".
  • The indented print(fruit) is the body, and it runs once per item.

The loop variable name is your choice; fruit just describes what it holds. Notice the colon at the end of the for line and the indentation of the body β€” Python uses indentation to know what's inside the loop.

Looping over a string

A string is a sequence of characters, so a for loop can walk through it letter by letter:

for letter in "cat":
    print(letter)

This prints c, then a, then t, each on its own line. On the first pass letter is "c", then "a", then "t". This is handy whenever you want to examine text one character at a time.

Counting with range()

Sometimes you don't have a list β€” you just want to repeat something a set number of times, or count. That's what range() is for:

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

This prints 0 1 2 3 4 (each on its own line). The key rule: **range(5) counts from 0 up to but not including 5.** So you get five numbers, starting at zero. Programmers often use i (short for "index") as the loop variable when counting.

To just repeat an action without using the number, ignore the loop variable:

for i in range(3):
    print("Hip hip hooray!")

This prints the cheer exactly three times.

Controlling range: start, stop, step

range() can take up to three numbers: where to start, where to stop (exclusive), and the step between values.

for n in range(1, 6):       # start at 1, stop before 6
    print(n)                # 1 2 3 4 5

for n in range(0, 11, 2):   # start 0, stop before 11, step 2
    print(n)                # 0 2 4 6 8 10
  • range(1, 6) starts at 1 and stops before 6, giving 1 2 3 4 5.
  • range(0, 11, 2) jumps in steps of 2, giving the even numbers up to 10.

You can even count backwards with a negative step:

for n in range(5, 0, -1):
    print(n)                # 5 4 3 2 1
print("Lift off!")

This makes a neat countdown.

The accumulator pattern

One of the most useful loop techniques is building up a result with an accumulator β€” a variable you update on every pass. Here's how to add up a list of numbers:

numbers = [4, 8, 15, 16, 23]
total = 0

for n in numbers:
    total = total + n

print(total)   # 66

How it works:

  • total = 0 is set before the loop. This is crucial β€” if it were inside the loop it would reset every pass.
  • Each pass, total = total + n adds the current number to the running total.
  • After the loop visits all five numbers, total holds 4 + 8 + 15 + 16 + 23, which is 66.

The same pattern counts things, joins text together, or finds a largest value β€” just change what happens inside the loop.

Worked example: a times table

Let's build a clean program that prints the multiplication table for any number, using ideas from Python numbers and math along the way.

number = 7

print("The", number, "times table:")
for i in range(1, 11):
    answer = number * i
    print(number, "x", i, "=", answer)

How it works:

  1. number = 7 is the table we want.
  2. range(1, 11) produces 1 through 10 (stopping before 11), so the loop runs ten times.
  3. On each pass, answer = number * i calculates one row of the table, and print shows it as 7 x 1 = 7, 7 x 2 = 14, and so on up to 7 x 10 = 70.

By changing only the first line to number = 9, you instantly get the nine times table. That's the power of a loop: write the pattern once, reuse it for any value.

Try it yourself

Write a program that finds the sum of all even numbers from 1 to 20:

  • Create an accumulator: total = 0.
  • Loop with for n in range(2, 21, 2): so n takes the even values 2, 4, 6 ... 20.
  • Inside the loop, add each n to total.
  • After the loop, print total (the answer is 110).

Then change the step to count odd numbers instead, and see how the total changes. When you're ready for loops that don't count a fixed number of times, explore python while loops, which repeat based on a condition.

Quick quiz

Test yourself and earn XP

How many numbers does range(5) produce?

What is the first number produced by range(3)?

In `for letter in "cat":`, what does letter hold on the first pass?

What does range(2, 10, 2) produce?

Why must you create a total variable before the loop, not inside it?

FAQ

A for loop is best when you know how many times to repeat, or when you want to go through every item in a list or string. A while loop repeats as long as a condition stays True, which suits situations where you don't know the number of repetitions in advance, like 'keep asking until the user types quit'. For counting and going through sequences, the for loop is usually the clearer choice.

range uses an 'up to but not including' rule. range(5) gives 0, 1, 2, 3, 4 β€” five values. This pairs neatly with the fact that Python counts list positions starting at 0, so range(len(my_list)) lines up exactly with every valid position in the list. Once you get used to it, the off-by-one feeling disappears.