Python’s return
keyword commands the execution flow to exit a function immediately and return a value to the caller of the function. You can specify an optional return value—or even a return expression—after the return
keyword. If you don’t provide a return value, Python will return the default value None
to the caller.
Python Return Keyword Video
Return Keyword Followed by Return Value
Here’s an example of the return keyword in combination with a return value:
def f(): return 4 print(f()) # OUTPUT: 4
Within function f()
, Python returns the result 4 to the caller. The print()
function then prints the output to the shell.
Return Keyword Followed by Return Expression
Here’s an example of the return keyword in combination with a return expression:
def f(): return 2+2 print(f()) # OUTPUT: 4
Within function f()
, Python evaluates the expression 2+2=4
and returns the result 4 to the caller. The print()
function then prints the output to the shell.
Return Keyword Followed by No Value
Here’s an example of the return keyword without defining a return value:
def f(): return print(f()) # OUTPUT: None
Within function f()
, Python returns the default value None
to the caller. The print()
function then prints the output to the shell.
Interactive Code Shell
Run the following code in your browser:
Exercise: Change the three return values to 42, 42, and ‘Alice’ in the interactive code shell!
π Recommended Tutorial: Whatβs the Difference Between return and break in Python?