I understand how this construct works:
for i in range(10):
print(i)
if i == 9:
print(\"Too big - I\'m
Great answers are:
My note here comes from what Donald Knuth once said (sorry can't find reference) that there is a construct where while-else is indistinguishable from if-else, namely (in Python):
x = 2
while x > 3:
print("foo")
break
else:
print("boo")
has the same flow (excluding low level differences) as:
x = 2
if x > 3:
print("foo")
else:
print("boo")
The point is that if-else can be considered as syntactic sugar for while-else which has implicit break at the end of its if block. The opposite implication, that while loop is extension to if, is more common (it's just repeated/looped conditional check), because if is often taught before while. However that isn't true because that would mean else block in while-else would be executed each time when condition is false.
To ease your understanding think of it that way:
Without
break,return, etc., loop ends only when condition is no longer true and in such caseelseblock will also execute once. In case of Pythonforyou must consider C-styleforloops (with conditions) or translate them towhile.
Another note:
Premature
break,return, etc. inside loop makes impossible for condition to become false because execution jumped out of the loop while condition was true and it would never come back to check it again.