Loops let you repeat code. Python has two loop types: for (iterate over a sequence) and while (repeat while a condition is true).
for
while
for iterates over any iterable โ strings, lists, ranges, dicts, etc.:
range() generates a sequence of integers. It's the go-to for index-based or count-based loops:
range()
while repeats as long as its condition is truthy:
break immediately exits the nearest enclosing loop:
break
continue skips the rest of the current iteration and moves to the next:
continue
Python's loops have an optional else clause that runs only if the loop completed without hitting break:
else
The else runs when:
The else does NOT run when break was used.
pass is a no-op โ it does nothing. Use it as a placeholder:
pass
What does range(2, 10, 3) produce?
When does the else clause of a for loop execute?
What does the continue statement do in a loop?