The exec statement executes a bit of code regardless of the rest of your code.
Hence the line:
exec("break")
tantamount to calling break from nowhere, in a script where nothing happens and where there is no loop.
The correct way to call the break statement:
while True: break
EDIT
A comment from Leaf made me think.
Actually, the exec statement does not run code from nowhere.
>>> i = 12 >>> exec("print(i)") 12
The best answer, as I understand it, is that exec executes a piece of code in the same environment as the source code, but independently of it.
This basically means that all variables that exist at the time exec are called can be used in code called exec . But the context is all new, so return , break , continue and other operators that need context will not work if the correct context is not created.
By the way, I kept the word "statement" when I talked about exec , but it became a function in Python3, just like print .
source share