Python for AIPython for AI
Functions

Return values

Get results back from your functions

Functions are great for organizing your code. They let you reuse blocks of instructions. But sometimes, you want a function to give you information back. This is where return values come in handy!

Getting results from functions

Imagine you have a function that calculates an answer. How do you get that answer out of the function so you can use it in other parts of your program? That's what returning a value does.

It's like asking a friend to do a task for you. They do the task, and then they tell you the result. Your program works the same way: a function performs its job and then "tells" your program its outcome.

The return statement

To send a value back from a function, you use the return keyword. When Python sees return, it immediately exits the function and sends the value specified right after return back to where the function was called.

python
def add_numbers(a, b):
    sum_result = a + b
    return sum_result # This sends sum_result back

# Call the function and store its return value
my_total = add_numbers(5, 3)
print(my_total)

Using returned values

The value a function returns can be stored in a variable, used in an expression, or even passed as an argument to another function.

python
def calculate_area(length, width):
    return length * width

room_area = calculate_area(10, 7) # Store in a variable
print(f"The room area is: {room_area} square units")

double_area = calculate_area(4, 5) * 2 # Use in an expression
print(f"Double the area is: {double_area}")

Returning multiple values

Python has a cool feature: functions can return more than one value! You just list them separated by commas after the return keyword.

When a function returns multiple values, Python actually packs them into a single 'tuple'. You can then unpack this tuple into separate variables.

python
def get_user_info():
    name = "Alice"
    age = 30
    city = "New York"
    return name, age, city # Returns a tuple (name, age, city)

# Unpack the returned values into separate variables
user_name, user_age, user_city = get_user_info()

print(f"Name: {user_name}, Age: {user_age}, City: {user_city}")

Return vs print

This is a common point of confusion for beginners. print() simply displays something on your screen. return sends a value back from the function so your program can actually use it.

  • print() is for human eyes.
  • return is for your code to use the result.
python
def function_with_print(num):
    print(f"Inside print function: {num * 2}")

def function_with_return(num):
    return num * 2


result_print = function_with_print(5) # Prints, but result_print is None
result_return = function_with_return(5) # Returns 10, result_return is 10

print(f"Value from print function call: {result_print}")
print(f"Value from return function call: {result_return}")

Functions without return

What happens if a function doesn't have a return statement? Python functions always return something. If you don't specify a return value, the function implicitly returns None.

None is a special Python keyword that represents the absence of a value.

python
def greet(name):
    print(f"Hello, {name}!")
    # No return statement here

my_greeting = greet("Bob")
print(f"The return value of greet is: {my_greeting}")

Common mistakes

  • Forgetting to store the returned value: If a function returns something, make sure you assign it to a variable or use it immediately.
  • Confusing print with return: Remember, return gives data back, print shows it.
  • Placing return too early: Any code after a return statement in a function will not be executed.
python
def example_func(x):
    return x * 2
    print("This line will never run!") # Dead code

final_value = example_func(10)
print(final_value)

Practice

Try these exercises to lock in what you just learned.

Quiz
Not started
What does a function return if it has no `return` statement?
Code challenge
Not started
Write square(n) that returns n*n, then print square(6).

What's next?

Now you know how to make your functions give back useful information! This is a core concept that you'll use all the time. Practice creating functions that perform calculations or fetch data and then return the results.

Next, you might explore more complex data types that functions can return, like lists or dictionaries, or learn about different ways to handle function arguments.