computer4kids is now ComputerLeap. Same free lessons, same team. Read why we changed our name

← All lessons · 🧑‍💻 Coding Academy

🎢

🎓

⏱ 25 min

Free

Loops Deep Dive

Loop through lists, use while loops and stop loops early with break.

🎯 What you will learn

  • Loop through every item in a list
  • Use while loops
  • Control loops with break

👋 Let’s get started!

Loops are a coder’s superpower 🦸. Now let’s use them on lists and learn while loops — loops that keep going until something changes.

🪜 Step by step

1. 📋 Loop over a list

for item in list: visits every item.

pets = ["cat", "dog", "fish"]
for pet in pets:
    print("I love my", pet)
2. ⏳ while loops

A while loop repeats as long as its condition is True.

fuel = 3
while fuel > 0:
    print("Fuel left:", fuel)
    fuel = fuel - 1
print("Out of fuel!")
3. 🛑 break

break jumps out of a loop right away.

for n in range(1, 100):
    if n * n > 50:
        print("First square over 50:", n * n)
        break

🧪 Try it!

Change the code and press ▶ Run to see what happens. You can’t break anything!

Total your scores

scores = [8, 10, 7, 9]
total = 0
for s in scores:
    total = total + s
print("Total:", total)
print("Average:", total / len(scores))

Countdown with while

count = 3
while count > 0:
    print(count)
    count = count - 1
print("Go!")

📖 Key words

Tap a card to flip it over!

while
Repeats while something is True ⏳
break
Exits a loop early 🛑
Infinite loop
A loop that never stops ♾️ (a bug!)

🏆 Challenge

Use a loop to print only the even numbers in the list, one per line.

Challenge

numbers = [3, 2, 7, 8, 10, 5]
for n in numbers:
    

Knowledge Check Quiz

  1. How many times does this print?
  2. What does break do?
  3. Why is this a bug?
← Previous lesson
Next lesson →