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

← All lessons · 🧑‍💻 Coding Academy

🔁

🎓

⏱ 20 min

Free

Repeat It! (for loops)

Make Python repeat things with for loops and range().

🎯 What you will learn

  • Repeat code with a for loop
  • Use range() to count
  • Indent the code inside a loop

👋 Let’s get started!

Remember loops from Code Critters? 🐛 In Python, we write them with for. Get ready to print 100 stars with ONE line!

🪜 Step by step

1. 🔁 for and range

for i in range(3): repeats the indented lines 3 times.

for i in range(3):
    print("Hip hip hooray! 🎉")
2. ↔️ Indent!

Lines inside the loop start with 4 spaces. That’s how Python knows they belong to the loop.

for i in range(2):
    print("inside the loop")
print("after the loop")
3. 🔢 Counting

i counts for you: 0, 1, 2… Add 1 to start at 1.

for i in range(5):
    print(i + 1)

🧪 Try it!

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

Star staircase

for i in range(5):
    print("⭐" * (i + 1))

Countdown loop

for i in range(3):
    print(3 - i)
print("Lift off! 🚀")

📖 Key words

Tap a card to flip it over!

for loop
Repeats code ↻
range()
Makes numbers to count with 🔢
Indent
Spaces at the start of a line ↔️

🏆 Challenge

Use a loop to print “Coding rocks!” exactly 4 times.

Challenge

for i in range(1):
    print("Coding rocks!")

Knowledge Check Quiz

  1. How many times does this print?
  2. What is the first number range(5) gives?
  3. How does Python know a line is inside the loop?
← Previous lesson
Next lesson →