Loops in Python

Module 3 · Loops in Python · Lesson 2 of 6

Infinite loops

A loop only ends when its condition becomes False. So what if the condition is always True? Then it never ends — an infinite loop. The plainest one is while True:, since True is, well, always true.

A loop that never endsrunning… forever
while True:
i += 1
# nothing ever stops this…
i
0

while True:won't stop on its own. You escape it with a breakinside the loop — or, if it's really stuck, by pressing Ctrl-C.

Most infinite loops are accidents: you forget the line that moves the condition along, so it never changes. A countdown where you forget n -= 1 will print the same number forever. If you ever run a program that just hangs, a runaway loop is the usual suspect — press Ctrl-C in the terminal to stop it.

But infinite loops are also written on purpose. A common, very useful pattern is while True: with a break inside — “keep going until something tells me to stop.” The loop runs until a condition inside it triggers the break:

Run it yourselfruns in your browser · Python
main.py

⚠ A word of warning: only run a while True loop that you know has a break — a truly endless one would freeze the page. We'll look at break properly in a couple of lessons.