Lesson 57 min read

Loops

Do things over and over without writing the same code 100 times

For Loops — When You Know How Many Times

A for loop is like a tour guide walking through a group of items one by one. "Here's item 1, now item 2, now item 3..." until there's nothing left.

You can loop over anything iterable: lists, strings, ranges, dictionaries — even files. The variable after for takes on each value in turn.

For loops iterate over a known sequence; while loops repeat until a condition becomes False

For Loops & range()

# Loop over a list
pets = ["cat", "dog", "hamster", "parrot"]
for pet in pets:
print(f"I love my {pet}!")
print() # blank line
# Loop over a range of numbers
# range(5) gives: 0, 1, 2, 3, 4
for i in range(5):
print(f"Count: {i}")
print() # blank line
# range(start, stop, step)
for i in range(2, 11, 2):
print(i, end=" ") # Even numbers from 2 to 10
Output
I love my cat!
I love my dog!
I love my hamster!
I love my parrot!

Count: 0
Count: 1
Count: 2
Count: 3
Count: 4

2 4 6 8 10 

While Loops — When You Don't Know How Many Times

A while loop is like a guard who keeps checking a condition: "Is it still raining? Yes → stay inside. Is it still raining? Yes → stay inside. Is it still raining? No → go outside!"

Use while when you don't know in advance how many iterations you need. Just be careful — if the condition never becomes False, you've got an infinite loop!

While Loops

# Countdown timer
countdown = 5
while countdown > 0:
print(f"{countdown}...")
countdown -= 1
print("Liftoff! 🚀")
print()
# Guessing game logic
import random
secret = random.randint(1, 10)
guess = 0
attempts = 0
while guess != secret:
guess = random.randint(1, 10) # simulate guessing
attempts += 1
print(f"Found {secret} in {attempts} attempts!")
Output
5...
4...
3...
2...
1...
Liftoff! 🚀

Found 7 in 3 attempts!

Break, Continue & Enumerate

Sometimes you need more control inside a loop:

  • breakStop the loop entirely. Jump out and move on. Like finding what you're looking for and leaving the store.
  • continueSkip this iteration and jump to the next one. Like skipping a song in a playlist.
  • enumerate() — Gives you both the index and the value on each iteration. Super useful when you need to know the position.

Break, Continue & Enumerate

# break — stop when you find what you need
numbers = [4, 7, 2, 9, 1, 5]
for n in numbers:
if n == 9:
print(f"Found 9! Stopping.")
break
print(f"Checking {n}...")
print()
# continue — skip odd numbers
for i in range(10):
if i % 2 != 0:
continue # skip odd numbers
print(i, end=" ")
print("\n")
# enumerate — get index AND value
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index + 1}. {fruit}")
print()
# enumerate with custom start
for rank, fruit in enumerate(fruits, start=1):
print(f"#{rank}: {fruit}")
Output
Checking 4...
Checking 7...
Checking 2...
Found 9! Stopping.

0 2 4 6 8 

1. apple
2. banana
3. cherry

#1: apple
#2: banana
#3: cherry

Nested Loops

You can put a loop inside another loop. Keep in mind that nested loops multiply the work — a loop inside a loop over n items runs n×n times. Understanding Big-O notation helps you reason about this.

You can also put a loop inside another loop. The inner loop runs completely for each iteration of the outer loop. Think of it like a clock: the minute hand (inner loop) goes around 60 times for every 1 tick of the hour hand (outer loop).

Nested Loops

# Multiplication table (3×3)
for row in range(1, 4):
for col in range(1, 4):
result = row * col
print(f"{result:4d}", end="")
print() # new line after each row
print()
# Finding pairs that sum to 10
numbers = [2, 4, 6, 8, 3, 7]
for i in range(len(numbers)):
for j in range(i + 1, len(numbers)):
if numbers[i] + numbers[j] == 10:
print(f"{numbers[i]} + {numbers[j]} = 10")
Output
   1   2   3
   2   4   6
   3   6   9

2 + 8 = 10
4 + 6 = 10
3 + 7 = 10
Note: If you ever find yourself writing for i in range(len(my_list)) just to get the index, stop! Use enumerate(my_list) instead. It's more Pythonic, more readable, and less error-prone.

Quick check

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

Continue reading

Singly Linked ListData Structure
Nodes, traversal, insertion, deletion
Dynamic ArraysData Structure
Resizing strategy, amortized O(1) push
ConditionalsLists & Tuples