def foo:
return 1
print(varsum)
would the print command still be executed, or would the program be terminated at 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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With