🔁 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.
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:
- Create a variable before the loop (
total = 0). - Update it inside the loop (
total += price). - Use it after the loop.
Shopping receipt
Add another price to the list and run it again.
Count and track the best
Two accumulators in one loop: a counter and a running maximum. Try changing the "hot" threshold to 20.
What does this print?
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.
What does this print?