Why doesn't exec(“break”) work inside a while loop

后端 未结 6 610
执笔经年
执笔经年 2021-01-18 13:26

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.

6条回答
  •  旧巷少年郎
    2021-01-18 13:58

    The exec statement runs a bit of code independently from the rest of your code.

    Hence, the line:

    exec("break")
    

    is tantamount to calling break out of nowhere, in a script where nothing else happens, and where no loop exists.

    The right way to call the break statement is:

    while True:
        break
    

    EDIT

    The comment from Leaf made me think about it.

    Actually, the exec statement does not run the code out of nowhere.

    >>> i = 12
    >>> exec("print(i)")
    12
    

    A better answer, as far as I understand, is that exec runs a piece of code in the same environment as the original code, but independently from it.

    This basically means that all the variables that exist at the moment exec is called can be used in the code called by exec. But the context is all new, so return, break, continue and other statements that need a context, will not work, unless the right context is created.

    By the way, I kept the word "statement" when talking about exec, but it has become a function in Python3, the same way print did.

提交回复
热议问题