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

后端 未结 6 602
执笔经年
执笔经年 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:50

    exec is a built in function ,

    Python insists that break should happen inside the loop,not inside a function

    What is happening in your code is you are putting break inside a function which is exec you can't break out of a loop by executing a break within a function that's called inside the loop.

    For Ex

    >>> def func():
            break
    SyntaxError: 'break' outside loop
    >>> 
    

提交回复
热议问题