Python & data · Lesson 06
Repeat work with loops
Use for and while loops to repeat work and keep track of results.
- Iterate over a sequence
- Use range() and enumerate()
- Stop a loop safely
Helpful background: Understand variables and if statements.
Visit each item
A for loop takes each item from an iterable and runs an indented block. In this example, the name park refers to a different string on each pass.
A descriptive loop variable helps explain what each item represents.
parks = ["Oak", "River", "Hill"]
for park in parks:
print(park)Count with range
range(3) produces 0, 1, and 2. The stop value is excluded. range(1, 4) produces 1, 2, and 3.
Use enumerate() when you need both an index and the item; its optional start argument changes the displayed count.
parks = ["Oak", "River", "Hill"]
for position, park in enumerate(parks, start=1):
print(position, park)Build a result
Initialize an accumulator before the loop, update it inside the loop, and use the final result afterwards. Here total starts at zero and increases for each daily count.
counts = [8, 12, 10]
total = 0
for count in counts:
total += count
print(total) # 30While loops and stopping
A while loop continues while its condition is true. Make sure something in the loop can change that condition, or the loop may never stop. break exits the nearest loop; continue skips to its next iteration.
remaining = 3
while remaining > 0:
print(remaining)
remaining -= 1
print("Done")Which numbers are produced by range(3)?
Your turn
Use a loop to add the numbers in [4, 6, 2] and print the total.
total = 0 for number in [4, 6, 2]: total += number print(total) # 12
BUILT TOGETHER
Help make this explanation better.
Have a clearer explanation, a useful example, or a correction? Share it with the community.
Be the first to add your name when you improve this lesson.
How to get credited