In this answer https://stackoverflow.com/a/27680814/3456281, the following construct is presented
a=[1,2]
while True:
if IndexError:
print ("Stopped.")
break
print(a[2])
which actually prints "Stopped." and breaks (tested with Python 3.4.1).
Why?! Why is if IndexError
even legal? Why does a[2]
not raise an IndexError
with no try ... except
around?
All objects have a boolean value. If not otherwise defined, that boolean value is True.
So this code is simply the equivalent of doing if True
; so execution reaches the break
statement immediately and the print
is never reached.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments