A more interesting example of the use of a while
loop is given by this implementation of Euclid's algorithm for finding the greatest common divisor of two numbers, $\mathrm{gcd}(a,b)$:
>>> a, b = 1071, 462
>>> while b:
... a, b = b, a % b
...
>>> print(a)
21
The loop continues until b
divides a
exactly; on each iteration, b
is set to the remainder of a//b
and then a
is set to the old value of b
. Recall that the integer 0 evaluates as boolean False
so while b:
is equivalent to while b != 0:
.