Python return Statement
The return
statement is used inside a function to send a value back to the caller. It ends the function's execution.
Syntax
def function_name():
return value
value
can be any Python object: number, string, list, dict, etc.- If no
return
is specified, the function returnsNone
.
Example 1: Basic Return
def greet():
return "Hello"
message = greet()
print(message)
Output:
Hello
Example 2: Return a Calculation
def add(a, b):
return a + b
result = add(3, 4)
print("Sum:", result)
Output:
Sum: 7
Example 3: Return Multiple Values
def stats(a, b):
return a + b, a * b
sum_val, product = stats(3, 4)
print("Sum:", sum_val)
print("Product:", product)
Output:
Sum: 7
Product: 12
Python functions can return multiple values as a tuple.
Example 4: Early Return
def check_age(age):
if age < 18:
return "Too young"
return "Allowed"
print(check_age(15))
print(check_age(20))
Output:
Too young
Allowed
Example 5: No Return = None
def no_return():
print("I do not return anything")
result = no_return()
print(result)
Output:
I do not return anything
None
return
vs print
print() | return |
---|---|
Displays output on the screen | Sends result to the caller function |
Used for debugging/output | Used to pass data between functions |
Doesn't end function | Ends the function immediately |
Real-World Use Case
def is_even(n):
return n % 2 == 0
nums = [1, 2, 3, 4]
evens = list(filter(is_even, nums))
print(evens)
Output:
[2, 4]
Summary
return
ends the function and sends data back.- You can return any data type.
- Returning multiple values is allowed (as a tuple).
- A function without
return
returnsNone
.
Practice Task
Write a function that returns both square and cube of a number:
def power(n):
return n**2, n**3
sq, cb = power(3)
print("Square:", sq)
print("Cube:", cb)
Output:
Square: 9
Cube: 27