A loop's else block runs only when the loop finishes without break.
Read else on a loop as "no break".
# else runs if no break
for i in range(5):
if i == 10:
break
else:
print("Loop completed")
# ans: Loop completed
# else runs after while completes
count = 0
while count < 3:
print(count)
count += 1
else:
print("Done")
# ans: 0, 1, 2, Done
# break prevents else from running
for i in range(5):
if i == 3:
break
else:
print("This won't print")
# ans: nothing: break skips the else
# else runs even if the loop is empty
for i in range(0):
pass
else:
print("Runs")
# ans: Runs
Does the else run? Predict, then press → to trace.
# does else run?
for i in range(5):
pass
else:
print("Done")
# ans: Done (no break)
# what about this?
for i in range(5):
if i == 2:
break
else:
print("Done")
# ans: nothing (break prevents else)
# while-else?
x = 0
while x < 0:
x += 1
else:
print("Else runs")
# ans: Else runs (the body never executes, but there is no break)
# tricky: does else run?
for i in range(0):
pass
else:
print("Yes")
# ans: Yes (empty range, no break)
# what prints?
for i in range(3):
if i == 5:
break
else:
print("Complete")
# ans: Complete (the condition is never True, so no break)
# while-else with break?
x = 0
while x < 3:
if x == 2:
break
x += 1
else:
print("Done")
# ans: nothing (break prevents else)
# nested loop else?
for i in range(2):
for j in range(2):
if j == 1:
break
else:
print("Outer else")
# ans: Outer else (the inner break doesn't affect the outer loop)
# what happens?
for i in range(3):
if i == 3:
break
else:
print("Runs")
# ans: Runs (range(3) stops at 2, so i == 3 is never True)
# while-else execution?
x = 5
while x < 3:
x += 1
else:
print("Else")
# ans: Else (the condition is False from the start)
# tricky break?
for i in range(3):
if False:
break
else:
print("Complete")
# ans: Complete (the break never executes)
The else block runs when the loop ends normally.
Leaving with break jumps past the else.
A loop that never runs its body still ends normally, so else runs.
A break in an inner loop doesn't stop the outer loop's else.