Loops
for and while loops, plus break, continue, and the loop else clause.
for loops
A for loop iterates over anything iterable — a list, string, range, dict, or file. range(n) generates 0, 1, ..., n-1; range(a, b) generates a, ..., b-1.
for i in range(5):
print(i) # 0 1 2 3 4
videos = ["Intro", "Variables", "Loops"]
for video in videos:
print("Now playing:", video)
for index, video in enumerate(videos):
print(index, "->", video) # enumerate() gives you both index and value
while loops
Repeats while a condition stays true — use it when you don't know the number of iterations upfront (waiting for user input, polling, game loops).
subscribers = 0
target = 5
while subscribers < target:
subscribers += 1
print(f"Gained subscriber #{subscribers}")
print("Reached the target!")
A while True: loop repeats forever until something inside explicitly breaks out of it — a very common pattern for "keep asking until valid input."
break, continue, and the loop's else
break exits the loop entirely; continue skips the rest of the current iteration and moves to the next one. A loop's else block runs only if the loop finished without hitting break — a lesser-known but genuinely useful feature for "search and report if not found" patterns.
videos = ["Intro", "Variables", "Loops", "Functions"]
target = "Functions"
for video in videos:
if video == target:
print("Found it!")
break
else:
print("Not in the playlist")
Classic drill: FizzBuzz
for i in range(1, 16):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)- •for iterates over any iterable; while repeats based on a condition — use while when the number of iterations isn't known upfront.
- •range(a, b) produces a, a+1, ..., b-1 — the stop value is never included.
- •enumerate(iterable) gives you (index, value) pairs without manually tracking a counter.
- •break exits the loop entirely; continue skips only the current iteration.
- •A for/while loop's else block runs only if the loop completed without break — handy for 'search, and report if nothing was found'.
FizzBuzz
for/else — search a playlist
Revision Flashcards
Tap a card to flip it and see the answer.