Have you ever had to write the same thing over and over? That's boring, right? Well, computers feel the same way! That's why we have loops - they let us tell the computer to repeat something many times without writing it again and again. Let's learn this superpower!
The For Loop
A 'for' loop repeats code a specific number of times. Here's how it works:
for i in range(5):
print("Hello!")
This prints "Hello!" five times! The 'range(5)' means "do this 5 times". The 'i' keeps track of which round we're on (0, 1, 2, 3, 4).
Try this:
for i in range(5):
print("Round number:", i)
You'll see it counts from 0 to 4!
Creating Patterns with Loops
Let's make some cool patterns! Try this star pattern:
for i in range(1, 6):
print("*" * i)
Output:
*
**
***
****
*****
The '* i' multiplies the star by the number i. So round 1 prints 1 star, round 2 prints 2 stars, and so on. You can change the * to any character you like - try using your name's first letter!
The While Loop
A 'while' loop keeps going as long as something is true. Think of it like "keep eating while you're hungry":
count = 0
while count < 3:
print("Count is:", count)
count = count + 1
This prints:
Count is: 0
Count is: 1
Count is: 2
The loop stops when count reaches 3 because 3 is not less than 3!
Fun Project: Countdown Timer
Let's make a rocket countdown!
import time
print("Rocket Launch Countdown!")
for i in range(10, 0, -1):
print(i)
time.sleep(1) # Wait 1 second
print("🚀 BLAST OFF!")
The range(10, 0, -1) counts backwards from 10 to 1. The time.sleep(1) makes it wait 1 second between numbers. Run this and watch your rocket launch!
Amazing work! You've learned two types of loops - 'for' loops for when you know how many times to repeat, and 'while' loops for when you want to repeat until something changes. Loops are used everywhere: in games (checking if you're still alive), in apps (loading items one by one), and in websites (showing posts from a list). Practice making different patterns and countdowns - the more you experiment, the better you'll get!
C
Codive Team
Codiver · Coding Enthusiast
Share this post

