Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Keyword while

Test the condition before each iteration, including the first.

Version: Python 3.14; repository image, production runtime not attested

Syntax

while condition:
    ...
else:
    ...

Test the condition before each iteration, including the first.

A false initial test therefore executes zero loop bodies and can run else. continue returns to the test, while break exits without running else. while True: break terminates without changing the condition.

Examples

def countdown(n, stop):
    seen = []
    while n > 0:
        if n == stop:
            break
        seen.append(n)
        n -= 1
    else:
        seen.append("done")
    return seen
print(countdown(0, 9), countdown(3, 2))
while True:
    break
print("break exits")

Result

['done'] [3]
break exits

A false initial test therefore executes zero loop bodies and can run else. continue returns to the test, while break exits without running else. `while True: break` terminates without changing the condition.

Sources