does return stop a python script [closed]

百般思念 提交于 2019-12-07 04:07:15

问题


def foo:
    return 1
    print(varsum)

would the print command still be executed, or would the program be terminated at return()


回答1:


  1. The print statement would not be executed.
  2. The program would not be terminated.

The function would return, and execution would continue at the next frame up the stack. In C the entry point of the program is a function called main. If you return from that function, the program itself terminates. In Python, however, main is called explicitly within the program code, so the return statement itself does not exit the program.

The print statement in your example is what we call dead code. Dead code is code that cannot ever be executed. The print statement in if False: print 'hi' is another example of dead code. Many programming languages provide dead code elimination, or DCE, that strips out such statements at compile time. Python apparently has DCE for its AST compiler, but it is not guaranteed for all code objects. The following two functions would compile to identical bytecode if DCE were applied:

def f():
    return 1
    print 'hi'
def g():
    return 1

But according to the CPython disassembler, DCE is not applied:

>>> dis.dis(f)
  2           0 LOAD_CONST               1 (1)
              3 RETURN_VALUE        

  3           4 LOAD_CONST               2 ('hi')
              7 PRINT_ITEM          
              8 PRINT_NEWLINE       
>>> dis.dis(g)
  2           0 LOAD_CONST               1 (1)
              3 RETURN_VALUE        



回答2:


In fact, the return statement will end your function. So your print won't be executed.

Here a similar question about it, and lot of interesting answers




回答3:


Neither. What would happen is that the function would return. The print will not be executed. The script may or may not terminate depending on the code that calls asdf().




回答4:


The return statement will end the current scope in which it is written. So if you return from a function, it will return to the place from which that function was called. If you return in the main python script, it will yield control to the OS that was running it.



来源:https://stackoverflow.com/questions/23745654/does-return-stop-a-python-script

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!