I understand how this construct works:
for i in range(10):
print(i)
if i == 9:
print(\"Too big - I\'m
The else
keyword can be confusing here, and as many people have pointed out, something like nobreak
, notbreak
is more appropriate.
In order to understand for ... else ...
logically, compare it with try...except...else
, not if...else...
, most of python programmers are familiar with the following code:
try:
do_something()
except:
print("Error happened.") # The try block threw an exception
else:
print("Everything is find.") # The try block does things just find.
Similarly, think of break
as a special kind of Exception
:
for x in iterable:
do_something(x)
except break:
pass # Implied by Python's loop semantics
else:
print('no break encountered') # No break statement was encountered
The difference is python
implies except break
and you can not write it out, so it becomes:
for x in iterable:
do_something(x)
else:
print('no break encountered') # No break statement was encountered
Yes, I know this comparison can be difficult and tiresome, but it does clarify the confusion.