Loops: Repeating Actions Like a Pro
Welcome to the world of automation! Loops are your programβs way of doing repetitive tasks without writing the same code over and over.
What are Loops?
Loops are like washing machines:
- You put in the clothes (data)
- Set the cycle (loop type)
- The machine does the work repeatedly
- Stops when the cycle is complete
The while Loop - Repeat Until Condition Changes
Real-Life Example: Filling a Glass
glass_capacity = 250 # ml
current_water = 0
pour_amount = 50 # ml per pour
print("Filling glass with water...")
while current_water < glass_capacity:
current_water += pour_amount
print(f"Poured {pour_amount}ml. Total: {current_water}ml")
if current_water > glass_capacity:
overflow = current_water - glass_capacity
print(f"Overflow: {overflow}ml")
current_water = glass_capacity
print(f"Glass is now full: {current_water}ml")
Basic while Loop
# Count from 1 to 5
counter = 1
while counter <= 5:
print(f"Count: {counter}")
counter += 1 # Don't forget to update the condition!
print("Counting complete!")
Real-Life Example: ATM Withdrawal
balance = 1000
withdraw_amount = 100
print("ATM Withdrawal Simulator")
print(f"Initial balance: ${balance}")
while balance >= withdraw_amount:
balance -= withdraw_amount
print(f"Withdrew ${withdraw_amount}. Remaining: ${balance}")
print("Insufficient funds for another withdrawal.")
print(f"Final balance: ${balance}")
The for Loop - Repeat for Each Item
Real-Life Example: Grocery Shopping
shopping_list = ["apples", "bananas", "milk", "bread", "eggs"]
print("Shopping list:")
for item in shopping_list:
print(f"β {item}")
print("\nStarting to shop...")
for item in shopping_list:
print(f"β
Bought {item}")
print("Shopping complete!")
Basic for Loop with Lists
fruits = ["apple", "banana", "orange", "grape", "kiwi"]
print("My favorite fruits:")
for fruit in fruits:
print(f"I love {fruit}s!")
print(f"Total fruits: {len(fruits)}")
The range() Function - Creating Number Sequences
Basic range() Usage
# range(end) - from 0 to end-1
print("Counting from 0 to 4:")
for i in range(5):
print(f"Number: {i}")
print()
# range(start, end) - from start to end-1
print("Counting from 1 to 5:")
for i in range(1, 6):
print(f"Number: {i}")
print()
# range(start, end, step) - with custom step
print("Even numbers from 0 to 10:")
for i in range(0, 11, 2):
print(f"Even: {i}")
print()
# Counting backwards
print("Countdown from 10 to 1:")
for i in range(10, 0, -1):
print(f"T-minus {i}...")
print("Blast off! π")
Real-Life Example: Multiplication Table
number = 7
print(f"Multiplication table for {number}:")
for i in range(1, 13): # 1 to 12
result = number * i
print(f"{number} Γ {i} = {result}")
print("Table complete!")
Loop Control Statements
break - Exit the Loop Immediately
# Find the first even number
numbers = [1, 3, 5, 7, 8, 9, 10]
print("Looking for the first even number...")
for num in numbers:
print(f"Checking: {num}")
if num % 2 == 0: # If even
print(f"Found first even number: {num}")
break # Exit the loop immediately
print("Search complete.")
continue - Skip to Next Iteration
# Print only odd numbers
print("Odd numbers from 1 to 10:")
for num in range(1, 11):
if num % 2 == 0: # If even, skip it
continue
print(f"Odd number: {num}")
print("All odd numbers printed.")
Real-Life Example: Quality Control
products = ["good", "defective", "good", "good", "defective", "good"]
passed_products = 0
print("Quality control check:")
for product in products:
if product == "defective":
print("β Defective product found - skipping")
continue
print(f"β
{product} product passed")
passed_products += 1
print(f"Total products passed: {passed_products}")
Nested Loops - Loops Inside Loops
Real-Life Example: Weekly Meal Plan
days = ["Monday", "Tuesday", "Wednesday"]
meals = ["Breakfast", "Lunch", "Dinner"]
print("Weekly Meal Plan:")
for day in days:
print(f"\n{day}:")
for meal in meals:
print(f" - {meal}: Plan your meal")
print("\nMeal planning complete!")
Multiplication Table Grid
print("Multiplication Table (1-5):")
print(" ", end="")
for i in range(1, 6):
print("3d", end="")
print()
for i in range(1, 6):
print("3d|", end="")
for j in range(1, 6):
print("3d", end="")
print()
# Output:
# 1 2 3 4 5
# 1| 1 2 3 4 5
# 2| 2 4 6 8 10
# 3| 3 6 9 12 15
# 4| 4 8 12 16 20
# 5| 5 10 15 20 25
else with Loops
Real-Life Example: Job Search
job_requirements = ["Python", "SQL", "Excel"]
my_skills = ["Python", "JavaScript", "SQL", "Excel"]
print("Checking job requirements...")
for requirement in job_requirements:
if requirement not in my_skills:
print(f"β Missing skill: {requirement}")
break
else: # This runs only if no break occurred
print("β
You meet all requirements! Apply for the job!")
print("Skill check complete.")
Prime Number Checker
def is_prime(number):
if number <= 1:
return False
for divisor in range(2, int(number ** 0.5) + 1):
if number % divisor == 0:
return False
else: # No divisor found
return True
# Test the function
test_numbers = [2, 3, 4, 5, 17, 18, 23]
for num in test_numbers:
if is_prime(num):
print(f"{num} is prime")
else:
print(f"{num} is not prime")
Common Loop Patterns
Pattern 1: Accumulator Pattern
# Calculate sum of numbers
numbers = [1, 2, 3, 4, 5]
total = 0
for num in numbers:
total += num # Accumulate the sum
print(f"Sum of {numbers} = {total}")
# Count occurrences
text = "hello world"
letter_counts = {}
for letter in text:
if letter.isalpha(): # Only count letters
letter = letter.lower()
if letter in letter_counts:
letter_counts[letter] += 1
else:
letter_counts[letter] = 1
print("Letter counts:", letter_counts)
Pattern 2: Find Maximum/Minimum
scores = [85, 92, 78, 96, 88]
highest_score = scores[0] # Start with first score
for score in scores[1:]: # Check remaining scores
if score > highest_score:
highest_score = score
print(f"Highest score: {highest_score}")
# Find minimum
lowest_score = scores[0]
for score in scores[1:]:
if score < lowest_score:
lowest_score = score
print(f"Lowest score: {lowest_score}")
Pattern 3: Filter Items
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print(f"Even numbers: {even_numbers}")
# Filter with condition
grades = [85, 92, 78, 96, 88, 75, 89]
passing_grades = []
for grade in grades:
if grade >= 80:
passing_grades.append(grade)
print(f"Passing grades: {passing_grades}")
Infinite Loops (And How to Avoid Them)
Dangerous: Infinite while Loop
# β This will run forever!
# counter = 1
# while counter <= 5:
# print(counter)
# # Forgot to increment counter!
# β
Correct version
counter = 1
while counter <= 5:
print(counter)
counter += 1 # Don't forget this!
Safe Infinite Loop with Break
# Menu system
while True:
print("\nMenu:")
print("1. Say hello")
print("2. Say goodbye")
print("3. Exit")
choice = input("Enter choice (1-3): ")
if choice == "1":
print("Hello!")
elif choice == "2":
print("Goodbye!")
elif choice == "3":
print("Exiting...")
break # Exit the loop
else:
print("Invalid choice. Try again.")
Loop Best Practices
1. Use the Right Loop Type
# β
Use for loop when you know the number of iterations
for i in range(5):
print(f"Iteration {i}")
# β
Use while loop when you don't know how many iterations
user_input = ""
while user_input != "quit":
user_input = input("Enter something (or 'quit' to exit): ")
2. Avoid Modifying Lists While Iterating
# β Dangerous - modifying list while iterating
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
numbers.remove(num) # This can cause problems!
print(numbers) # Unpredictable result
# β
Safe - create new list
numbers = [1, 2, 3, 4, 5]
even_numbers = []
for num in numbers:
if num % 2 == 0:
even_numbers.append(num)
print(f"Original: {numbers}")
print(f"Evens: {even_numbers}")
3. Use enumerate() for Index and Value
fruits = ["apple", "banana", "orange"]
# β Manual index tracking
index = 0
for fruit in fruits:
print(f"{index}: {fruit}")
index += 1
# β
Use enumerate()
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Start index from 1
for index, fruit in enumerate(fruits, start=1):
print(f"{index}. {fruit}")
Practice Exercises
Exercise 1: Number Pyramid
Create a program that prints a pyramid of numbers:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Exercise 2: Password Guessing Game
Create a game where the user has 3 attempts to guess a password.
Exercise 3: Fibonacci Sequence
Generate the first 10 numbers in the Fibonacci sequence.
Exercise 4: Shopping Cart Total
Calculate the total price of items in a shopping cart with tax.
Exercise 5: Number Guessing Game with Hints
Improve the number guessing game to give βhotterβ or βcolderβ hints.
Summary
Loops make your code powerful by automating repetitive tasks:
whileloops: Repeat until a condition becomes falseforloops: Repeat for each item in a sequencerange(): Generate number sequences for loopsbreak: Exit loop immediatelycontinue: Skip to next iterationelsewith loops: Execute code when loop completes normally
Remember:
- Always ensure your loop has an exit condition
- Use
forloops when you know the number of iterations - Use
whileloops for indefinite repetition - Be careful with infinite loops
- Donβt modify lists while iterating over them
Next: Functions - reusable blocks of code! π§±