For Loops: draw a whole row of stars from one line
A for loop is your shortcut for doing the same thing again and again. Watch one draw a whole row of stars from just three lines — it's one of the biggest ideas in all of coding.
The big idea
A for loop repeats the same steps over and over, counting as it goes — so you write the steps once instead of copying them.
See it in code
The simplest loop just repeats. range(3) means do this 3 times, and the indented line underneath is what gets repeated:
for i in range(3):
print("Star!")Star! Star! Star!
Three trips around the loop, three lines. Change the 3 and you change how many times it runs.
A loop also counts for you. Each time around, the loop variable i becomes the next number — and it starts at 0:
for i in range(5):
print("Star number", i)Star number 0 Star number 1 Star number 2 Star number 3 Star number 4
See how i went 0, 1, 2, 3, 4? That counting is the secret — you can use i to make each trip a little different.
Now the payoff: use that counter as a position. range(8) gives us 0 through 7, and we turn each i into an x-spot — sliding each star a little further to the right:
from art import Canvas, star
screen = Canvas.create()
Canvas.fill(screen)
for i in range(8):
star(screen, 60 + i * 55, 250)
One for line drew all eight stars. Want forty? Change the 8 to 40 — same three lines, no extra typing.
A loop doesn't only draw stars. The same three lines can place a row of game characters, go through a list of names one at a time, or repeat any steps you'd otherwise copy-paste. Stars are just the easiest way to see a loop working.
Try it yourself
Change range(8) to range(20) and run it — twenty stars appear from the same three lines. Then swap the y (the 250) for i * 25 + 120 and make your stars climb like a staircase. Try it next time you're in a loop activity.
The common mistake
The classic oops: forgetting to use i. If you write star(screen, 60, 250) inside the loop (no i anywhere), every star lands in the exact same spot — so it looks like there's only one. The i is what makes each star show up somewhere new.
What it unlocks
Once one loop feels easy, loops inside loops fill the whole sky with rows and columns of stars, and the range() function lets you start, stop, and skip-count however you like.