Python Loops
Loops allow you to execute a block of code repeatedly. Python provides for and while loops with powerful iteration capabilities.
What are Loops?
Loops are control structures that repeat a block of code until a condition is met. Python has two main types of loops: for loops (for iterating over sequences) and while loops (for conditional repetition).
"Loops automate repetitive tasks, making code more efficient and readable."
For Loops
For loops iterate over sequences (lists, tuples, strings, etc.):
# Basic for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterating over strings
for char in "Python":
print(char)
# Iterating over ranges
for i in range(5): # 0 to 4
print(i)
for i in range(1, 6): # 1 to 5
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8
print(i)
# Iterating with index
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
While Loops
While loops continue executing as long as a condition is true:
# Basic while loop
count = 0
while count < 5:
print(count)
count += 1
# While loop with break
number = 0
while True:
print(number)
number += 1
if number >= 5:
break
# While loop with user input
password = ""
while password != "secret":
password = input("Enter password: ")
print("Access granted!")
# Infinite loop (avoid!)
# while True:
# print("This will run forever")
Loop Control Statements
Python provides statements to control loop execution:
# break - exit the loop
for i in range(10):
if i == 5:
break
print(i) # Prints 0, 1, 2, 3, 4
# continue - skip current iteration
for i in range(10):
if i % 2 == 0:
continue
print(i) # Prints 1, 3, 5, 7, 9
# else clause with for loop
for i in range(5):
print(i)
else:
print("Loop completed successfully")
# else clause with while loop
count = 0
while count < 3:
print(count)
count += 1
else:
print("While loop completed")
# break prevents else execution
for i in range(5):
if i == 3:
break
print(i)
else:
print("This won't print because of break")
Nested Loops
Loops can be nested inside other loops:
# Nested for loops
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} * {j} = {i*j}")
print() # Empty line
# Nested while loops
i = 1
while i <= 3:
j = 1
while j <= 3:
print(f"{i} * {j} = {i*j}")
j += 1
print()
i += 1
# Breaking out of nested loops
for i in range(5):
for j in range(5):
if i * j == 6:
print(f"Found at i={i}, j={j}")
break
else:
continue
break
List Comprehensions
List comprehensions provide a concise way to create lists:
# Basic list comprehension
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
# Nested comprehensions
matrix = [[i*j for j in range(3)] for i in range(3)]
print(matrix) # [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
# 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
squares_set = {x**2 for x in range(-5, 6)}
print(squares_set) # {0, 1, 4, 9, 16, 25}
Iterating Over Different Data Types
# Lists
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
# Tuples
coordinates = (3, 4, 5)
for coord in coordinates:
print(coord)
# Dictionaries
person = {"name": "Alice", "age": 25, "city": "NYC"}
for key in person:
print(f"{key}: {person[key]}")
for key, value in person.items():
print(f"{key}: {value}")
# Sets
colors = {"red", "green", "blue"}
for color in colors:
print(color) # Order not guaranteed
# Strings
for char in "Python":
print(char)
# Files
# with open("file.txt", "r") as file:
# for line in file:
# print(line.strip())
Loop Performance and Best Practices
- Use for loops for known iterations: When you know how many times to loop
- Use while loops for conditional repetition: When continuation depends on a condition
- Avoid modifying lists during iteration: Create new lists instead
- Use enumerate() for indices: When you need both index and value
- Prefer list comprehensions: For simple transformations
- Use break and continue sparingly: They can make code harder to follow
- Avoid deep nesting: Extract nested loops into functions
Common Loop Patterns
# Finding items
numbers = [1, 3, 5, 7, 9]
target = 5
for num in numbers:
if num == target:
print(f"Found {target}")
break
else:
print(f"{target} not found")
# Accumulating results
total = 0
for num in range(1, 11):
total += num
print(f"Sum: {total}") # 55
# Filtering with loops
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
evens = []
for num in numbers:
if num % 2 == 0:
evens.append(num)
print(evens) # [2, 4, 6, 8, 10]
# Using zip for parallel iteration
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
Loops are essential for automating repetitive tasks. Understanding when to use for vs while loops, and how to control loop execution with break and continue, is crucial for writing efficient Python code.