Search notes:

Python: while statement

The while statement iterates over a block of code until a given condition becomes false.

Simple iteration

The following simple example prints the numbers 0 through 4 (the loop is exited when cond < 5 becomes false, thus 5 is not printed).
cnt = 0

while cnt < 5:
      print('cnt = {0}'.format(cnt))
      cnt += 1
Github repository about-Python, path: /statements/while/simple.py
The output of this example is:
cnt  = 0
cnt  = 1
cnt  = 2
cnt  = 3
cnt  = 4

while … next

The while statement can optionally be suffexed with a else handler which is executed when the loop terminates:
cnt = 0

while cnt < 5:
      print('cnt = {0}'.format(cnt))
      cnt += 1
else:
      print('finished')
Github repository about-Python, path: /statements/while/else.py
The output of this example is:
cnt  = 0
cnt  = 1
cnt  = 2
cnt  = 3
cnt  = 4
finished

break, continue

Within a loop (such a while loop), the break statement unconditionally and immediately jumps out of the loop.
The continue statement jumps to the begin of the loop again.
x = 0

while True:

      x += 1

      if x == 2:
         print('x = 2 -> continue')
         continue

      if x == 5:
         print('x = 5 -> break')
         break

      print('end of loop, x = {0}'.format(x))
Github repository about-Python, path: /statements/while/break-continue.py
The output of this example is:
end of loop, x = 1
x = 2 -> continue
end of loop, x = 3
end of loop, x = 4
x = 5 -> break

Assignment in while statement

PEP-572 defines the assignment expression (aka walrus operator) with which it is (finally) possible to have an assignment in the while condition. The assignment expression requires at least Python version 3.8.
import random

random.seed('tq84')

while (rnd := random.random()) < 0.9:
      print('rnd = {0}'.format(rnd))
#
#     rnd = 0.15919424924070613
#     rnd = 0.4948802376988537
#     rnd = 0.6212905728914367
#     rnd = 0.5917838981303569
Github repository about-Python, path: /statements/while/assignment-expression.py

See also

The else clause
Each object can be evaluated in a boolean context, such as an if or while statement. The rules if an object is considered to be True or False are described here.

Index