Skip to content
Tactiverge

Python reference

while loops

Also called: while · loop until · break · infinite loop

Definition

A while loop repeats its body as long as its condition stays true, checking the condition before each pass.

Picture it

Use while when you do not know in advance how many passes you need: 'keep halving until the step is small enough'. Every while loop needs something inside it that eventually makes the condition false, or a break, or it never ends.

Worked example

How many passes does this loop make, and what is x at the end? x = 100 n = 0 while x > 1: x = x / 2 n += 1

  1. 100 → 50 → 25 → 12.5 → 6.25 → 3.125 → 1.5625 → 0.78125
  2. That is 7 halvings

Answer7 passes; x ends at 0.78125.

✓ The 2 numbers in this answer are recomputed from scratch by an automated test.

In Python

while not at_target():
    step_motor()
    if timeout():
        break  # always plan an exit

Common misconceptions

  • Misconception: The condition is only checked at the top of each pass, not continuously.
  • Misconception: A loop waiting for a sensor with no timeout can hang a robot forever.