Concept of Return Statement
The return statement is used inside a function to send a value back to the part of the program that called it, allowing the result to be stored, reused, or passed into other functions.
Using return in a Function
def add_numbers(a, b):
return a + b
result = add_numbers(5, 10)
print(result)
return vs print()
print() only displays a value on the screen, while return actually hands the value back so it can be used elsewhere in your code.
def square(n):
return n * n
total = square(4) + square(3)
print(total)
Returning Multiple Values
def get_min_max(numbers):
return min(numbers), max(numbers)
low, high = get_min_max([4, 9, 1, 7])
print(low, high)
A function without a
return statement still runs correctly, but it sends back the value None, which can cause confusing bugs if you try to use its result elsewhere.Coming Up
The final topic in this section explains a special variable, __name__, and the __main__ check used to control what runs when a Python file is executed directly.