The for loop

Loops, lesson 2 of 5

🔁 Loops, lesson 2 of 5

The for loop

Visit every item in a sequence and total things up as you go.

9 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

A for loop runs its body once for every item in a sequence, such as the characters of a string. Each time around, the loop variable holds the next item. No counter to manage, and no risk of looping forever.

Example

Team cheer

Change team to your favourite team's name.

You can also loop over a list: values in square brackets, separated by commas. (Lists get a whole module next.)

A very common pattern is the accumulator:

  1. Create a variable before the loop (total = 0).
  2. Update it inside the loop (total += price).
  3. Use it after the loop.
Example

Shopping receipt

Add another price to the list and run it again.

Example

Count and track the best

Two accumulators in one loop: a counter and a running maximum. Try changing the "hot" threshold to 20.

Quiz

What does this print?

Exercise

Count the vowels

Loop over sentence and count how many vowels (a, e, i, o, u, upper or lower case) it contains. Store the count in vowels.

Quiz

What does this print?