Python Glossary Русский

all Python 3Loopsconstruct

while

while loop

A loop with a pre-condition. It runs its body while the condition is true. The condition has to be changed explicitly, otherwise the loop never ends.

Syntax

while условие:
    блок

Reach for while rather than for when you don't know the iteration count ahead of time — reading until a sentinel, looping until convergence, waiting for an event; use for to walk a ready-made sequence. Little-known: while has an else branch that runs only when the loop ends on its condition, never after a break.

Examples

i = 0
while i < 5:
    print(i, end=" "); i += 1  # → 0 1 2 3 4
total = 0; n = 10
while n > 0:
    total += n; n -= 1
print(total)  # → 55 (сумма 1..10)
lst = [3, 7, 1, 9, 2]
i = 0
while i < len(lst) and lst[i] != 9:
    i += 1
print(i)  # → 3 (индекс элемента 9)
count = 0
while True:
    count += 1
    if count == 5:
        break
print(count)  # → 5

See also

Open in the full glossarydocs.python.orgReport an inaccuracy