The return
statement in Python is used to send a value back from a function. It terminates the function and allows you to store the returned value for further use.
Using the Return Statement
A function can return any data type, including numbers, strings, lists, tuples, dictionaries, or even other functions.
Example: Returning a Single Value
def add(a, b): return a + b result = add(5, 3) print(result) # Output: 8
Example: Returning Multiple Values
A function can return multiple values as a tuple.
def operations(a, b): return a + b, a - b, a * b, a / b sum_result, diff, prod, div = operations(10, 2) print(sum_result, diff, prod, div)
Example: Returning a List
You can return lists or other complex data structures from a function.
def squares(numbers): return [n ** 2 for n in numbers] print(squares([1, 2, 3, 4]))
Key Takeaways
- The
return
statement sends data back from a function. - A function can return a single value, multiple values, or complex data types.
- Returning multiple values automatically packs them into a tuple.