VMware ESXi and vSphere Cluster Management

Python Return Statement

Learn how Python return statements send values from functions to calling code, including None, conditional returns, and tuple unpacking.

What the Python return statement does

A function is a named, reusable block of code that can accept input and optionally produce a result. The return statement sends a result from a function back to the code that called it and finishes that function call.

Returning a value is different from displaying a value with print(). A printed value appears on the screen, but a returned value becomes available to the caller. The caller can store it, use it in another expression, pass it to another function, or print it later.

def add_tax(price):
    return price * 1.20

final_price = add_tax(50)
print(final_price)

Here, add_tax(50) returns 60.0. The caller stores that return value in final_price.

Basic return syntax

Place return inside a function body, followed by a value or expression:

def square(number):
    return number * number

When Python reaches the statement, it evaluates the expression and sends the resulting value to the caller. In this example, square(4) produces the number 16.

The indentation is important. The return statement must be part of the def block:

def greet(name):
    return "Hello, " + name

A function definition is the code beginning with def that creates a function and names its parameters. A function call runs that function by placing its name followed by parentheses, such as greet("Sam").

Following a return value from call to caller

A parameter is a variable listed in a function definition. An argument is the actual value supplied in a function call. With a positional argument, Python matches values to parameters by their position.

StageExample roleDescription
Argument supplied at call siteconvert(25)25 is the value supplied by the caller.
Parameter inside functiondollarsThe parameter receives the argument value.
Calculation within functiondollars * 0.92The function computes a new value.
Return value assigned by callereuros = convert(25)The caller stores the value sent back by the function.

The flow is therefore: argument value, parameter, calculation, return value, and assignment in the caller.

Central example: currency conversion

This example accepts a dollar amount, applies a fixed exchange-rate multiplier, returns the converted amount, and displays it outside the function. The rate is only an example; real exchange rates change.

def dollars_to_euros(dollars):
    exchange_rate = 0.92
    euros = dollars * exchange_rate
    return euros

amount_text = input("Enter an amount in dollars: ")
dollars = float(amount_text)
euros = dollars_to_euros(dollars)
print(f"You have approximately {euros:.2f} euros.")

input() always produces text, also called a string. float() converts that text into a number that can be used in arithmetic. The value in dollars is passed as an argument to dollars_to_euros(); inside the function, the parameter named dollars receives it. The calculated result is returned and assigned to euros.

return versus print()

print() is useful when a function's purpose is to display information. It does not, by itself, send the displayed value back as the function's result.

def print_total(price, tax):
    print(price + tax)

def calculate_total(price, tax):
    return price + tax

printed_result = print_total(10, 2)
calculated_result = calculate_total(10, 2)

print(printed_result)       # None
print(calculated_result)    # 12
print(calculated_result * 2)  # 24

The first function displays 12, but printed_result receives None. The second function returns 12, so the caller can store and reuse it.

Function body behaviorValue received by callerTypical use
return expressionThe expression's valueCalculate and provide a result.
return with no expressionNoneStop the function while explicitly indicating no meaningful result.
No return statementNone implicitlyPerform an action or side effect without producing a result.
print expression without returnNone, although text appears on screenDisplay information only.

None is Python's special value for no meaningful result. It is not the same as 0, False, or an empty string.

Execution flow after return

return immediately ends the current function invocation. Statements below an unconditional return in the same block cannot run.

def describe(number):
    return "The function ends here."
    print("This line is never executed.")

message = describe(5)
print(message)

After the function returns its value, execution continues in the caller. In this example, Python assigns the result to message and then runs the next print() statement outside the function.

Place required calculations or actions before the return, or use conditional branches when different situations need different results.

Returning different types

A function can return any Python value, including numbers, strings, Boolean values, and collections. The caller should use the returned type appropriately.

def get_score():
    return 87                 # int

def get_label():
    return "passed"           # str

def is_positive(number):
    return number > 0          # bool

def get_colors():
    return ["red", "green"]   # list

score = get_score()
label = get_label()
positive = is_positive(3)
colors = get_colors()

print(score + 5)
print(label.upper())
print(positive)
print(colors[0])

A returned list can be indexed or looped over, a returned string can use string methods, and a returned Boolean can control an if statement.

Conditional returns

Return statements can appear inside if and else branches. If a function is expected to produce a value, make sure every intended path returns an appropriate value.

Boolean eligibility check

def is_eligible(age):
    if age >= 18:
        return True
    else:
        return False

age = 20
if is_eligible(age):
    print("Eligible")
else:
    print("Not eligible")

This function returns a Boolean result. The caller uses that result directly as the condition of an if statement.

Status result with several branches

def score_status(score):
    if score >= 90:
        return "excellent"
    elif score >=  pass_mark:
        return "passed"
    else:
        return "not passed"

The previous example contains an undefined name, so use a complete version with a parameter for the passing threshold:

def score_status(score, pass_mark):
    if score >= 90:
        return "excellent"
    elif score >= pass_mark:
        return "passed"
    else:
        return "not passed"

status = score_status(76, 60)
print(status)

Each branch returns a string, so every expected path produces a result. If a conditional function omits a return in one path, calls taking that path reach the end and produce None.

Returning multiple values

Python can return several values separated by commas. Conceptually, the function returns one tuple value. Tuple unpacking assigns the tuple's items to separate variables for convenience.

def find_min_max(numbers):
    return min(numbers), max(numbers)

smallest, largest = find_min_max([8, 3, 11, 5])
print(smallest)  # 3
print(largest)   # 11

The returned value is conceptually (3, 11). The assignment unpacks its first item into smallest and its second item into largest.

You can also receive the tuple as one variable:

result = find_min_max([8, 3, 11, 5])
print(result)       # (3, 11)
print(result[0])    # 3

Local variables and returned results

Variables created inside a function are usually local to that function. Code outside the function cannot directly use a local calculation variable unless the function returns its value.

def calculate_area(width, height):
    area = width * height
    return area

room_area = calculate_area(4, 6)
print(room_area)

The local variable area exists while the function runs. The returned value is assigned to room_area in the caller.

Common problems and fixes

The assigned result is None

The function may print a value without returning it, or it may reach the end without an explicit return. Add return for the intended result:

def wrong_double(number):
    print(number * 2)


def correct_double(number):
    return number * 2

result = correct_double(5)

Code after return does not execute

This is expected because return ends the current function call. Move necessary statements before it or restructure the branches.

Syntax or indentation error

A return statement outside a function is invalid, and incorrect indentation can place it outside the intended block. Keep it indented beneath def:

def get_message():
    return "Ready"

Some calls return a value and others return None

A conditional branch probably has no return statement. Add a return to every expected branch, or deliberately handle None in the caller.

Arithmetic fails after input()

Because input() returns text, convert it before passing it to a calculation function:

amount = float(input("Amount: "))
converted = dollars_to_euros(amount)

The function result is unavailable outside the function

A local variable does not automatically become available to the caller. Return the local calculation and assign the function call's result:

def make_message(name):
    message = "Hello, " + name
    return message

message_for_user = make_message("Riley")

Key points

  • return expression evaluates the expression and sends its value to the caller.
  • return by itself sends None.
  • A function with no explicit return statement also returns None.
  • return immediately ends the current function invocation.
  • Returning is different from printing: returned values can be assigned, reused, or passed elsewhere.
  • Conditional functions should return suitable values on every expected path.
  • Several comma-separated return values form one tuple, which can be unpacked into multiple variables.