← Module 2 Module 4 β†’

πŸ” Module 3

Loops

Loops let you do the same idea again and again β€” once for each house, each spell, each quiz score.

A clockwork owl repeatedly delivers envelopes around a circular path while a coder counts.
Patch has been pressing Enter in a loop. This is either testing or a very small parade.

πŸͺ„ The concept

A for loop walks through each item in a list (or each number from range()) and runs a block of code for that item.

Loops are how you turn a pile of numbers into totals, averages, highs and lows β€” or how you print a cheer for every house without rewriting the same line four times.

enumerate() gives you both a counter and the item (Lesson 1, Lesson 2…). You can also build a new list inside a loop β€” for example, only the passing scores.

πŸ’¬ Discussion

Talk these through with a friend, a class, or just your notes app:

  1. Where do you already β€œloop” in real life? (Checking each bag of chips at a store, practicing free throws…)
  2. Would you rather write four print statements or one loop that prints four times? When might the long way still be clearer?
  3. How could a game use a loop to visit every room on a map?

πŸ’» Code walkthrough

Copy into your editor, or download the .py file and run it. Tinker β€” change names, numbers, and spells.

For loops over a list for_loops.py

# Loop through each house and print a cheer
houses = ["Gryffindor", "Hufflepuff", "Ravenclaw", "Slytherin"]

for house in houses:
    print("Points for", house, "β€” ten points!")

# range() gives a sequence of numbers β€” useful for counting spells
for i in range(3):
    print("Practice swing", i + 1)

Summing and averaging (stats with loops) scores_stats.py

# Track quiz scores and find the total and average
scores = [88, 92, 75, 95, 81]
total = 0

for score in scores:
    total = total + score   # add each score to the running total

average = total / len(scores)
print("Total points:", total)
print("Average score:", round(average, 1))

enumerate() β€” loop with an index counter enumerate_loop_with_an_index_counter.py

# Useful when you need "spell 1, spell 2..." while looping
spells = ["Lumos", "Nox", "Accio"]

for number, spell in enumerate(spells, start=1):
    print(f"Lesson {number}: learn {spell}")

Finding min, max, and building a new list finding_min_max_and_building_a_new_list.py

quiz_scores = [72, 95, 88, 61, 90]
print("Highest:", max(quiz_scores))
print("Lowest:", min(quiz_scores))

# Build a list of passing grades only
passing = []
for score in quiz_scores:
    if score >= 70:
        passing.append(score)

print("Passed:", passing)

πŸ§ͺ Try this

  1. Make a list of your favorite snacks (or spells). Loop through and print I like … for each one.
  2. Change the quiz scores in scores_stats.py to your own numbers. Does the average match what you expect?
  3. Use enumerate to number a packing list for a trip to Hogwarts (or anywhere). Start at 1, not 0.

πŸ“ Local files

All runnable Python for this module:

module-03-loops/ Β· all modules

🎬 Video lesson

← Module 2 Module 4 β†’