Skip to content
elephantoo

Loops: for, while & friends

Lesson 7 of 38 13 min read

for and while loops, range, enumerate, zip, break/continue, loop else and loop-replacing built-ins.


Computers are great at doing the same thing thousands of times without getting bored. Loops let you process every item in a list, every line in a file, or keep asking until the user gets it right. Python has two loops — for and while — plus some elegant helper functions that make loops read like plain English.

The for loop#

Python's for walks through the items of any iterable — a list, a string, a range, a dictionary, a file — one at a time:

Python
languages = ["Python", "Java", "Go"]
for lang in languages:
    print(f"I'm learning {lang}")

for ch in "hey":
    print(ch.upper())
Output
I'm learning Python
I'm learning Java
I'm learning Go
H
E
Y

The loop variable (lang, ch) takes each value in turn. There's no index bookkeeping and no risk of going off the end.

Counting with range()#

When you need numbers, use range(stop), range(start, stop) or range(start, stop, step). The stop value is never included:

Python
print(list(range(5)))
print(list(range(1, 6)))
print(list(range(0, 20, 5)))
print(list(range(10, 0, -3)))   # count down
Output
[0, 1, 2, 3, 4]
[1, 2, 3, 4, 5]
[0, 5, 10, 15]
[10, 7, 4, 1]

range doesn't build a list in memory — it produces numbers on demand, so range(1_000_000_000) costs almost nothing. (We wrapped it in list() above just to display it.)

Python
total = 0
for n in range(1, 101):
    total += n
print(f"1 + 2 + ... + 100 = {total}")
Output
1 + 2 + ... + 100 = 5050

enumerate(): index and value together#

Beginners from other languages often write for i in range(len(items)):. Python has a better way:

Python
tasks = ["write code", "test it", "ship it"]
for number, task in enumerate(tasks, start=1):
    print(f"{number}. {task}")
Output
1. write code
2. test it
3. ship it

zip(): loop over several sequences in parallel#

Python
names = ["Ada", "Grace", "Linus"]
scores = [92, 88, 79]

for name, score in zip(names, scores):
    print(f"{name:<6} {score}")
Output
Ada    92
Grace  88
Linus  79

zip stops at the shortest input. Pass strict=True (Python 3.10+) to raise an error if the lengths differ — a great way to catch bugs.

Looping over dictionaries#

Iterating a dict gives you its keys; use .items() to get key–value pairs:

Python
prices = {"apple": 40, "banana": 10, "mango": 60}

for fruit in prices:
    print(fruit, end=" ")
print()

for fruit, price in prices.items():
    print(f"{fruit}: ₹{price}")
Output
apple banana mango 
apple: ₹40
banana: ₹10
mango: ₹60

The while loop#

while repeats as long as a condition is true. Use it when you don't know in advance how many iterations you need:

Python
balance = 1000
year = 0
while balance < 2000:
    balance *= 1.07      # 7% growth per year
    year += 1
print(f"Doubled after {year} years: ₹{balance:.2f}")
Output
Doubled after 11 years: ₹2104.85

Make sure something inside the loop eventually makes the condition false, or you'll write an infinite loop (stop a runaway program with Ctrl+C).

A deliberate while True: with a break is a common, readable pattern for "loop until something happens" — for example, a menu or input validation:

Python
commands = iter(["help", "list", "quit", "never reached"])  # simulated user input

while True:
    cmd = next(commands)
    if cmd == "quit":
        print("Goodbye!")
        break
    print(f"Running {cmd}...")
Output
Running help...
Running list...
Goodbye!

break, continue and else#

  • break leaves the loop immediately.
  • continue skips the rest of this iteration and moves on to the next.
Python
for n in range(1, 11):
    if n % 2 == 0:
        continue          # skip even numbers
    if n > 7:
        break             # stop completely after 7
    print(n, end=" ")
print()
Output
1 3 5 7 

Loops can have an else clause that runs only if the loop wasn't stopped by break. It's perfect for searches:

Python
def find_first_negative(numbers):
    for i, n in enumerate(numbers):
        if n < 0:
            print(f"first negative is {n} at index {i}")
            break
    else:
        print("no negatives")


find_first_negative([4, 7, -2, 9])
find_first_negative([1, 2, 3])
Output
first negative is -2 at index 2
no negatives

Nested loops#

A loop inside a loop runs the inner loop completely for every step of the outer one:

Python
for row in range(1, 4):
    for col in range(1, 4):
        print(f"{row * col:3}", end="")
    print()
Output
  1  2  3
  2  4  6
  3  6  9

break only exits the innermost loop. To stop everything, move the loops into a function and return.

Handy built-ins that replace loops#

Many loops just compute a summary. Python has built-ins for the common ones:

Python
nums = [4, 8, 15, 16, 23, 42]

print(sum(nums), min(nums), max(nums))
print(any(n > 40 for n in nums))      # at least one?
print(all(n > 0 for n in nums))       # every one?
print(sorted(nums, reverse=True))
for n in reversed(nums[:3]):
    print(n, end=" ")
print()
Output
108 4 42
True
True
[42, 23, 16, 15, 8, 4]
15 8 4 

Worked example: FizzBuzz and a number-guessing game#

The classic interview warm-up:

Python
for n in range(1, 16):
    if n % 15 == 0:
        print("FizzBuzz")
    elif n % 3 == 0:
        print("Fizz")
    elif n % 5 == 0:
        print("Buzz")
    else:
        print(n)
Output
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

And a small game that combines while, input and conditionals:

guess.py
import random

secret = random.randint(1, 20)
attempts = 0

while True:
    guess = int(input("Guess (1-20): "))
    attempts += 1
    if guess < secret:
        print("Higher!")
    elif guess > secret:
        print("Lower!")
    else:
        print(f"Correct! You needed {attempts} attempts.")
        break

Common mistakes#

  • Modifying a list while looping over it. Removing items mid-loop skips elements. Loop over a copy (for x in items[:]) or build a new list.
  • Off-by-one with range. range(1, 10) stops at 9. Use range(1, 11) for 1–10.
  • for i in range(len(items)) when you only need the items — loop directly, or use enumerate.
  • Forgetting to update the while condition, creating an infinite loop.

What's next#

You can now repeat work over collections. Time to study the most important collection of all: the list.

Check your understanding

Quick quiz

0/3 answered
  1. 1.What does range(2, 10, 3) produce?

  2. 2.What does continue do inside a loop?

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

Finished reading?

Mark this lesson complete to track your progress.