PythonSyntax and keywords
return
Ends a function and returns a value to the place it was called from.
Example
#Python
def min_max(values):
return min(values), max(values)
low, high = min_max([72, 95, 64, 88])
print(low, high)
def greet(name):
print(f"Hi, {name}!")
result = greet("Emma")
print(result)Resultsaved result, you can check it
64 95
Hi, Emma!
None
Definition and usage
#The return statement ends a function’s execution and passes the result back to where the function was called. Code after return in the same block no longer runs.
A function with no return (or with a bare return) returns None. This is a common source of bugs: the result of a function that only prints something is not usable in further calculations.
You can return several values at once, separated by commas. Python packs them into a tuple, which you can conveniently unpack at the call site: low, high = min_max(values).
Syntax
#Syntax
def name():
return valueGood practices
#- An early
returnfor special cases (empty data, invalid arguments) simplifies the rest of the function. - Remember that a function which prints its result with
print()does not return it. You needreturnto use the value further.
Related entries
#- defDefines a function: a named block of code with parameters that you can call multiple times.
- yieldCreates a generator: a function that returns successive values on demand.
- lambdaA short anonymous function written as a single expression.
- Unpacking sequencesAssigning the items of a tuple or list to several variables at once.
Spotted a mistake or missing an example? Write to us.