- Understand what loops are and why they're powerful
- Use for loops to iterate over sequences
- Master the range() function for number sequences
- Apply loops to solve real-world problems
For Loops and Iteration
Imagine you're a teacher who needs to print "Welcome!" for each of your 30 students. Without loops, you'd write print("Welcome!") 30 times. That's tedious, error-prone, and frankly, insane. What if you had 1000 students?
Loops are one of programming's most powerful concepts. They let you repeat actions as many times as needed with just a few lines of code. The for loop is particularly elegant – it goes through items one by one, like a librarian checking each book on a shelf.
In this lesson, you'll learn to harness this superpower and save yourself from repetitive coding forever!
What is a Loop?
A loop is a control structure that repeats a block of code multiple times. Think of it like:
Real-World Loop Examples
Music Playlist: "For each song in playlist, play it"
Email Check: "For each email in inbox, show preview"
Shopping: "For each item in cart, add to total"
Attendance: "For each student in class, check name"
Without Loops vs With Loops
# WITHOUT loops - Repetitive and hard to maintain
print("Hello, Alice!")
print("Hello, Bob!")
print("Hello, Carol!")
print("Hello, David!")
# WITH loops - Clean and flexible
names = ["Alice", "Bob", "Carol", "David"]
for name in names:
print(f"Hello, {name}!")
The Basic for Loop
The for loop iterates over items in a sequence (like a list, string, or range).
Anatomy of a for Loop
for Loop Structure
for item in sequence: ← Loop definition
# do something ← Loop body (indented)
# with item ← Runs once per item
next_code() ← Runs after loop ends
• "item" is the loop variable - gets each value
• "sequence" is what you're looping through
• The colon (:) and indentation are required
Simple Example
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}!")
print("Done listing fruits!")
What happens step by step:
| Iteration | fruit value |
Output |
|---|---|---|
| 1st | "apple" | "I like apple!" |
| 2nd | "banana" | "I like banana!" |
| 3rd | "cherry" | "I like cherry!" |
Then: "Done listing fruits!"
The range() Function
range() generates a sequence of numbers – perfect for when you need to repeat something a specific number of times.
range() with One Argument
# range(stop) - generates 0 to stop-1
for i in range(5):
print(i)
# Output: 0, 1, 2, 3, 4
Remember:
range(5)gives you 5 numbers, but starts at 0!
range() with Two Arguments
# range(start, stop) - generates start to stop-1
for i in range(1, 6):
print(i)
# Output: 1, 2, 3, 4, 5
range() with Three Arguments
# range(start, stop, step) - with custom increment
for i in range(0, 10, 2):
print(i)
# Output: 0, 2, 4, 6, 8 (even numbers)
# Counting backwards
for i in range(5, 0, -1):
print(i)
# Output: 5, 4, 3, 2, 1 (countdown!)
Visual Guide to range()
range() Variations
range(5) → 0 1 2 3 4
5 numbers, starting at 0
range(2, 7) → 2 3 4 5 6
starts at 2, stops before 7
range(0, 10, 2) → 0 2 4 6 8
every 2nd number
range(10, 0, -1) → 10 9 8 7 6 5 4 3 2 1
counting backwards
Looping Through Strings
Strings are sequences of characters, so you can loop through them:
word = "Python"
for letter in word:
print(letter)
# Output:
# P
# y
# t
# h
# o
# n
Practical String Loop
message = "HELLO"
secret = ""
for char in message:
# Shift each letter by 1 (simple cipher)
new_char = chr(ord(char) + 1)
secret += new_char
print(f"Original: {message}")
print(f"Encoded: {secret}")
# Output:
# Original: HELLO
# Encoded: IFMMP
Looping with Index: enumerate()
Sometimes you need both the item AND its position. enumerate() gives you both:
fruits = ["apple", "banana", "cherry"]
for index, fruit in fruits: # This won't work!
print(f"{index}: {fruit}")
# Use enumerate()
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: cherry
Start Index at 1
contestants = ["Alice", "Bob", "Carol"]
for position, name in enumerate(contestants, start=1):
print(f"#{position}: {name}")
# Output:
# #1: Alice
# #2: Bob
# #3: Carol
Common Loop Patterns
Pattern 1: Accumulator (Summing Values)
numbers = [10, 20, 30, 40, 50]
total = 0 # Start with zero
for num in numbers:
total += num # Add each number
print(f"Sum: {total}") # Sum: 150
Pattern 2: Counter
word = "mississippi"
count_s = 0
for letter in word:
if letter == "s":
count_s += 1
print(f"Letter 's' appears {count_s} times") # 4 times
Pattern 3: Building a New List
numbers = [1, 2, 3, 4, 5]
squares = []
for num in numbers:
squares.append(num ** 2)
print(squares) # [1, 4, 9, 16, 25]
Pattern 4: Finding Maximum/Minimum
temperatures = [22, 28, 19, 31, 25, 17]
hottest = temperatures[0] # Start with first value
for temp in temperatures:
if temp > hottest:
hottest = temp
print(f"Hottest: {hottest}°C") # Hottest: 31°C
Nested Loops
Loops inside loops – useful for grids, tables, and multi-dimensional data.
Simple Nested Loop
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
result = i * j
print(f"{i} × {j} = {result}")
print("---") # Separator between groups
Output:
1 × 1 = 1
1 × 2 = 2
1 × 3 = 3
---
2 × 1 = 2
2 × 2 = 4
2 × 3 = 6
---
3 × 1 = 3
3 × 2 = 6
3 × 3 = 9
---
Creating a Pattern
# Triangle pattern
for row in range(1, 6):
print("*" * row)
# Output:
# *
# **
# ***
# ****
# *****
Practical Examples
Example 1: Shopping Cart Total
cart = [
{"item": "Apple", "price": 1.50, "quantity": 4},
{"item": "Bread", "price": 2.50, "quantity": 2},
{"item": "Milk", "price": 3.00, "quantity": 1},
]
print(" Your Shopping Cart")
print("=" * 35)
total = 0
for product in cart:
subtotal = product["price"] * product["quantity"]
total += subtotal
print(f"{product['item']}: ${product['price']:.2f} × {product['quantity']} = ${subtotal:.2f}")
print("=" * 35)
print(f"Total: ${total:.2f}")
Example 2: Grade Analyzer
students = {
"Alice": 85,
"Bob": 92,
"Carol": 78,
"David": 95,
"Eve": 88
}
print(" Grade Report")
print("-" * 30)
total = 0
count = 0
highest_name = ""
highest_score = 0
for name, score in students.items():
total += score
count += 1
if score > highest_score:
highest_score = score
highest_name = name
# Assign letter grade
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"
print(f"{name}: {score} ({grade})")
average = total / count
print("-" * 30)
print(f"Class Average: {average:.1f}")
print(f"Top Student: {highest_name} ({highest_score})")
Example 3: Password Strength Checker
password = "MyP@ssw0rd!"
has_upper = False
has_lower = False
has_digit = False
has_special = False
length_ok = len(password) >= 8
for char in password:
if char.isupper():
has_upper = True
elif char.islower():
has_lower = True
elif char.isdigit():
has_digit = True
else:
has_special = True
print(" Password Strength Check")
print("-" * 30)
print(f" Length >= 8: {'Yes' if length_ok else 'No'}")
print(f" Uppercase: {'Yes' if has_upper else 'No'}")
print(f" Lowercase: {'Yes' if has_lower else 'No'}")
print(f" Numbers: {'Yes' if has_digit else 'No'}")
print(f" Special chars: {'Yes' if has_special else 'No'}")
strength = sum([length_ok, has_upper, has_lower, has_digit, has_special])
print("-" * 30)
print(f"Strength: {strength}/5 {' Strong!' if strength >= 4 else ' Needs improvement'}")
Key Takeaways
Remember These Points
for loops repeat code for each item in a sequence
Syntax: for item in sequence:
(indented code)
range() generates number sequences:
• range(5) → 0,1,2,3,4
• range(2,6) → 2,3,4,5
• range(0,10,2) → 0,2,4,6,8
enumerate() gives you index AND value
Common patterns: sum, count, find max/min, build lists
Nested loops are loops inside loops
What's Next?
You've mastered for loops – great for when you know what you're iterating over. But what if you want to repeat until a condition changes? In the next lesson, we'll explore while loops and learn how to control loop flow with break and continue!
