09
Day 9: Loops and Iteration
Chapter 9 • Beginner
45 min
Loops allow you to execute a block of code multiple times. Python has two main types of loops:
For Loops:
- Used for iterating over a sequence (list, tuple, string, etc.)
- Execute a block of code for each item in the sequence
- Can use range() function to generate numbers
While Loops:
- Execute a block of code as long as the condition is True
- Need to be careful to avoid infinite loops
- Often used when you don't know how many iterations you need
Loop Control Statements:
- break - Exit the loop completely
- continue - Skip the current iteration
- pass - Do nothing (placeholder)
Hands-on Examples
For Loops
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}")
# Using range
print("\nNumbers 1 to 5:")
for i in range(1, 6):
print(i)
# Iterate over string
word = "Python"
print("\nLetters in 'Python':")
for letter in word:
print(letter)
# Nested loops
print("\nMultiplication table (1-3):")
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i * j}")
# Loop with enumerate
colors = ["red", "green", "blue"]
print("\nColors with index:")
for index, color in enumerate(colors):
print(f"{index}: {color}")For loops are perfect when you know how many times you want to repeat an action.