It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

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!

  1. Write a function multiply(x, y) that returns the result of x multiplied by y.
  2. Create a function get_full_name(first, last) that returns the full name as one string.
  3. 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 returns None.
  • Return values can be stored and reused in your code.