The return statement is used inside a Python function to send a result back to the place where the function was called. Unlike print(), which displays a value on the screen, return allows the returned value to be stored, reused, or used in another expression.
What is return?
The return statement ends the execution of a function and sends a value back to the caller.
def add(a, b):
return a + b
result = add(10, 20)
print(result)Output:
30Here, return a + b sends the result 30 back to the function call. The returned value is then stored in the result variable.
A function can also use return without a value:
def check():
return
print(check())Output:
NoneWhen no value is returned, Python returns None.
Returning a Value
A function can return almost any Python value, such as a number, string, list, dictionary, or Boolean value.
For example:
def square(number):
return number * number
result = square(6)
print(result)Output:
36The returned value can also be used directly in another operation:
def add(a, b):
return a + b
total = add(10, 5) * 2
print(total)Output:
30The return statement also stops the function immediately.
def check_number(number):
if number > 0:
return "Positive"
return "Not positive"
print(check_number(5))Output:
PositiveOnce Python executes return, the remaining statements in that function are not executed.
Returning Multiple Values
Python allows a function to return multiple values. These values are automatically packed into a tuple.
def calculate(a, b):
return a + b, a - b
result = calculate(10, 5)
print(result)Output:
(15, 5)You can also assign the returned values to separate variables:
def calculate(a, b):
return a + b, a - b
addition, subtraction = calculate(10, 5)
print(addition)
print(subtraction)Output:
15
5A function can return more than two values in the same way:
def student():
return "Abhishek", 22, "Python"
name, age, course = student()
print(name)
print(age)
print(course)Output:
Abhishek
22
Pythonreturn vs print()
Although both return and print() can appear inside a function, they serve different purposes.
print() displays a value on the screen, while return sends a value back to the caller.
def using_print():
print(10)
def using_return():
return 10
x = using_print()
y = using_return()
print("x =", x)
print("y =", y)Output:
10
x = None
y = 10The first 10 is displayed by print() inside using_print(). However, that function does not return a value, so x receives None.
The using_return() function sends 10 back to the caller, so y contains 10.
The difference becomes especially useful when the result needs to be reused:
def square(number):
return number * number
result = square(5)
double = result * 2
print(double)Output:
50With return, the result of a function can be stored in a variable, passed to another function, or used in calculations. print() is mainly used when you simply want to display information.