Course topics

By WebNest Studio

Python Tutorial

Loops in Python: for and while

Loops repeat work: process every order, retry until a download succeeds, read every line of a file. Python has two loop statements. The for loop iterates over the items of any iterable — lists, strings, ranges, dictionaries, files. The while loop repeats as long as a condition stays true.

This lesson covers both loops, range(), enumerate() and zip(), looping over dictionaries, nested loops, the loop else clause, and how to choose between for and while.

The for Loop

for item in iterable: runs the block once per item. It works with any iterable, not just numbers. range(stop), range(start, stop) and range(start, stop, step) produce integer sequences (stop is exclusive). enumerate() gives index and item together; zip() walks several sequences in parallel; reversed() and sorted() change the order.

The while Loop

while condition: repeats while the condition is truthy. Use it when you do not know in advance how many iterations are needed: reading until the user types "quit", retrying a network call, running a game loop. Make sure something inside the loop eventually makes the condition false, or you get an infinite loop.

Loop else

A loop can have an else block that runs only if the loop finished without a break. It is handy for search loops: "look for the item; else report it was not found".

for vs while

Use for when iterating over a collection or a known range — it cannot accidentally run forever and needs no manual counter. Use while for condition-driven repetition. Most Python loops are for loops; if you write while i < len(items) with a manual index, a for loop is almost always cleaner.

Examples

for loops with range, enumerate and zip

Python
for i in range(1, 6):
    print(i, end=" ")
print()

for n in range(10, 0, -3):
    print(n, end=" ")
print()

fruits = ["mango", "apple", "banana"]
for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)

names = ["Asha", "Ravi", "Meera"]
scores = [88, 72, 95]
for name, score in zip(names, scores):
    print(f"{name}: {score}")
Output
1 2 3 4 5
10 7 4 1
1 mango
2 apple
3 banana
Asha: 88
Ravi: 72
Meera: 95

Looping over strings and dictionaries, and nested loops

Python
for ch in "Hi!":
    print(ch)

prices = {"pen": 10, "book": 250, "bag": 899}
for item, price in prices.items():
    print(f"{item:<5} Rs.{price}")

for row in range(1, 4):
    print(" ".join(str(row * col) for col in range(1, 4)))
Output
H
i
!
pen   Rs.10
book  Rs.250
bag   Rs.899
1 2 3
2 4 6
3 6 9

while loops and the loop else clause

Python
balance = 1000
years = 0
while balance < 2000:
    balance *= 1.08
    years += 1
print(f"Doubled in {years} years: {balance:.2f}")

numbers = [4, 8, 15, 16, 23, 42]
target = 15
for position, n in enumerate(numbers):
    if n == target:
        print("Found at index", position)
        break
else:
    print("Not found")

for n in numbers:
    if n == 99:
        break
else:
    print("99 not found (loop finished without break)")
Output
Doubled in 10 years: 2158.92
Found at index 2
99 not found (loop finished without break)

Common Mistakes

  • Forgetting that range(1, 10) stops at 9.
  • Modifying a list while iterating over it — iterate over a copy or build a new list.
  • Writing while loops whose condition never becomes false.
  • Using range(len(items)) and items[i] when enumerate() is clearer.
  • Misunderstanding loop else: it runs when no break happened, not when the loop body never ran.

Key Points to Remember

  • for iterates over any iterable; range() generates number sequences (stop exclusive).
  • enumerate() gives indices, zip() pairs sequences, .items() walks dicts.
  • while repeats while a condition is true — ensure it eventually ends.
  • A loop's else runs only if the loop was not ended by break.
  • Prefer for loops for collections; while for condition-driven repetition.

Practice the examples

Change an input, predict the result, then compare it with the output. Explain why the result changes.