Python Function Return Value Explained with Examples

Python functions can return values using the return statement. When a function is called and a return statement is encountered, the function stops executing, and the specified value is passed back to the caller.

Basic Return Statement

Use the return statement to send a value back to the caller.

def add_numbers(a, b):
    return a + b

result = add_numbers(5, 3)
print(result)  # Output: 8

Returning Multiple Values

Python functions can return multiple values as a tuple.

def calculate_values(x, y):
    sum_val = x + y
    product = x * y
    return sum_val, product

s, p = calculate_values(4, 3)
print(s)  # Output: 7
print(p)  # Output: 12

Returning None

If no return statement is specified, the function returns None by default.

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

result = greet("Alice")
print(result)  # Output: None

Returning Complex Objects

Functions can return any Python object, including lists, dictionaries, or custom objects.

def create_person(name, age):
    return {"name": name, "age": age}

person = create_person("Alice", 30)
print(person)  # Output: {'name': 'Alice', 'age': 30}

Returning Functions

Functions can also return other functions, allowing for advanced programming patterns like closures.

def get_multiplier(factor):
    def multiplier(x):
        return x * factor
    return multiplier

times_3 = get_multiplier(3)
print(times_3(4))  # Output: 12

Returning Lambda Functions

Lambda functions can be directly returned from a function.

def generate_incrementor(n):
    return lambda x: x + n

inc_by_5 = generate_incrementor(5)
print(inc_by_5(10))  # Output: 15