Repeat work without repeating code. Loop over sequences with for, count with range(), loop on a condition with while, and steer loops with break and continue.
By the end of today you can
- Loop over strings and lists with for
- Generate number sequences with range()
- Repeat while a condition is true with while
- Exit early with break and skip ahead with continue
- Use the accumulator pattern and enumerate()
Imagine printing a greeting for 100 students by writing 100 print lines. Loops let you write the work once and repeat it as many times as needed.
for: once per item
A for loop takes each item of a sequence in turn and runs the indented block with it:
range(): counting
range() produces a sequence of numbers on demand. Like slicing, the stop value is not included.
| Call | Produces |
|---|---|
range(5) | 0, 1, 2, 3, 4 |
range(2, 6) | 2, 3, 4, 5 |
range(0, 10, 3) | 0, 3, 6, 9 |
range(5, 0, -1) | 5, 4, 3, 2, 1 |
The accumulator pattern
Start with an empty total, then add to it on every pass. This is one of the most common patterns in programming:
enumerate(): the index and the item
while: repeat until a condition is false
Use while when you don't know how many repetitions you need, only when to stop:
break and continue
breakleaves the loop immediately.continueskips the rest of this pass and moves on to the next item.
Nested loops
A loop inside a loop runs the inner loop completely for every pass of the outer one:
Recap
for item in sequence:runs once per item;range()gives you numbers to loop over.while condition:repeats until the condition isFalse. Make sure something changes!breakexits a loop;continueskips to the next pass.- Accumulate totals with
total += x; useenumerate()when you need positions.
Knowledge check
Test what you learned
5 questions · pick an answer to see if you're right
- 1
Which numbers does range(2, 8, 2) produce?
- 2
How many times does the body of "for i in range(5):" run?
- 3
What does continue do inside a loop?
- 4
When should you prefer a while loop over a for loop?
- 5
What is a common cause of an infinite while loop?
Finished today's lesson?