Module 5 - Loops
This module covers loops in Python. You'll learn how to iterate over sequences using for loops, repeat code with while loops, and control loop execution with break, continue, and else clauses.
1. For Loops
1.1 Basic For Loop
# Iterate over a list
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)
# Iterate over a string
for char in "Python":
print(char)
# Iterate over a range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
1.2 Range Function
# range(stop)
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# range(start, stop)
for i in range(2, 7):
print(i) # 2, 3, 4, 5, 6
# range(start, stop, step)
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# Counting backwards
for i in range(10, 0, -1):
print(i) # 10, 9, 8, ..., 1
1.3 Enumerate Function
# Get index and value
fruits = ["apple", "banana", "orange"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 0: apple
# 1: banana
# 2: orange
# Start from custom index
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")
# 1. apple
# 2. banana
# 3. orange
1.4 Zip Function
# Iterate over multiple lists simultaneously
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
cities = ["NYC", "LA", "Chicago"]
for name, age, city in zip(names, ages, cities):
print(f"{name} is {age} years old and lives in {city}")
# Output:
# Alice is 25 years old and lives in NYC
# Bob is 30 years old and lives in LA
# Charlie is 35 years old and lives in Chicago
# zip stops at shortest list
numbers1 = [1, 2, 3, 4, 5]
numbers2 = [10, 20, 30]
for n1, n2 in zip(numbers1, numbers2):
print(n1, n2) # Only 3 pairs
Use enumerate() instead of manually tracking indices. Use zip() to iterate over multiple sequences in parallel.
2. While Loops
2.1 Basic While Loop
# Basic while loop
count = 0
while count < 5:
print(count)
count += 1
# While loop with condition
password = ""
while password != "secret":
password = input("Enter password: ")
print("Access granted!")
2.2 While True with Break
# Infinite loop with break
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input == "quit":
break
print(f"You entered: {user_input}")
# Menu system
while True:
print("\n1. Add")
print("2. View")
print("3. Exit")
choice = input("Choose option: ")
if choice == "1":
print("Adding...")
elif choice == "2":
print("Viewing...")
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid choice")
2.3 While with Multiple Conditions
attempts = 0
max_attempts = 3
authenticated = False
while attempts < max_attempts and not authenticated:
password = input("Enter password: ")
if password == "secret123":
authenticated = True
print("Login successful!")
else:
attempts += 1
remaining = max_attempts - attempts
print(f"Wrong password. {remaining} attempts remaining")
if not authenticated:
print("Account locked!")
3. Break Statement
3.1 Breaking Out of Loops
# Break in for loop
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for num in numbers:
if num > 5:
break
print(num) # Prints 1, 2, 3, 4, 5
# Search example
names = ["Alice", "Bob", "Charlie", "David"]
search = "Charlie"
for name in names:
if name == search:
print(f"Found {search}!")
break
else:
print(f"{search} not found")
3.2 Break in Nested Loops
# Break only breaks inner loop
for i in range(3):
for j in range(3):
if j == 1:
break
print(f"i={i}, j={j}")
print(f"Completed outer iteration {i}")
# Using flag to break outer loop
found = False
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
target = 5
for row in matrix:
for num in row:
if num == target:
print(f"Found {target}!")
found = True
break
if found:
break
4. Continue Statement
4.1 Skipping Iterations
# Skip even numbers
for i in range(10):
if i % 2 == 0:
continue
print(i) # Prints odd numbers: 1, 3, 5, 7, 9
# Skip specific values
names = ["Alice", "", "Bob", None, "Charlie"]
for name in names:
if not name:
continue
print(f"Hello, {name}!")
4.2 Practical Examples
# Process only valid data
data = [10, -5, 20, 0, 30, -10, 40]
for value in data:
if value <= 0:
continue
processed = value * 2
print(processed)
# Skip weekends
days = ["Monday", "Tuesday", "Wednesday", "Thursday",
"Friday", "Saturday", "Sunday"]
for day in days:
if day in ["Saturday", "Sunday"]:
continue
print(f"{day} is a working day")
5. Else Clause in Loops
5.1 For-Else
# Else executes if loop completes normally (no break)
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num > 10:
print("Found number > 10")
break
else:
print("No number > 10 found")
# Practical example: Search
def find_prime(start, end):
for num in range(start, end):
if num < 2:
continue
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
break
else:
return num
return None
print(find_prime(10, 20)) # 11
5.2 While-Else
# While-else example
count = 0
max_count = 5
while count < max_count:
print(count)
count += 1
else:
print("Loop completed normally")
# With break
count = 0
while count < 10:
if count == 5:
break
count += 1
else:
print("This won't print") # Skipped due to break
The else clause executes only if the loop completes normally (without hitting a break). This is useful for search operations.
6. Nested Loops
6.1 Basic Nested Loops
# Multiplication table
for i in range(1, 6):
for j in range(1, 6):
print(f"{i} x {j} = {i*j}")
print() # Blank line after each table
# Pattern printing
for i in range(5):
for j in range(i + 1):
print("*", end="")
print()
# Output:
# *
# **
# ***
# ****
# *****
6.2 Matrix Operations
# 2D matrix traversal
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Print matrix
for row in matrix:
for element in row:
print(element, end=" ")
print()
# Sum all elements
total = 0
for row in matrix:
for element in row:
total += element
print(f"Total: {total}") # 45
7. List Comprehensions
7.1 Basic List Comprehension
# Traditional approach
squares = []
for i in range(10):
squares.append(i ** 2)
# List comprehension (Pythonic)
squares = [i ** 2 for i in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With strings
fruits = ["apple", "banana", "orange"]
upper_fruits = [fruit.upper() for fruit in fruits]
print(upper_fruits) # ['APPLE', 'BANANA', 'ORANGE']
7.2 Conditional List Comprehension
# Filter even numbers
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = [n for n in numbers if n % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
# If-else in comprehension
numbers = [1, 2, 3, 4, 5]
result = ["Even" if n % 2 == 0 else "Odd" for n in numbers]
print(result) # ['Odd', 'Even', 'Odd', 'Even', 'Odd']
# Multiple conditions
numbers = range(1, 21)
filtered = [n for n in numbers if n % 2 == 0 if n % 3 == 0]
print(filtered) # [6, 12, 18]
7.3 Nested List Comprehensions
# Flatten 2D matrix
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flat = [num for row in matrix for num in row]
print(flat) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Create 2D matrix
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix) # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
7.4 Dictionary and Set Comprehensions
# Dictionary comprehension
squares_dict = {x: x**2 for x in range(5)}
print(squares_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# Set comprehension
numbers = [1, 2, 2, 3, 3, 3, 4, 5, 5]
unique_squares = {n**2 for n in numbers}
print(unique_squares) # {1, 4, 9, 16, 25}
# Swap keys and values
original = {"a": 1, "b": 2, "c": 3}
swapped = {value: key for key, value in original.items()}
print(swapped) # {1: 'a', 2: 'b', 3: 'c'}
Use comprehensions for simple transformations. Use regular loops for complex logic or when readability matters more.
8. Loop Optimization
8.1 Avoid Unnecessary Work
# Bad: Repeated calculation
for i in range(len(items)):
process(items[i])
# Good: Direct iteration
for item in items:
process(item)
# Bad: Expensive operation in loop
for i in range(n):
result = expensive_function() # Called every iteration
use(result)
# Good: Move outside loop
result = expensive_function()
for i in range(n):
use(result)
8.2 Early Exit
# Stop early when found
def find_in_list(items, target):
for item in items:
if item == target:
return True # Exit immediately
return False
# Process until condition met
def process_until_valid(data):
for item in data:
result = process(item)
if is_valid(result):
return result
return None
9. Common Loop Patterns
9.1 Accumulator Pattern
# Sum
total = 0
for num in [1, 2, 3, 4, 5]:
total += num
print(total) # 15
# Product
product = 1
for num in [1, 2, 3, 4, 5]:
product *= num
print(product) # 120
# String building
result = ""
for char in "Python":
result += char.upper()
print(result) # PYTHON
9.2 Counter Pattern
# Count occurrences
numbers = [1, 2, 3, 2, 1, 3, 2, 4, 5, 2]
count = 0
for num in numbers:
if num == 2:
count += 1
print(f"2 appears {count} times") # 4 times
# Count conditions
ages = [15, 20, 25, 30, 35, 40]
adults = 0
for age in ages:
if age >= 18:
adults += 1
print(f"{adults} adults") # 5 adults
9.3 Filter Pattern
# Keep only valid items
numbers = [1, -2, 3, -4, 5, -6]
positives = []
for num in numbers:
if num > 0:
positives.append(num)
print(positives) # [1, 3, 5]
# Or use list comprehension
positives = [num for num in numbers if num > 0]
10. Summary
| Concept | Description | Example |
|---|---|---|
| for loop | Iterate over sequences | for x in items: |
| while loop | Loop while condition true | while x < 10: |
| range() | Generate number sequence | range(5) or range(1, 10, 2) |
| enumerate() | Get index and value | for i, x in enumerate(items): |
| zip() | Iterate multiple sequences | for a, b in zip(list1, list2): |
| break | Exit loop early | break |
| continue | Skip to next iteration | continue |
| else | Execute if loop completes | for...else: |
| List comprehension | Concise list creation | [x**2 for x in range(10)] |
- Use
forloops for definite iteration (known sequence) - Use
whileloops for indefinite iteration (condition-based) - Leverage
enumerate()andzip()for cleaner code - Use comprehensions for simple transformations
- Break and continue control loop flow
- Loop else clause is useful for search patterns
11. What's Next?
In Module 6 - Functions, you'll learn:
- Defining functions with
def - Parameters and arguments
- Return values
*argsand**kwargs- Lambda functions
- Scope and namespaces
12. Practice Exercises
Exercise 1: FizzBuzz
Print numbers 1-100. For multiples of 3 print "Fizz", for multiples of 5 print "Buzz", for multiples of both print "FizzBuzz".
# Your code here
Exercise 2: Prime Numbers
Find all prime numbers between 1 and 100 using loops.
# Your code here
Exercise 3: Pattern Printing
Create a function that prints a diamond pattern with asterisks.
def print_diamond(n):
# Your code here
pass
Exercise 4: Sum of Digits
Write a function that calculates the sum of digits in a number using a while loop.
def sum_of_digits(n):
# Your code here
pass
Exercise 5: List Manipulation
Given a list of numbers, create three new lists using list comprehensions:
- Squares of even numbers
- Cubes of odd numbers
- Numbers divisible by 3
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Your code here
Try solving these exercises on your own first. Solutions will be provided in the practice section.