Loops
Loops are like having a magical repeat button. Instead of writing the same lines of code over and over, you can loop through your tasks.
FOR Loops: The Workhorse of Repetition
Imagine you’re handing out chocolates to your classmates. Instead of saying, “Here’s one chocolate, here’s another,” you can just write:
FOR Counter ← 1 TO 5
OUTPUT "Here’s a chocolate!"
NEXT Counter
In Python:
for Counter in range(1, 6):
print("Here’s a chocolate!")
Behind the Scenes
The loop starts with Counter = 1 and runs until Counter = 5. Each time it loops, it increases Counter by 1 automatically. Handy, right?
WHILE Loops: When You Don’t Know When to Stop
Sometimes, you don’t know how many times something will repeat. Maybe you’re waiting for your pet dog to bark, and only then will you stop:
DECLARE DogBarked : BOOLEAN
DogBarked ← FALSE
WHILE DogBarked = FALSE DO
OUTPUT "Waiting for the dog to bark..."
// Imagine DogBarked is updated when the dog barks
ENDWHILE
In Python:
DogBarked = False
while not DogBarked:
print("Waiting for the dog to bark...")
# Simulate the dog barking
DogBarked = True
REPEAT-UNTIL Loops: The One That Guarantees a Try
A REPEAT-UNTIL loop guarantees at least one execution, no matter what. Think of it like trying to guess a password (don’t actually hack, though!):
DECLARE Password : STRING
REPEAT
OUTPUT "Guess the password:"
INPUT Password
UNTIL Password = "OpenSesame"
In Python:
Password = ""
while True:
Password = input("Guess the password: ")
if Password == "OpenSesame":
print("You guessed it!")
break
Loops + Conditions: The Ultimate Combo
Loops and conditions together are like peanut butter and jelly—they just work! Let’s say you want to print the first 10 even numbers:
DECLARE Number : INTEGER
Number ← 2
WHILE Number <= 20 DO
OUTPUT Number
Number ← Number + 2
ENDWHILE
In Python:
Number = 2
while Number <= 20:
print(Number)
Number += 2
A Fun Challenge for You!
Write a program that:
- Asks the user for their favourite number.
- If the number is less than 10, print "Small number!"
- If the number is between 10 and 50, print "Medium number!"
- If the number is above 50, print "Big number!"
Need a hint? Use IF-THEN-ELSE and maybe a loop if you want to keep asking for numbers until the user types 0 to quit.
Now you know the secrets of control structures! Go forth, young coder, and make your programs dance to the beat of your logic. And remember: the power of loops and conditions lies in making your life easier—so use them wisely and have fun!