Return Values in Functions
You’ll understand how to make your functions send data back using the return
statement.
What Is a Return Value?
So far, we’ve seen functions that do something — like print output. But what if we want a function to give something back?
That’s where return
comes in!
def add(a, b):
return a + b
result = add(5, 3)
print(result) # Output: 8
return
sends data back to wherever the function was called.
Why Use return
?
Using return
allows you to:
- Store the result in a variable.
- Use it in calculations or logic.
- Chain multiple functions together.
def square(x):
return x * x
def cube(x):
return x * square(x)
print(cube(3)) # Output: 27
A Function Ends When It Returns
The moment return
is hit, the function exits immediately — even if there's more code after it.
def test():
return "Done"
print("This will never run")
print(test()) # Output: Done
No Return? It Returns None
def say_hello():
print("Hello")
result = say_hello()
print(result) # Output: Hello \n None
You Can Return Anything
Functions can return any type of value — numbers, strings, lists, even other functions!
def make_list():
return [1, 2, 3]
print(make_list()) # Output: [1, 2, 3]
Exercise: Try It Yourself!
- Write a function
multiply(x, y)
that returns the result of x multiplied by y. - Create a function
get_full_name(first, last)
that returns the full name as one string. - Build a function
get_even_numbers(numbers)
that takes a list and returns only the even numbers.
Summary
return
lets a function send back a result.- Once
return
is reached, the function stops. - If you don’t use
return
, Python returnsNone
. - Return values can be stored and reused in your code.