Loops: Repeat the Fun! 🔄🎉
What if you could tell the computer to do something 100 times with just ONE instruction?
🤔 What is a Loop?
A loop is a way to make the computer do the same thing over and over again. It's like pressing repeat on your favorite song!
Without a Loop vs With a Loop
say "Hello!"
say "Hello!"
say "Hello!"
say "Hello!"
say "Hello!"
5 lines for 5 hellos!
repeat 5 times:
say "Hello!"
Just 2 lines! Much easier!
🌍 Loops in Real Life
You do loops every single day!
Eating
Bite, chew, swallow... repeat until food is gone!
Walking
Left foot, right foot... repeat until you arrive!
Music
The chorus repeats several times in a song!
Day & Night
Morning, afternoon, night... repeat forever!
🎬 Watch the Loop!
See how a loop counts from 1 to 5:
for number from 1 to 5 :
say number 🎯 Different Kinds of Loops
There are different ways to repeat things!
"Do this X times"
When you know exactly how many times to repeat.
repeat 10 times: jump up and down
"Do this until..."
Keep going until something happens!
while hungry: eat more food
"Do this for each thing"
Go through every item in a list!
for each friend: say "Hi!"
🎮 Loops in Games!
Video games use LOTS of loops! Can you spot them?
Running Character
Loop: Keep moving forward while the button is pressed!
Enemy Spawning
Loop: Create a new enemy every few seconds!
Background Music
Loop: Play the song, then start over!
Game Timer
Loop: Count down 1 second, repeat until 0!
⚠️ Watch Out: Infinite Loops!
A loop that NEVER stops is called an infinite loop. It's like asking someone to count to infinity - they'd never finish!
This loop never stops:
while true: say "Help!" Always make sure your loop has a way to stop!
⭐ Remember This!
- 1
Loops let you repeat code without writing it many times
- 2
You can repeat a specific number of times (like 10 times)
- 3
You can repeat until something happens (like until you're full)
- 4
Always make sure loops can stop - no infinite loops!