Course Progress20% complete
🐍 Python Basics Topic 20 / 100
⏱ 10 min read

for Loops

Repeating actions over every item in a collection — one of the most useful and most used features in all of Python.

"Without loops, a program that processes 1000 students would need 1000 lines of code. With a for loop — just 3 lines."

— ShurAI

Why Do We Need Loops?

Imagine you want to greet 5 friends by name. Without a loop, you write this:

python — without a loop (tedious)
# ❌ Writing the same thing 5 times — not scalable
print("Hello, Riya!")
print("Hello, Arjun!")
print("Hello, Sneha!")
print("Hello, Vikram!")
print("Hello, Kavya!")

Now imagine it is 500 students. A for loop handles any number with the exact same code:

python — with a for loop
# ✅ Works for 5 or 5000 names — same code
friends = ["Riya", "Arjun", "Sneha", "Vikram", "Kavya"]

for name in friends:
    print(f"Hello, {name}!")
output
Hello, Riya!
Hello, Arjun!
Hello, Sneha!
Hello, Vikram!
Hello, Kavya!

Anatomy of a for Loop

for name in friends :
code to run each time
keyword
loop variable
(one item at a time)
keyword
the collection
to loop over
required
colon

Counting with range()

range() generates a sequence of numbers. It is the most common thing you loop over when you just need to repeat something N times:

python
# range(5) → 0, 1, 2, 3, 4  (starts at 0, stops before 5)
for i in range(5):
    print(f"Count: {i}")
# Count: 0  Count: 1  Count: 2  Count: 3  Count: 4

# range(1, 6) → 1, 2, 3, 4, 5  (start, stop)
for i in range(1, 6):
    print(i, end=" ")
# 1 2 3 4 5

# range(1, 11, 2) → 1, 3, 5, 7, 9  (start, stop, step)
for i in range(1, 11, 2):
    print(i, end=" ")
# 1 3 5 7 9

# Count DOWN with negative step
for i in range(10, 0, -1):
    print(i, end=" ")
# 10 9 8 7 6 5 4 3 2 1

Looping Over a String

A string is just a collection of characters — you can loop over each letter:

python
name = "Python"

for letter in name:
    print(letter, end=" ")
# P y t h o n

Loop + if = Very Powerful

Combine a loop with an if statement to process each item selectively:

python — find passing students
scores = [45, 82, 30, 91, 55, 73, 28]

print("Passing scores (>= 60):")
for score in scores:
    if score >= 60:
        print(f"  ✅ {score}")
    else:
        print(f"  ❌ {score}")
output
Passing scores (>= 60):
  ❌ 45
  ✅ 82
  ❌ 30
  ✅ 91
  ❌ 55
  ✅ 73
  ❌ 28

The Accumulator Pattern — Very Common

Start with a variable set to zero. Add to it each loop. This is how you calculate totals, averages, and counts:

python — calculate class average
marks = [72, 88, 91, 65, 79]
total = 0   # accumulator starts at 0

for m in marks:
    total = total + m    # add each mark to total

average = total / len(marks)
print(f"Total  : {total}")    # Total  : 395
print(f"Average: {average:.1f}")  # Average: 79.0

Real Example — Shopping Cart Total 🛒

python
cart = [
    ("Rice 5kg",      280),
    ("Dal 1kg",       120),
    ("Milk 2L",        90),
    ("Bread",          45),
    ("Eggs (12)",      96),
]

total = 0
print(f"{'Item':16} {'Price':>8}")
print("-" * 26)

for item, price in cart:
    print(f"{item:16} Rs.{price:>5}")
    total += price

print("-" * 26)
print(f"{'TOTAL':16} Rs.{total:>5}")

# 10% discount if total over 500
if total > 500:
    discount = total * 0.10
    print(f"Discount (10%) : -Rs.{discount:.0f}")
    print(f"{'YOU PAY':16} Rs.{total - discount:>5.0f}")
output
Item              Price
--------------------------
Rice 5kg          Rs.  280
Dal 1kg           Rs.  120
Milk 2L           Rs.   90
Bread             Rs.   45
Eggs (12)         Rs.   96
--------------------------
TOTAL             Rs.  631
Discount (10%) : -Rs.63
YOU PAY           Rs.  568

Bonus — Times Table Generator ✖️

python
n = int(input("Times table for which number? "))

print(f"\n--- {n} Times Table ---")
for i in range(1, 11):
    print(f"{n} × {i:2} = {n * i}")
terminal
Times table for which number? 7

--- 7 Times Table ---
7 ×  1 = 7
7 ×  2 = 14
7 ×  3 = 21
7 ×  4 = 28
7 ×  5 = 35
7 ×  6 = 42
7 ×  7 = 49
7 ×  8 = 56
7 ×  9 = 63
7 × 10 = 70

"The for loop is Python's workhorse. Once you really understand it, you will see uses for it everywhere — in data, in files, in games, in everything."

— ShurAI

🧠 Quiz — Question 1

What does range(5) produce?

🧠 Quiz — Question 2

In for fruit in fruits:, what is fruit?

🧠 Quiz — Question 3

What does range(2, 10, 2) produce?

🧠 Quiz — Question 4

What is the accumulator pattern used for?