Course contentsLesson 6 of 13← Course overview
  1. 01Meet Python12 min
  2. 02Set up and run Python12 min
  3. 03Variables and data types15 min
  4. 04Strings and input15 min
  5. 05Decisions with conditionals15 min
  6. 06Repeat work with loops15 min
  7. 07Functions and return values18 min
  8. 08Work with lists16 min
  9. 09Dictionaries and tuples16 min
  10. 10Understand errors and exceptions14 min
  11. 11Read and write files16 min
  12. 12Modules and the standard library14 min
  13. 13Build a small data summary20 min

Python & data · Lesson 06

Repeat work with loops

Edit lesson

Use for and while loops to repeat work and keep track of results.

15 minProgress saves on this device
In this lesson
  • 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.

Iterate over a listpython
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.

Number itemspython
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.

Add countspython
counts = [8, 12, 10]
total = 0
for count in counts:
    total += count
print(total)  # 30

While 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.

Count downpython
remaining = 3
while remaining > 0:
    print(remaining)
    remaining -= 1
print("Done")
Knowledge check

Which numbers are produced by range(3)?

Try first; feedback appears after you check.
Apply it

Your turn

Use a loop to add the numbers in [4, 6, 2] and print the total.

Continue readingPython: for statements

BUILT TOGETHER

Help make this explanation better.

Have a clearer explanation, a useful example, or a correction? Share it with the community.

Contributors

Be the first to add your name when you improve this lesson.

How to get credited
Previous lessonNext lesson