Loops are like the repetitive engines of programming. Whether you’re looping through a grocery list, checking sensor readings, or printing out rows in a report—loops let your code repeat tasks without rewriting the same lines again and again.
This guide will walk you through Python’s two main types of loops: for loops and while loops. You’ll learn what they do, how they work, and when to use each one.
🌀 What Is a Loop in Programming?
A loop is a way to repeat a block of code multiple times.
Think of it like:
🔁 “Keep doing this task until a certain condition is met.”
Why are loops essential?
- They save time and space in code.
- They automate repetitive tasks.
- They make programs dynamic and responsive.
🔄 for vs. while Loops: What’s the Difference?
| Feature | for Loop | while Loop |
|---|---|---|
| Used When | You know how many times to loop | You don’t know how many times to loop |
| Structure | Iterates over items in a sequence | Repeats while a condition is true |
| Common Use Case | Loop through lists, strings, ranges | Wait for user input, run until a state |
🔁 Understanding the for Loop
📌 Syntax
pythonCopyEdit# Loop through a sequence of numbers
for i in range(5):
print(i)
💬 Breakdown
for: Starts the loopi: A variable that takes the value of each item in the sequencein: Keyword that connects the loop variable and the sequencerange(5): A built-in function that generates numbers from 0 to 4print(i): The body of the loop that runs each time
✅ Example 1: Looping through a list
pythonCopyEditfruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
➡️ Output:
nginxCopyEditapple
banana
cherry
✅ Example 2: Summing numbers with range()
pythonCopyEdittotal = 0
for num in range(1, 6): # 1 through 5
total += num
print("Total:", total)
➡️ Output:
makefileCopyEditTotal: 15
🔁 Understanding the while Loop
📌 Syntax
pythonCopyEdit# Repeat as long as a condition is true
count = 0
while count < 5:
print(count)
count += 1 # Increment to avoid infinite loop
💬 Breakdown
while: Starts the loopcount < 5: The condition to keep loopingprint(count): Executes if the condition is truecount += 1: Moves closer to stopping the loop
✅ Example 1: Waiting for correct user input
pythonCopyEditpassword = ""
while password != "python123":
password = input("Enter password: ")
print("Access granted!")
⚙️ Advanced Loop Features
🔚 break – Exit a loop early
pythonCopyEditfor number in range(10):
if number == 5:
break # Stop the loop when number is 5
print(number)
➡️ Output:
CopyEdit0
1
2
3
4
🔁 continue – Skip current iteration
pythonCopyEditfor number in range(5):
if number == 2:
continue # Skip the rest of this loop cycle
print(number)
➡️ Output:
CopyEdit0
1
3
4
😲 else with loops
pythonCopyEditfor i in range(3):
print(i)
else:
print("Loop finished normally")
elseruns only if the loop wasn’t broken early.
🚫 Common Mistakes & Gotchas
❗ Infinite loops
pythonCopyEdit# Oops! count never increases
count = 0
while count < 5:
print("Looping forever...")
✅ Fix: Make sure your condition will eventually become False.
❗ Off-by-one errors
pythonCopyEdit# Only runs 4 times instead of 5
for i in range(1, 5): # 1 to 4, NOT 1 to 5
print(i)
✅ Fix: Understand that range(start, end) goes up to but not including end.
❗ Modifying a list while looping over it
pythonCopyEdititems = [1, 2, 3]
for item in items:
items.remove(item) # Bad idea!
✅ Fix: Loop over a copy: for item in items[:]
🧠 Mini-Challenges: Try It Yourself
- Print even numbers from 2 to 20 using a
forloop - Create a
whileloop that asks the user to type “yes” to continue - Use a
forloop to find the sum of all numbers from 1 to 100 - Make a loop that skips printing the number 4, but prints others from 1 to 10
- Write a loop that breaks when a number divisible by 7 is entered
📋 Summary Table: for vs. while
| Feature | for Loop | while Loop |
|---|---|---|
| Known number of steps | ✅ Best suited | 🚫 Less ideal |
| Runs on condition | 🚫 Not directly | ✅ Runs until condition is false |
| Iterating over sequence | ✅ Perfect for lists, strings, ranges | 🚫 Manual setup required |
| Risk of infinite loop | Low (automatic stop) | Higher (needs careful condition) |
| Flexibility | Moderate | High (more control flow possibilities) |
🎯 Real-World Analogies
forloop = A playlist that plays each song in order and stops at the end.whileloop = A song on repeat that plays until you hit the stop button.
👩💻👨💻 Final Thoughts
Loops are one of the most powerful tools in programming. They help us repeat, automate, and control our code. Whether you’re printing, checking, collecting, or calculating—loops give your code rhythm and flexibility.