Beginner

Loops in Python

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.

What Are Loops?

A loop is a programming structure that repeats a block of code multiple times. Python gives you two main types of loops:

What is a for loop?

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)

What is a while loop?

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...")

How do they work?

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).

The Perfect Analogy

Think of loops like a conveyor belt in a factory. Each item on the belt represents one iteration of your loop:

In both cases, you're performing the same action (processing items) repeatedly, but the stopping mechanism differs.

Visual Understanding

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.

Real Examples: From Simple to Complex

Example 1: Basic for Loop with range()

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].

Example 2: Basic while Loop

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!

Example 3: Looping Through a List

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!

Example 4: Practical Sum Calculator

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

Example 5: Using break and continue

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

Hands-On Exercise: Sum Numbers 1 to 100

Let's build your loop skills by calculating the sum of all numbers from 1 to 100. Follow these steps:

Step 1: Create Your Python File

Create a new file called sum_calculator.py in your working directory.

Step 2: Write the Starter Code

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}")

Step 3: Add the for Loop

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}")

Step 4: Test Your Code

Run your script from the terminal:

python sum_calculator.py

Step 5: Expected Output

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!

Troubleshooting Tips

Common Mistakes to Avoid

1. Infinite Loops (The Never-Ending Story)

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.

2. Off-By-One Errors with range()

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.

3. Modifying a List While Iterating

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)

4. Forgetting to Update the Loop Variable

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!

5. Incorrect Indentation

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

6. Using = Instead of == in While Conditions

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

Mini-Project: Number Guessing Game

Goal: Build an interactive game where the player guesses a secret number between 1 and 10, with hints for each wrong guess.

Requirements

Step-by-Step Implementation

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!")

Expected Output

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!

Bonus Challenges

  1. Add guess counting: Track how many guesses the player needed
  2. Input validation: Check if the guess is between 1-10, handle invalid input
  3. Random secret number: Use import random and random.randint(1, 10) for variety
  4. Play again option: Wrap everything in another loop that asks "Play again? (yes/no)"
  5. Difficulty levels: Let players choose ranges (1-10 easy, 1-50 medium, 1-100 hard)

💡 Learning Tip: Try implementing one bonus challenge at a time. Test after each change to ensure everything still works!

Summary

Key Takeaways

What Makes Loops Special

Your Next Steps

Congratulations! 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! 🚀

🎯 Test Your Knowledge: Python Loops

Check your understanding with this quick quiz

1. What will range(2, 7) generate?

[2, 3, 4, 5, 6, 7]
[2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]
[3, 4, 5, 6, 7]

2. Which loop is best when you don't know how many iterations you need?

for loop
while loop
if statement
range loop

3. What does the break statement do?

Pauses the loop temporarily
Skips to the next iteration
Exits the loop immediately
Restarts the loop from the beginning

4. What causes an infinite loop?

Using range() incorrectly
A while loop condition that never becomes false
Forgetting to use break
Using a for loop on a large list
← Previous: Conditional Statements Next: Data Structures →