does return stop a python script

Question:

def foo:
    return 1
    print(varsum)

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

Asked By: Hans

||

Answers:

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 foo().

Answered By: NPE

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

Answered By: F.Baheux
  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        
Answered By: kojiro

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.

Answered By: Tyler McAtee
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.