Master for and while loops to automate repetitive tasks
Imagine you need to send 100 personalized emails to your customers. Would you write the same code 100 times, changing only the recipient's name each time? Of course not! This is exactly where loops come to the rescue. Loops are one of programming's most powerful features—they let you repeat actions efficiently without drowning in copy-paste madness. Whether you're processing data, building games, or automating tasks, loops are your best friend.
A loop is a programming structure that repeats a block of code multiple times. Python gives you two main types of loops:
A for loop iterates over a sequence (like a list, string, or range of numbers) and executes code for each item. Think of it as going through items on a conveyor belt—you process each one until you've handled them all.
# Basic for loop syntax
for item in collection:
# Code to execute for each item
print(item)
A while loop repeats code as long as a condition remains true. It's like saying, "Keep doing this until something changes." This is perfect when you don't know in advance how many times you need to repeat something.
# Basic while loop syntax
while condition:
# Code to execute while condition is True
print("Still going...")
Unlike conditional statements (if) that run once, loops create a cycle. The for loop automatically moves to the next item after each iteration. The while loop checks its condition before each cycle—if the condition becomes false, the loop stops.
💡 Key Difference: Use for loops when you know what you're iterating over (a collection or range). Use while loops when you're waiting for a condition to change (like user input or a calculation reaching a threshold).
Think of loops like a conveyor belt in a factory. Each item on the belt represents one iteration of your loop:
for loop is like a belt with a fixed number of items. You process each item (apple, orange, banana) in order until the belt is empty.while loop is like a belt that keeps running until you press the stop button. The belt continues as long as the "keep running" condition is true.In both cases, you're performing the same action (processing items) repeatedly, but the stopping mechanism differs.
Here's how loops flow through your code:
# FOR LOOP FLOW
Start → Check if items remain in collection
↓ Yes
Process current item → Move to next item → Repeat
↓ No
Exit loop → Continue with rest of program
# WHILE LOOP FLOW
Start → Check condition
↓ True
Execute code block → Check condition again → Repeat
↓ False
Exit loop → Continue with rest of program
⚠️ Important: Every loop needs a way to end! A for loop ends when it runs out of items. A while loop ends when its condition becomes false. Without an exit strategy, you create an infinite loop that crashes your program.
The range() function generates a sequence of numbers, perfect for counting:
# Count from 1 to 5
for i in range(1, 6):
print("Count:", i)
# Output:
# Count: 1
# Count: 2
# Count: 3
# Count: 4
# Count: 5
💡 Range Syntax: range(start, stop, step) generates numbers from start up to (but not including) stop. range(1, 6) gives you [1, 2, 3, 4, 5].
A countdown using a while loop that checks a condition:
# Countdown from 3
n = 3
while n > 0:
print("n =", n)
n -= 1 # Decrease n by 1 each time
print("Blastoff!")
# Output:
# n = 3
# n = 2
# n = 1
# Blastoff!
Process each item in a collection with descriptive variable names:
# Iterate over a list of fruits
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
print(f"I love {fruit}s!")
# Output:
# I love apples!
# I love bananas!
# I love cherrys!
# I love dates!
Combine loops with accumulation—a common programming pattern:
# Calculate the sum of numbers 1 through 10
total = 0 # Initialize accumulator
for number in range(1, 11):
total += number # Add current number to total
print(f"Added {number}, total is now {total}")
print(f"\nFinal sum: {total}")
# Output shows progressive addition:
# Added 1, total is now 1
# Added 2, total is now 3
# ...
# Final sum: 55
Control loop flow with special keywords:
# Find the first even number divisible by 7
for num in range(1, 50):
if num % 2 != 0:
continue # Skip odd numbers
if num % 7 == 0:
print(f"Found it: {num}")
break # Stop searching once found
# Output: Found it: 14
Let's build your loop skills by calculating the sum of all numbers from 1 to 100. Follow these steps:
Create a new file called sum_calculator.py in your working directory.
Begin with a basic structure and a variable to store your sum:
# sum_calculator.py
# Calculate sum of numbers 1 to 100
total = 0 # This will store our running sum
# Your loop will go here
print(f"The sum of numbers 1 to 100 is: {total}")
Insert a for loop that adds each number to your total:
# sum_calculator.py
total = 0
for number in range(1, 101): # Remember: range(1, 101) gives 1-100
total += number # Same as: total = total + number
print(f"The sum of numbers 1 to 100 is: {total}")
Run your script from the terminal:
python sum_calculator.py
You should see:
The sum of numbers 1 to 100 is: 5050
💡 Bonus Challenge: Modify your code to also count how many even numbers appear in the range 1-100. Use an if statement inside your loop!
range(1, 101) not range(1, 100)total = 0 before the loop?Problem: Your program hangs and never finishes.
Why it happens: A while loop condition never becomes false.
# WRONG - Infinite loop!
while True:
print("This will never stop...")
# No way to exit!
# CORRECT - Proper exit condition
count = 0
while count < 5:
print("This will stop")
count += 1 # Ensures condition eventually becomes False
Solution: Always ensure your while loop condition will eventually become false, or use break to exit.
Problem: Your loop runs one time too many or too few.
Why it happens: Forgetting that range(5) generates [0, 1, 2, 3, 4], not [1, 2, 3, 4, 5].
# WRONG - Prints 0-4, not 1-5
for i in range(5):
print(i) # Outputs: 0, 1, 2, 3, 4
# CORRECT - Prints 1-5
for i in range(1, 6):
print(i) # Outputs: 1, 2, 3, 4, 5
Prevention: Remember: range(start, stop) stops BEFORE reaching the stop value.
Problem: Unexpected behavior or errors when changing a list during iteration.
# WRONG - Removing items while looping
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
numbers.remove(num) # Causes skipping!
# CORRECT - Loop over a copy
numbers = [1, 2, 3, 4, 5]
for num in numbers[:]: # [:] creates a copy
if num % 2 == 0:
numbers.remove(num)
Problem: While loop never progresses.
# WRONG - i never changes
i = 0
while i < 5:
print(i)
# Missing: i += 1 (This would cause infinite loop!)
# CORRECT - Update the variable
i = 0
while i < 5:
print(i)
i += 1 # Don't forget this!
Problem: Code runs when it shouldn't, or doesn't run when it should.
# WRONG - print is outside the loop
for i in range(3):
total = i * 2
print(total) # Only prints once after loop ends
# CORRECT - print inside the loop
for i in range(3):
total = i * 2
print(total) # Prints three times during loop
Problem: Assignment instead of comparison causes syntax errors.
# WRONG - Assignment, not comparison
x = 10
while x = 10: # SyntaxError!
print(x)
# CORRECT - Use comparison operator
x = 10
while x == 10:
print(x)
x -= 1
Goal: Build an interactive game where the player guesses a secret number between 1 and 10, with hints for each wrong guess.
Step 1: Create guessing_game.py and set up the secret number:
# guessing_game.py
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 10...")
secret = 7
guess = None # Will store player's guess
Step 2: Add the main game loop using while:
while guess != secret:
guess = int(input("Enter your guess (1-10): "))
# We'll add feedback here in the next step
Step 3: Implement the feedback logic with conditionals:
while guess != secret:
guess = int(input("Enter your guess (1-10): "))
if guess < secret:
print("Too low! Try again.")
elif guess > secret:
print("Too high! Try again.")
else:
print("🎉 Correct! You guessed it!")
print(f"The secret number was {secret}.")
Step 4: Complete the game with a welcome message:
# Complete guessing_game.py
print("Welcome to the Number Guessing Game!")
print("I'm thinking of a number between 1 and 10...\n")
secret = 7
guess = None
while guess != secret:
guess = int(input("Enter your guess (1-10): "))
if guess < secret:
print("Too low! Try again.\n")
elif guess > secret:
print("Too high! Try again.\n")
else:
print("\n🎉 Correct! You guessed it!")
print(f"The secret number was {secret}.")
print("\nThanks for playing!")
When you run the game, it should look like this:
Welcome to the Number Guessing Game!
I'm thinking of a number between 1 and 10...
Enter your guess (1-10): 5
Too low! Try again.
Enter your guess (1-10): 8
Too high! Try again.
Enter your guess (1-10): 7
🎉 Correct! You guessed it!
The secret number was 7.
Thanks for playing!
import random and random.randint(1, 10) for variety💡 Learning Tip: Try implementing one bonus challenge at a time. Test after each change to ensure everything still works!
range(start, stop, step) to generate number sequences for countingbreak exits a loop immediately, continue skips to the next iterationCongratulations! You've mastered one of programming's most essential concepts. Loops are everywhere in code—from processing files to building games to analyzing data. With this foundation, you're ready to automate tasks and write more powerful programs. Keep practicing, and remember: the best way to learn loops is to loop through practice exercises! 🚀
Check your understanding with this quick quiz
1. What will range(2, 7) generate?
2. Which loop is best when you don't know how many iterations you need?
3. What does the break statement do?
4. What causes an infinite loop?