Chapter 4: The Super Power of Repetition
Last week, I was assigned a massive project: I had to draw 100 tiny, perfectly shaped yellow stars for a giant school science poster. By the tenth star, my hand was totally cramping. By the thirtieth star, my yellow marker was running dry. By the fiftieth star, I sat there staring at the poster, wishing I had a magic, automatic stamp that could just do all the boring work for me so I could go play outside.
Well, in the world of coding, we actually do have a magic stamp!
Doing all of that by clicking your mouse 10,000 times would take forever and ruin your mouse! In programming, we have a superpower that fixes this. We call it a : .
Instead of typing the same exact command 50 times in our script, we just tell the computer: “Hey, do this 50 times.” Loops make your code faster, shorter, and way smarter—just like building an automatic Redstone machine in Minecraft instead of doing all the heavy lifting by hand.
The “For” Loop (The Counted Loop)
Section titled “The “For” Loop (The Counted Loop)”The first type of loop you will learn is called a : . We use this specific loop when we know exactly how many times we want to do something.
Think of it like crafting a stack of items in Minecraft. You know you want exactly 64 torches. You don’t want 63, and you don’t want 65. You want a precise number.
Real World Check-In: Think about a lawn sprinkler in your yard. What if you had to water the whole lawn by running back and forth with a tiny bucket of water? You’d be exhausted! Thankfully, a sprinkler doesn’t just spin randomly. It is programmed to go back and forth exactly 5 times before it stops to let the water soak in. That automatic repetition is a for loop!
The Syntax (Writing the Code)
Section titled “The Syntax (Writing the Code)”To write a loop in Python, we use the magic word : . Think of range as setting up a target number for the computer’s internal stopwatch.
Minecraft Example: Building a Tower
Imagine you want to place 5 blocks to build a pillar. Instead of writing print("Placed a block!") five separate times on five separate lines, we can use a loop to do the heavy lifting!
print("Start building...")
for i in range(5): print("Placed a block!")
print("Tower complete!")What exactly is happening behind the scenes?
- The computer sees
range(5)and says, “Got it, I need to do the next part 5 times.” - It looks down and runs the indented code (
print("Placed a block!")). - It loops back up to the top and repeats that exact line again.
- Once it has done it exactly 5 times, it breaks out of the loop and moves on to print “Tower complete!”
Wait, what is the letter i?
You might be wondering: What is that random letter i doing hanging out in our code? The i stands for Index (or simply, “Item”). It is an invisible, temporary variable that counts the laps for you behind the scenes.
Computers are a little weird—they actually start counting at zero! So the i variable counts like this: “0, 1, 2, 3, 4.” That’s 5 laps! If you change your code to print(i), the computer will actually show you its secret counting numbers! It uses i to keep track of which lap it is currently on so it doesn’t lose its place.
The “While” Loop (The Condition Loop)
Section titled “The “While” Loop (The Condition Loop)”Sometimes, you don’t know exactly how many times you need to repeat something. You can’t give the computer a specific number because the game is unpredictable.
For unpredictable situations like this, we use a <VocabHover def=“A type of loop that continues running as long as a specific condition remains True.”>while loop</VocabHover>. A while loop acts a lot like an if statement from Chapter 3, but instead of checking the rule once, it checks the rule over and over again, and keeps running as long as the condition is True.
Real World Check-In: Imagine you are eating a giant bowl of popcorn during movie night. You don’t count exactly 64 pieces before you start. Instead, your brain uses a while loop! The code in your brain looks like this: While there is still popcorn in the bowl, grab another handful! The loop only breaks when your hand hits the empty bottom of the bowl.
Roblox Example: The Boss Fight & The Timer
Section titled “Roblox Example: The Boss Fight & The Timer”Let’s look at a countdown timer for a round of “Tower of Darkness.” The game needs to count down from 3 before the doors open.
timer = 3
while timer > 0: print("Time remaining: " + str(timer)) timer = timer - 1
print("GO!")Output:
Time remaining: 3Time remaining: 2Time remaining: 1GO!🚨 Warning: The Infinite Loop! 🚨
Section titled “🚨 Warning: The Infinite Loop! 🚨”Look very closely at the code above. We wrote timer = timer - 1. This is the most important part of the whole script! If we forgot to subtract the time, the timer variable would stay at 3 forever.
Imagine a robot that is told to “Walk forward” but is never given a command to stop. It would crash through the wall, out the door, and into the ocean! If we forget to change the timer, the computer would scream “Time remaining: 3” billions and billions of times until the game completely crashed!
In the programming world, this nightmare is called an <VocabHover def=“A bug where the loop never stops running because the condition never becomes False.”>Infinite Loop</VocabHover> (and in Roblox, players call it a “Lag Machine”). Always make sure your while loop has a way to eventually become False!
Combining Loops, Variables, AND Conditionals!
Section titled “Combining Loops, Variables, AND Conditionals!”Now, let’s mix Chapter 2 (Variables), Chapter 3 (Conditionals), and Chapter 4 (Loops) all together. This is where you officially become a coding wizard.
<CodingActivity title=“The Diamond Miner”> We will create a script that mines for diamonds. We will start with 0 diamonds, dig 5 times using a loop, and add a diamond to our inventory every time we swing our pickaxe.
But wait—mining is dangerous! We are going to add an if statement inside our loop so that on the 3rd swing (when i equals 2, because computers start at 0!), we dodge a pool of lava!
Type this code exactly as you see it:
inventory = 0print("Heading into the dark mines...")
for i in range(5): print("Swing!")
if i == 2: print("Whoa! Dodged some lava!") else: print("You found a Diamond!") inventory = inventory + 1
print("--- Mining Finished ---")print("Total Diamonds in your backpack: " + str(inventory))Why is this so cool?
Because we put the inventory = inventory + 1 inside the loop (indented), the computer does the math for us automatically. And because we added an if statement, the computer makes a smart decision on every single lap! You just turned a simple script into a totally automated mini-game!
</CodingActivity>
Your 3 Action Steps!
Section titled “Your 3 Action Steps!”Ready to practice your new looping superpower? Do these three things before you start the next chapter:
- Spot the Loop: Be a Loop Detective. Find at least two things in your house that use a mechanical or computer loop (Hint: Check the kitchen microwave, the laundry room washing machine, or a digital clock!).
- Write a Paper Program: Write a fake while loop on a piece of paper for walking your dog. What is the rule that keeps you walking? (Example:
while dog_has_energy > 0: keep_walking()). - Run the Mega Miner: Type the “Diamond Miner” code from the activity above into a Python editor. Try changing the
range(5)to a massive number, likerange(1000). Watch how incredibly fast the computer can mine 1,000 blocks compared to doing it by hand in a real game!