๐Ÿ”„for, while, range(), break, continueLESSON

for, while, range(), break, continue

Loops let you repeat code. Python has two loop types: for (iterate over a sequence) and while (repeat while a condition is true).

The for Loop

for iterates over any iterable โ€” strings, lists, ranges, dicts, etc.:

range()

range() generates a sequence of integers. It's the go-to for index-based or count-based loops:

while Loop

while repeats as long as its condition is truthy:

break โ€” Exit Early

break immediately exits the nearest enclosing loop:

continue โ€” Skip to Next Iteration

continue skips the rest of the current iteration and moves to the next:

else Clause on Loops

Python's loops have an optional else clause that runs only if the loop completed without hitting break:

The else runs when:

  • for loop: the iterable was exhausted normally
  • while loop: the condition became False

The else does NOT run when break was used.

pass Statement

pass is a no-op โ€” it does nothing. Use it as a placeholder:

Nested Loops

Common Loop Patterns

Knowledge Check

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?