Loops in Python
Loops are fundamental programming structures that allow you to repeat code multiple times. Whether you're processing items in a list, counting numbers, or running a program until a condition is met, loops make it possible. Python provides two main types of loops: for loops and while loops.
Why Use Loops?
Loops help you:
- Avoid repetition: Write code once, run it many times
- Process collections: Iterate through lists, strings, dictionaries
- Automate tasks: Repeat actions until a goal is achieved
- Handle unknown quantities: Process data when you don't know how much there is
- Make programs dynamic: Respond to user input or changing conditions
The for Loop
The for loop iterates over a sequence (list, string, range, etc.) and executes code for each item.
Basic for Loop Syntax
# Loop through a list
fruits = ['apple', 'banana', 'cherry', 'date']
for fruit in fruits:
print(f"I like {fruit}")
Output:
I like apple
I like banana
I like cherry
I like date
Looping Through Different Types
# Loop through a string (iterates over characters)
word = "Python"
for letter in word:
print(letter)
# Loop through a range of numbers
for number in range(5):
print(f"Count: {number}")
# Loop with start and end
for number in range(1, 6):
print(number)
# Loop with step
for number in range(0, 10, 2): # Count by 2s
print(number)
The range() Function
The range() function generates sequences of numbers.
# range(stop): 0 to stop-1
for i in range(5):
print(i) # 0, 1, 2, 3, 4
# range(start, stop): start to stop-1
for i in range(2, 7):
print(i) # 2, 3, 4, 5, 6
# range(start, stop, step): with custom increment
for i in range(0, 20, 5):
print(i) # 0, 5, 10, 15
# Counting backwards
for i in range(10, 0, -1):
print(i) # 10, 9, 8, ..., 1
Practical range() Examples
# Print multiplication table
number = 7
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")
# Sum numbers from 1 to 100
total = 0
for i in range(1, 101):
total += i
print(f"Sum of 1 to 100: {total}")
# Generate list of squares
squares = []
for i in range(1, 11):
squares.append(i ** 2)
print(f"Squares: {squares}")
The while Loop
The while loop repeats as long as a condition is True.
Basic while Loop
# Count to 5
count = 1
while count <= 5:
print(f"Count is: {count}")
count += 1
print("Done counting!")
while Loop with User Input
# Keep asking until correct password
correct_password = "secret123"
password = ""
while password != correct_password:
password = input("Enter password: ")
if password != correct_password:
print("Incorrect! Try again.")
print("Access granted!")
Infinite Loops (Use with Caution)
# Infinite loop with break condition
while True:
user_input = input("Enter 'quit' to exit: ")
if user_input.lower() == 'quit':
print("Goodbye!")
break
print(f"You entered: {user_input}")
Loop Control Statements
break: Exit Loop Early
# Stop when we find what we're looking for
numbers = [1, 5, 8, 12, 15, 20, 25]
for num in numbers:
if num > 15:
print(f"Found a number greater than 15: {num}")
break
print(f"Checking {num}")
# Search for item in list
names = ['Alice', 'Bob', 'Charlie', 'Diana']
search_name = 'Charlie'
for name in names:
if name == search_name:
print(f"Found {search_name}!")
break
else:
print(f"{search_name} not found")
continue: Skip to Next Iteration
# Skip even numbers
for i in range(1, 11):
if i % 2 == 0:
continue # Skip the rest of this iteration
print(f"Odd number: {i}")
# Process only valid data
scores = [85, -1, 92, 0, 78, -5, 88]
for score in scores:
if score < 0:
print(f"Skipping invalid score: {score}")
continue
print(f"Valid score: {score}")
pass: Do Nothing (Placeholder)
# Placeholder for future code
for i in range(5):
if i == 3:
pass # TODO: Add special handling later
print(i)
# Empty loop body
for item in []:
pass # Does nothing but is syntactically required
Loop else Clause
Python loops can have an else clause that executes if the loop completes normally (without break).
# Check if a number is prime
number = 17
is_prime = True
for i in range(2, number):
if number % i == 0:
print(f"{number} is not prime (divisible by {i})")
is_prime = False
break
else:
# This runs only if break was NOT called
print(f"{number} is prime!")
# Search example
shopping_list = ['milk', 'bread', 'eggs', 'butter']
item_to_find = 'cheese'
for item in shopping_list:
if item == item_to_find:
print(f"Found {item_to_find}!")
break
else:
print(f"{item_to_find} not in shopping list")
Nested Loops
Loops can be placed inside other loops.
# Multiplication table
for i in range(1, 6):
for j in range(1, 6):
print(f"{i} x {j} = {i*j:2d}", end=" ")
print() # New line after each row
# Print a pattern
for i in range(5):
for j in range(i + 1):
print("*", end="")
print()
# Process 2D data
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for value in row:
print(value, end=" ")
print()
Breaking from Nested Loops
# Find first occurrence in 2D structure
found = False
data = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
target = 5
for i, row in enumerate(data):
for j, value in enumerate(row):
if value == target:
print(f"Found {target} at position ({i}, {j})")
found = True
break
if found:
break
Looping Through Collections
Enumerate: Get Index and Value
# Get both index and value
fruits = ['apple', 'banana', 'cherry']
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Start counting from 1
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")
Zip: Loop Through Multiple Lists
# Pair up elements from two lists
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# Zip works with any number of iterables
scores_math = [85, 90, 78]
scores_english = [88, 85, 92]
scores_science = [90, 87, 85]
for name, math, english, science in zip(names, scores_math, scores_english, scores_science):
average = (math + english + science) / 3
print(f"{name}: Math={math}, English={english}, Science={science}, Avg={average:.1f}")
Looping Through Dictionaries
# Dictionary loop basics
student = {
'name': 'Alice',
'age': 20,
'grade': 'A',
'gpa': 3.8
}
# Loop through keys
for key in student:
print(key)
# Loop through values
for value in student.values():
print(value)
# Loop through key-value pairs
for key, value in student.items():
print(f"{key}: {value}")
# Real example: Calculate total
prices = {'apple': 0.5, 'banana': 0.3, 'cherry': 0.2}
quantities = {'apple': 10, 'banana': 15, 'cherry': 20}
total = 0
for item in prices:
cost = prices[item] * quantities[item]
print(f"{item}: ${cost:.2f}")
total += cost
print(f"Total: ${total:.2f}")
List Comprehensions (Compact Loops)
List comprehensions provide a concise way to create lists.
# Traditional loop
squares = []
for i in range(1, 11):
squares.append(i ** 2)
# List comprehension (more Pythonic)
squares = [i ** 2 for i in range(1, 11)]
print(squares)
# With condition
even_squares = [i ** 2 for i in range(1, 11) if i % 2 == 0]
print(even_squares)
# Transform strings
names = ['alice', 'bob', 'charlie']
capitalized = [name.capitalize() for name in names]
print(capitalized)
# Nested comprehension
matrix = [[i*j for j in range(1, 4)] for i in range(1, 4)]
print(matrix)
Practical Examples
Example 1: Validate User Input
# Keep asking until valid input
while True:
age = input("Enter your age (1-120): ")
if not age.isdigit():
print("Please enter a number!")
continue
age = int(age)
if age < 1 or age > 120:
print("Age must be between 1 and 120!")
continue
print(f"Thank you! Your age is {age}")
break
Example 2: Calculate Statistics
# Calculate statistics from a list of numbers
numbers = [15, 23, 8, 42, 16, 31, 27, 19]
# Find minimum and maximum
minimum = numbers[0]
maximum = numbers[0]
for num in numbers:
if num < minimum:
minimum = num
if num > maximum:
maximum = num
print(f"Min: {minimum}, Max: {maximum}")
# Calculate average
total = 0
for num in numbers:
total += num
average = total / len(numbers)
print(f"Average: {average:.2f}")
# Count values above average
above_avg = 0
for num in numbers:
if num > average:
above_avg += 1
print(f"Numbers above average: {above_avg}")
Example 3: Generate Fibonacci Sequence
# Generate first n Fibonacci numbers
n = 10
fibonacci = []
a, b = 0, 1
for _ in range(n):
fibonacci.append(a)
a, b = b, a + b
print(f"First {n} Fibonacci numbers:")
print(fibonacci)
Example 4: Simple Menu System
# Interactive menu
while True:
print("\n=== Main Menu ===")
print("1. Calculate area")
print("2. Calculate perimeter")
print("3. Exit")
choice = input("Enter choice (1-3): ")
if choice == '1':
length = float(input("Enter length: "))
width = float(input("Enter width: "))
area = length * width
print(f"Area: {area:.2f}")
elif choice == '2':
length = float(input("Enter length: "))
width = float(input("Enter width: "))
perimeter = 2 * (length + width)
print(f"Perimeter: {perimeter:.2f}")
elif choice == '3':
print("Goodbye!")
break
else:
print("Invalid choice! Please try again.")
Example 5: Process Files or Data
# Process a list of transactions
transactions = [
{'type': 'deposit', 'amount': 100},
{'type': 'withdrawal', 'amount': 50},
{'type': 'deposit', 'amount': 200},
{'type': 'withdrawal', 'amount': 75},
{'type': 'deposit', 'amount': 150}
]
balance = 0
for transaction in transactions:
if transaction['type'] == 'deposit':
balance += transaction['amount']
print(f"Deposited ${transaction['amount']}, Balance: ${balance}")
elif transaction['type'] == 'withdrawal':
if balance >= transaction['amount']:
balance -= transaction['amount']
print(f"Withdrew ${transaction['amount']}, Balance: ${balance}")
else:
print(f"Insufficient funds for ${transaction['amount']} withdrawal")
print(f"\nFinal balance: ${balance}")
Common Loop Patterns
Pattern 1: Accumulator
# Sum all numbers
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num
print(f"Sum: {total}")
Pattern 2: Counter
# Count specific items
grades = ['A', 'B', 'A', 'C', 'A', 'B', 'D', 'A']
a_count = 0
for grade in grades:
if grade == 'A':
a_count += 1
print(f"Number of A's: {a_count}")
Pattern 3: Filter
# Extract items that meet criteria
numbers = [1, 15, 8, 42, 16, 31, 27, 5]
large_numbers = []
for num in numbers:
if num > 20:
large_numbers.append(num)
print(f"Large numbers: {large_numbers}")
Pattern 4: Transform
# Convert all items
celsius = [0, 10, 20, 30, 40]
fahrenheit = []
for temp in celsius:
f_temp = (temp * 9/5) + 32
fahrenheit.append(f_temp)
print(f"Fahrenheit: {fahrenheit}")
Common Mistakes and Solutions
Mistake 1: Modifying List While Iterating
# WRONG: Modifying list during iteration
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
numbers.remove(num) # Dangerous!
# CORRECT: Create new list
numbers = [1, 2, 3, 4, 5]
odd_numbers = []
for num in numbers:
if num % 2 != 0:
odd_numbers.append(num)
# Or use list comprehension
odd_numbers = [num for num in numbers if num % 2 != 0]
Mistake 2: Forgetting to Increment in while Loop
# WRONG: Infinite loop
# count = 1
# while count <= 5:
# print(count)
# # Forgot to increment!
# CORRECT:
count = 1
while count <= 5:
print(count)
count += 1 # Don't forget this!
Mistake 3: Off-by-One Errors
# Be careful with range boundaries
# range(5) gives 0, 1, 2, 3, 4 (NOT 5)
for i in range(5):
print(i) # Prints 0-4
# To include 5:
for i in range(6):
print(i) # Prints 0-5
# Or use start and stop:
for i in range(1, 6):
print(i) # Prints 1-5
Practice Exercises
Exercise 1: FizzBuzz
Print numbers 1-100, but:
- Print "Fizz" for multiples of 3
- Print "Buzz" for multiples of 5
- Print "FizzBuzz" for multiples of both
Exercise 2: Password Validator
Create a password validator that checks:
- Minimum 8 characters
- At least one uppercase letter
- At least one digit
- Keep prompting until valid
Exercise 3: Shopping Cart
Build a shopping cart that:
- Shows menu of items with prices
- Lets user add items
- Calculates total
- Allows checkout or continue shopping
Sample Solutions
Exercise 1:
for i in range(1, 101):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
Exercise 2:
while True:
password = input("Enter password: ")
if len(password) < 8:
print("Password must be at least 8 characters")
continue
has_upper = False
has_digit = False
for char in password:
if char.isupper():
has_upper = True
if char.isdigit():
has_digit = True
if not has_upper:
print("Password must contain an uppercase letter")
continue
if not has_digit:
print("Password must contain a digit")
continue
print("Password is valid!")
break
Exercise 3:
items = {
'apple': 0.5,
'banana': 0.3,
'orange': 0.6,
'milk': 2.5
}
cart = []
while True:
print("\n=== Shop Menu ===")
for item, price in items.items():
print(f"{item}: ${price:.2f}")
print("\nCommands: add <item>, checkout, quit")
command = input("Enter command: ").lower().split()
if command[0] == 'add' and len(command) > 1:
item = command[1]
if item in items:
cart.append(item)
print(f"Added {item}")
else:
print("Item not found")
elif command[0] == 'checkout':
total = sum(items[item] for item in cart)
print(f"\nItems: {cart}")
print(f"Total: ${total:.2f}")
break
elif command[0] == 'quit':
break
Key Takeaways
forloops iterate over sequences (lists, strings, ranges)whileloops repeat while a condition is Truerange()generates number sequencesbreakexits a loop immediatelycontinueskips to the next iterationpassdoes nothing (placeholder)- Loop
elseexecutes if loop completes normally enumerate()gives both index and valuezip()pairs up multiple iterables- List comprehensions provide compact syntax
- Always ensure while loops can exit (avoid infinite loops)
What's Next?
Now that you understand loops, you're ready for:
- Lists and Tuples - Collections that you'll loop through
- Dictionaries and Sets - More data structures
- Functions - Organize repeated code
Loops are the workhorses of programming. Practice with different types of loops and patterns to become fluent in controlling program flow!
