Loops
Ways to repeat code — either a set number of times, or until a condition changes.
For Loop & Range
range() generates a sequence of numbers and is most often used to control a for loop. range(stop) counts from 0 up to — but not including — stop.
print(list(range(5)))
You can also give it a start and a step: range(start, stop, step).
print(list(range(2, 11, 2))) print(list(range(10, 0, -1)))
A for loop runs its block once for every item in a sequence — a range, a string, a list, or anything else iterable.
for i in range(3):
print("Count:", i)
for letter in "Hi!":
print(letter)
Loops can be nested inside each other — handy for anything grid-shaped, like printing a pattern:
for i in range(4):
for j in range(i + 1):
print("*", end=" ")
print()
While Loop
A while loop keeps running its block as long as a condition stays True. Unlike a for loop, it doesn't know in advance how many times it'll run, which makes it useful when you're waiting for something to change.
counter = 0
while counter < 3:
print("Current count:", counter)
counter += 1
Forgetting to update the variable in the condition creates an infinite loop, since the condition never becomes False:
# Careful - this never stops on its own:
while True:
print("Looping forever...")
Break & Continue
break exits the loop immediately, skipping any remaining iterations entirely.
for i in range(10):
if i == 5:
print("Stopping at 5.")
break
print(i)
continue skips just the rest of the current iteration and moves on to the next one — the loop keeps going.
for i in range(5):
if i == 2:
continue
print(i)