Python For Loops – Repeat Like a Pro!
Last Updated: September 2025
Want Python to do the same thing again and again without writing it multiple times? That’s where for
loops come to the rescue! They’re simple, powerful, and everywhere once you start coding.
What’s a For Loop?
A for
loop lets you go through a collection like a list or string one item at a time. Instead of repeating code, you just tell Python: “For every item in this list, do this thing.” Easy and neat!
Example 1: Looping Through a List
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(fruit)
🔹Python goes through each fruit and prints it one by one. No need to repeat lines of code!
Example 2: Using range()
for Numbers
for i in range(5):
print(i)
🔹range(5)
means numbers from 0 to 4. Perfect when you want to repeat something a certain number of times!
Example 3: Looping Through a String
for char in "Python":
print(char)
🔹Each character is treated like an item in a list. Python loops through them one by one!
Example 4: Using break
to Stop Early
for i in range(1, 6):
if i == 4:
break
print(i)
🔹break
stops the loop when the condition is met. Here, it stops before reaching 4!
Example 5: Skipping Items with continue
for i in range(1, 6):
if i == 3:
continue
print(i)
🔹continue
skips the current iteration. Here, it jumps over 3 and keeps going!
Example 6: Looping with Else
for i in range(3):
print(i)
else:
print("Loop is done!")
🔹You can attach else
to run code after the loop finishes normally. Handy for cleanup or final messages!
Example 7: Build a Shopping Cart Total Calculator
cart = [
{"name": "T-shirt", "price": 499},
{"name": "Jeans", "price": 899},
{"name": "Sneakers", "price": 1299},
{"name": "Cap", "price": 199}
]
total = 0
for item in cart:
print(f"Adding {item['name']} for ₹{item['price']}")
total += item["price"]
print("------------------------")
print(f"Total amount: ₹{total}")
🔹This program goes through each item in the shopping cart, prints it, and keeps adding the price to get the final total!
Why Use For Loops?
- They make your code shorter and easier to read.
- You can loop through lists, strings, dictionaries, and more.
- They’re perfect when you know how many items you want to go through!
Common Errors
Forgetting to indent the loop block properly can lead to syntax errors. Always make sure your loop contents are indented under the for
statement!
Practice Time!
Create a list of your favorite games, then use a for
loop to print them out one by one. Add a condition to skip one of them using continue
. See how it works!