All courses › Programming with Python › while loop

while loop

A while loop repeats code as long as a condition is true. The condition is checked before each round, so it can run zero times. If you forget to change the tested variable, the loop runs forever.

while P:\text{while } P:run the block as long as the statement PP is true

Symbols

PPa condition (true/false)

Example

n = 0

while n < 10: n += 3

After the loop, n = 12 (0, 3, 6, 9, 12 — 4 rounds).

Always check that something in the condition is actually changed inside the loop.
Practise loops and conditions for free →

← for loop and range · Conditionals: if/elif/else →

Part of Programming with Python: Loops and conditions.