Loading...

Section

Return Values: Getting Information Back

Part of The Prince Academy's AI & DX engineering stack.

Follow The Prince Academy Inc.

One of the most powerful aspects of functions is their ability to 'return' values. This means a function can perform a calculation or process data, and then send the result back to the part of your program that called it. Think of it like ordering a pizza; you ask for it (call the function), and the pizza place makes it and gives it back to you (the return value).

To make a function return a value, you use the return keyword. Whatever expression, variable, or value comes after return will be sent back.

def add_numbers(x, y):
    sum_result = x + y
    return sum_result

result = add_numbers(5, 3)
print(result)

In the example above, the add_numbers function calculates the sum of x and y. The return sum_result line sends that sum back. The line result = add_numbers(5, 3) captures this returned value and stores it in the result variable. Finally, print(result) displays the value that was returned.

What happens if a function doesn't have a return statement? By default, Python functions return None. This is a special value representing the absence of a value.

def greet(name):
    print(f"Hello, {name}!")

return_value = greet("Alice")
print(return_value)

In this greet function, print is executed, but there's no return statement. So, when we try to capture its return value, we get None.

A function can return multiple values. To do this, you simply separate the values you want to return with commas. Python will automatically pack these into a tuple.

def get_coordinates():
    x = 10
    y = 20
    return x, y

coords = get_coordinates()
print(coords)
print(type(coords))

When calling a function that returns multiple values, you can also 'unpack' them directly into separate variables, which is often more convenient.

def get_name_and_age():
    name = "Bob"
    age = 30
    return name, age

person_name, person_age = get_name_and_age()
print(f"Name: {person_name}, Age: {person_age}")
graph TD;
    A[Function Call] --> B{Execute Function Body};
    B --> C{Encounter 'return'};
    C --> D[Return Value];
    D --> E[Store/Use Value];
    B --> F{No 'return' Found};
    F --> G[Return None];
    G --> E;

Understanding return values is crucial for building complex programs. It allows functions to be independent, self-contained units that perform specific tasks and provide their results to other parts of your code, making your programs modular, organized, and easier to debug.