What are Loops?
Loops in Python help you repeat actions without writing the same code over and over again. Imagine if you had to write "Hello!" 100 times—loops save you from that nightmare!
Python has two main types of loops:
Loop Type | Meaning |
---|---|
for loop |
Repeats a block of code a specific number of times |
while loop |
Repeats a block of code as long as a condition is True |
The for
Loop
Use a for
loop when you know exactly how many times you need to repeat something.
for i in range(5): # Loops 5 times (0 to 4)
print(f"Iteration {i} ")
Real-life Example:
- You have a box of chocolates and want to eat one at a time.
chocolates = ["Snickers", "Twix", "KitKat"]
for chocolate in chocolates:
print(f"Eating {chocolate} ")
The while
Loop
Use a while
loop when you don’t know exactly how many times to repeat, but you have a condition to check.
count = 0
while count < 5:
print(f"Counting... {count} 📊")
count += 1 # Don’t forget this! Or your loop will run forever
Real-life Example:
- Keep eating until you’re full!
hungry = True
slices = 5
while hungry and slices > 0:
print("Eating a slice")
slices -= 1
if slices == 0:
hungry = False
print("No more pizza!")
Loop Control Statements
Sometimes, you need to control how your loop behaves. Python provides:
Statement | Meaning |
---|---|
break |
Stops the loop immediately |
continue |
Skips the rest of the code and goes to the next iteration |
pass |
Does nothing (useful as a placeholder) |
for number in range(10):
if number == 5:
break # Stops the loop at 5
print(number)
for number in range(10):
if number % 2 == 0:
continue # Skips even numbers
print(number)
Nested Loops
Loops inside loops—loop-ception!
for i in range(3):
for j in range(2):
print(f"Outer loop {i}, Inner loop {j}")
Real-life Example:
- Imagine a cafeteria with 3 tables, and each table has 2 chairs. You want to check every chair.
tables = 3
chairs_per_table = 2
for table in range(1, tables + 1):
for chair in range(1, chairs_per_table + 1):
print(f"Checking Table {table}, Chair {chair}")
Summary
Loop Type | Purpose |
---|---|
for loop |
Use when you know how many times to loop |
while loop |
Use when looping until a condition is met |
break |
Stop the loop completely |
continue |
Skip the rest of the loop iteration |
pass |
Placeholder for future code |
Nested loops | Loop inside a loop! |
Now you're a looping master! Keep practicing and write efficient Python code!
0 Comments