Loops Make Patterns
Repeat code with a loop to draw stars and plant forests.
Loops Make Patterns 🔁
Did you notice drawing a square meant writing the same two lines four times? Coders don't like repeating themselves. Instead, they use a loop:
import turtle
t = turtle.Turtle()
for i in range(4):
t.forward(100)
t.left(90)for i in range(4): means "do the lines below 4 times."
💡⚠️ The lines that repeat must be indented (pushed in with spaces). That's how Python knows which lines belong to the loop.
⭐ Draw a star
Turn 144 degrees, 5 times, and you get a star. Space time!
import turtle
t = turtle.Turtle()
t.color("gold")
for i in range(5):
t.forward(150)
t.right(144)🌳 Loops work for printing too
for i in range(3):
print("Plant a tree")That prints Plant a tree three times.
Counting with a loop
i counts for you. range(1, 4) counts 1, 2, 3 (it stops before 4):
for i in range(1, 4):
print("Day", i)🌲 Fun fact
Every year, people around the world plant billions of trees to grow back forests. Trees clean the air and are home to huge numbers of animals. A loop that plants a billion trees would be a very long loop!
Type it yourself
Don't just read it — type the example from above into the box, press Run ▶, and watch what happens. Typing it yourself is how it really sticks! Stuck? Tap Show example.
Press ▶ Run to see your code come to life…