Python Glossary Русский

all Python 3astterm

ast.While

control flow

Node for a while loop: test is the condition, body is the loop body, orelse is the else branch run when the loop ends without break.

Syntax

ast.While(test, body, orelse)

The orelse field is almost always empty, so traversals and code generators forget it, yet it may hold the "not found" logic. Unlike For, While has no target or type_comment. An infinite while True: stores Constant(True) in test, not a Name as in old Python 2 code.

Examples

import ast
w = ast.parse('while x:\n    x -= 1\nelse:\n    done()').body[0]
print(type(w).__name__, w.test.id, len(w.body), len(w.orelse))  # → While x 1 1
t = ast.parse('while True: pass').body[0].test
print(type(t).__name__, t.value)  # → Constant True

See also

Open in the full glossarydocs.python.orgReport an inaccuracy