Python Essentials

Lesson 8 of 27

for loops

A loop does something repeatedly so you don't have to write it out by hand. The for loop is the workhorse: it runs a block of code once for each item in a collection. This is where programming starts to save you real work.

Looping over items

Python — Try it Yourself
Loading editor…
Output
Click Run to execute the code.

Read it like English: for each fruit in fruits, print a line. The variable fruit takes each value in turn — "apple", then "banana", then "cherry". The indented block runs once per item. You wrote the print once; it ran three times.

Looping a set number of times with range()

To repeat something N times, use range():

Python — Try it Yourself
Loading editor…
Output
Click Run to execute the code.

range(5) produces 0, 1, 2, 3, 4 — five numbers starting at 0. That's a Python habit worth burning in: counting starts at 0, and range(5) stops before 5. You can also give it a start and end:

Python — Try it Yourself
Loading editor…
Output
Click Run to execute the code.

Accumulating a result

A very common pattern: loop and build up a total:

Python — Try it Yourself
Loading editor…
Output
Click Run to execute the code.

Start a variable before the loop, add to it inside the loop, use it after. This "accumulator" pattern appears constantly — summing, counting, collecting.

The mistake beginners make

Forgetting that range(5) gives 0–4, not 1–5, and stops before the end number. If you want 1 to 5, write range(1, 6). This "off by one" confusion is so common it has a name: the off-by-one error.

Your turn

Python — Try it Yourself
Loading editor…
Output
Click Run to execute the code.

Your turn

  1. Loop over a list of your friends' names and greet each one.
  2. Use range() to print the numbers 1 to 10, then 10 down to 1 (hint: range can step by -1).
  3. Sum a list of numbers using the accumulator pattern (total = 0 before, total += each inside).

Key points

  • A for loop runs a block once for each item in a collection.
  • for item in collection: — item takes each value in turn.
  • range(n) gives 0 to n-1; range(a, b) gives a to b-1 — it stops BEFORE the end.
  • The accumulator pattern: start a total before the loop, add to it inside, use it after.

Q&A · 0

Enrol to ask questions and join the discussion.

No questions yet — be the first to ask.