Python Glossary Русский

all Python 3Loopsconstruct

else in loops

control

A loop's else block runs only if the loop finished WITHOUT a break. Handy for the 'search with a flag' pattern.

Syntax

for/while ...:
    ...
else:
    блок_если_не_break

Read it not as "else" but as "if no break": the else block runs when the loop ends normally (including when it never started because the iterable was empty) and is skipped only on break. A common mistake is tying else to the if inside the loop — it actually belongs to the for/while itself.

Examples

for i in range(2, 10):
    if 15 % i == 0:
        print(f"15 делится на {i}")  # → 15 делится на 3
        break
else:
    print("15 простое")  # не выполнится
target = 99
for x in [1, 2, 3]:
    if x == target:
        break
else:
    print("не найдено")  # → не найдено
i = 0
while i < 3:
    i += 1
else:
    print("while завершён штатно")  # → while завершён штатно

See also

Open in the full glossarydocs.python.orgReport an inaccuracy