📘 Lesson 09 · Intermediate

Python Loops

Learn for loops, while loops, break, continue, range(), enumerate() with examples and output.

The for Loop

A for loop iterates over a sequence — a list, string, range, dictionary, or any iterable. On each iteration the loop variable takes the next value from the sequence. This is Python's most common loop because Python programs deal heavily with collections of data.

for.py
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(f"I like {fruit}")

# Strings are iterable too
for char in "Hi!":
    print(char, end=" ")
▶ Output
I like apple
I like banana
I like cherry
H i !

range() — Looping a Set Number of Times

range(n) generates numbers from 0 to n-1. range(start, stop) gives start to stop-1. range(start, stop, step) adds a step size. The numbers are generated lazily (one at a time), so even range(1000000) barely uses any memory.

range.py
for i in range(5):        # 0 to 4
    print(i, end=" ")
print()

for i in range(1, 6):    # 1 to 5
    print(i, end=" ")
print()

for i in range(10, 0, -2): # countdown, step -2
    print(i, end=" ")
▶ Output
0 1 2 3 4 
1 2 3 4 5 
10 8 6 4 2

The while Loop

A while loop runs as long as its condition is True. Use it when you don't know in advance how many iterations are needed — for example, waiting for valid user input. Always make sure something inside the loop eventually makes the condition False, or you'll create an infinite loop.

while.py
count = 1
while count <= 5:
    print(f"Count: {count}")
    count += 1   # must update the variable or loop runs forever
print("Done!")
▶ Output
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Done!

break and continue

break exits the loop immediately — useful when you find what you're looking for. continue skips the rest of the current iteration and jumps to the next one — useful for filtering out unwanted items without adding another level of indentation.

break_continue.py
# break — stop when we reach 5
for i in range(10):
    if i == 5: break
    print(i, end=" ")
print("(stopped)")

# continue — skip even numbers
for i in range(10):
    if i % 2 == 0: continue
    print(i, end=" ")
▶ Output
0 1 2 3 4 (stopped)
1 3 5 7 9

enumerate() — Index and Value Together

When you need both the index and the value while looping, use enumerate() instead of manually tracking a counter. It returns pairs of (index, value). Use start=1 to begin numbering from 1 instead of 0.

enumerate.py
colours = ["red", "green", "blue"]
for i, colour in enumerate(colours, start=1):
    print(f"{i}. {colour}")
▶ Output
1. red
2. green
3. blue
Use for _ in range(n) when you just need to repeat something n times and don't care about the index. The underscore signals the variable is intentionally unused.

🧠 Quick Check

Which keyword skips the current iteration?

break
pass
skip
continue

Tags

for loopwhile loopbreakcontinuerangeenumeratenested loopspass