๐ Learn Python Basics
๐ Loops Recap and more
๐ What is a Loop?
Loops ๐ช
So we learned Loops help the computer repeat things automatically!
Imagine bouncing a ball ๐ again and again. Instead of saying **"bounce"** five times, we use a **loop**!
๐ค Python Makes Repeating Easy!
Without a loop, we'd have to write this:
print("Bounce!") print("Bounce!") print("Bounce!") print("Bounce!") print("Bounce!")
With a loop, it's **much shorter**:
for number in range(5): print("Bounce!")
๐ The **loop** makes it easier to repeat without typing too much!
๐ข But Why Do Loops Start at 0?
Computers count differently from humans! ๐
Example:
for i in range(3): print(i)
๐ข Output:
0 1 2
This helps computers count things correctly inside programs! ๐ฅ๏ธ
Example 1: Counting Steps ๐ฃ
Imagine a robot taking 3 steps:
for step in range(3): print("Step:", step)
๐ข Output:
Step: 0 Step: 1 Step: 2
The **first step** is actually "Step 0" for the computer! ๐ค
Example 2: Seats in a Movie Theater ๐ฌ
Imagine a theater with **5 seats**, labeled from **0 to 4**:
for seat in range(5): print("Seat number", seat, "is ready!")
๐ข Output:
Seat number 0 is ready! Seat number 1 is ready! Seat number 2 is ready! Seat number 3 is ready! Seat number 4 is ready!
The first seat is **seat 0**, not **seat 1**โjust like how computers count!
By starting at 0, computers can work **faster and smarter!** ๐ฅ๏ธโก
๐ Understanding the range()
Function
The range()
function helps us create loops easily!
Syntax:
range(start, stop, step)
Example 1: Counting Steps ๐ฃ
Imagine a robot taking 3 steps:
for step in range(3): # Same as range(0, 3) print("Step:", step)
๐ข Output:
Step: 0 Step: 1 Step: 2
Example 2: Counting from 1 Instead of 0
If we want to count **1, 2, 3** instead of **0, 1, 2**, we can set start=1
:
for num in range(1, 4): print("Number:", num)
๐ข Output:
Number: 1 Number: 2 Number: 3
๐ก Why Use range()
?
- โ **Repeat tasks easily** (like clapping ๐๐๐)
- โ **Save time** instead of writing the same thing many times
- โ **Make games and animations fun! ๐ฎ**
Now, let's try a game where you control a ๐ฐ bunny's jumps using loops!