Lesson 7 of 12

Python Loops (for and while)

A loop repeats a block of code. Instead of writing print() ten times, you write it once and let the loop run it ten times, or once for every item in a list, however long that list is. There are two Python loops: for, which goes through a collection, and while, which repeats as long as a condition is true. Both use the indented blocks you learnt in Python Conditions.

The for loop

A Python for loop takes each item of a sequence in turn, stores it in a variable, and runs the block. It works with lists, strings, tuples, dictionaries, files and more. There is no counter to manage, so there are fewer chances for mistakes.

temples = ["Meenakshi", "Brihadeeswarar", "Kapaleeshwarar"]

for temple in temples:
    print(f"Visit the {temple} temple")

for letter in "Ooty":
    print(letter, end=" ")
print()
Output
Visit the Meenakshi temple
Visit the Brihadeeswarar temple
Visit the Kapaleeshwarar temple
O o t y

The loop variable (temple) gets a new value each round. Choose a singular name for it and a plural name for the list, as here; it makes the code read naturally. The empty print() at the end simply finishes the line started with end=" ".

Counting with range()

To repeat something a fixed number of times, loop over range(). It produces numbers on demand without building a list in memory.

CallNumbers produced
range(5)0, 1, 2, 3, 4
range(1, 6)1, 2, 3, 4, 5
range(0, 20, 5)0, 5, 10, 15
range(10, 0, -3)10, 7, 4, 1

Like slices, range() stops before its end value. That is why range(1, 6) is the right way to count from 1 to 5.

number = 8
for i in range(1, 6):
    print(f"{number} x {i} = {number * i}")

monthly_sip = 2500
total = 0
for month in range(12):
    total += monthly_sip
print(f"Invested in a year: ₹{total:,}")
Output
8 x 1 = 8
8 x 2 = 16
8 x 3 = 24
8 x 4 = 32
8 x 5 = 40
Invested in a year: ₹30,000

The second loop shows the accumulator pattern: start with a variable at zero before the loop, and add to it on every round. You will use it constantly in Python loops, for totals, counts and averages.

The while loop

A while loop checks its condition before every round and stops when the condition becomes false. Use it when you do not know in advance how many rounds you need, for example “keep doubling until the value passes a target”.

savings = 10000
goal = 50000
months = 0

while savings < goal:
    savings += 4000
    months += 1

print(f"Goal reached in {months} months, savings ₹{savings}")
Output
Goal reached in 10 months, savings ₹50000

Watch out: If nothing inside the loop changes the condition, it never becomes false and the loop runs forever. If that happens, press Ctrl+C in the terminal to stop the program, then check that your loop updates the variable it tests.

break, continue and else

  • break leaves the loop immediately.
  • continue skips the rest of this round and moves to the next item.
  • A loop can have an else block. It runs only if the loop finished without hitting break, which is handy for “searched everything and did not find it” messages.
orders = [450, -20, 0, 1200, 25000, 300]

for amount in orders:
    if amount <= 0:
        continue
    if amount > 20000:
        print(f"₹{amount} needs manager approval. Stopping.")
        break
    print(f"Processed ₹{amount}")

pincodes = [600001, 641001, 625001]
for code in pincodes:
    if code == 605001:
        print("Puducherry pincode found")
        break
else:
    print("No Puducherry pincode in the list")
Output
Processed ₹450
Processed ₹1200
₹25000 needs manager approval. Stopping.
No Puducherry pincode in the list

enumerate() and zip()

Two built-in functions make for loops even more useful:

  • enumerate(items, start=1) gives you a counter and the item together, so you never need range(len(items)).
  • zip(a, b) walks through two (or more) lists side by side, pairing their items. It stops at the end of the shortest list.

Nested Python loops

A loop inside a loop runs the inner loop completely for every round of the outer loop. This suits grids such as seats in rows or days and periods in a timetable. Keep an eye on size: 100 outer rounds × 100 inner rounds means 10,000 runs of the inner block. Use clear names such as row and seat so you always know which loop a variable belongs to.

toppers = ["Meera", "Farhan", "Deepa"]
for rank, name in enumerate(toppers, start=1):
    print(f"Rank {rank}: {name}")

trains = ["Vaigai Express", "Pandian Express"]
platforms = [4, 2]
for train, platform in zip(trains, platforms):
    print(f"{train} on platform {platform}")

for row in "AB":
    for seat in range(1, 4):
        print(f"{row}{seat}", end=" ")
    print()
Output
Rank 1: Meera
Rank 2: Farhan
Rank 3: Deepa
Vaigai Express on platform 4
Pandian Express on platform 2
A1 A2 A3 
B1 B2 B3

Notice the empty print() after the inner loop. It belongs to the outer loop, so it ends each row’s line once the inner loop has printed all the seats in that row.

Tip: Looping over a list while adding or removing items from that same list leads to skipped items. Loop over a copy (for x in items[:]) or build a new list instead. Python Lists and Tuples shows list comprehensions, a short way to build a new list from a loop.

Further reading

Key takeaways

  • for goes through every item of a sequence; while repeats while a condition is true.
  • range(start, stop, step) counts and stops before stop.
  • break leaves a loop, continue skips a round, and loop else runs when no break happened.
  • enumerate() adds a counter; zip() pairs items from several lists.
  • Every while loop must change something so its condition can become false.

Quick quiz

Check what you learned – pick an answer.

1. Which numbers does range(2, 10, 3) produce?

2. When does the else block of a for loop run?

3. What does continue do?

Practice exercise

Given cities = ["Chennai", "Madurai", "Vellore"] and temps = [34, 37, 39], print a numbered list like 1. Chennai: 34 °C, then print the name of the hottest city.

Show a hint

Combine enumerate() and zip(): for number, (city, temp) in enumerate(zip(cities, temps), start=1). Track the highest temperature in a variable.

Show the solution
cities = ["Chennai", "Madurai", "Vellore"]
temps = [34, 37, 39]

hottest_city = cities[0]
highest = temps[0]

for number, (city, temp) in enumerate(zip(cities, temps), start=1):
    print(f"{number}. {city}: {temp} °C")
    if temp > highest:
        highest = temp
        hottest_city = city

print(f"Hottest: {hottest_city} ({highest} °C)")

Progress is saved in this browser only.