As the question asks, why doesn\'t the below code work:
while True:
exec(\"break\")
I am executing the above in pycharm via python 3.
exec() is a function. Assuming for simplicity that a function call constitutes a statement of its own (just like in your example), it may end in one of the following ways:
the function returns normally - in this case the next statement according to the control flow is executed;
an exception is raised/thrown from the function - in this case the matching except clause on the call stack (if any) is executed
the entire program is terminated due to an explicit call to exit() or equivalent - there is nothing to execute.
Calling a break (as well as return or yield) from inside exec() would modify the program execution flow in a way that is incompatible with the described aspect of the function call semantics.
Note that the documentation on exec() contains a special note on the use of return and yield inside exec():
Be aware that the
returnandyieldstatements may not be used outside of function definitions even within the context of code passed to theexec()function.
A similar restriction applies to the break statement (with the difference that it may not be used outside loops), and I wonder why it was not included in the documentation.