Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does return stop a python script [closed]

def foo:
    return 1
    print(varsum)

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

like image 809
Hans Avatar asked May 19 '14 19:05

Hans


People also ask

Does Python stop after return?

A return statement effectively ends a function; that is, when the Python interpreter executes a function's instructions and reaches the return , it will exit the function at that point.

Does function stop after return?

When a return statement is used in a function body, the execution of the function is stopped. If specified, a given value is returned to the function caller.

What does the return statement do in Python?

The Python return statement is a special statement that you can use inside a function or method to send the function's result back to the caller. A return statement consists of the return keyword followed by an optional return value. The return value of a Python function can be any Python object.


1 Answers

  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        
like image 195
kojiro Avatar answered Sep 18 '22 03:09

kojiro