Python Return Statement

I’ve found that the return statement is the most fundamental tool for controlling data flow.

It is the bridge that allows a function to send a result back to the caller, turning a block of code into a reusable tool.

I remember struggling with “None” values early in my career because I forgot that a function without a return statement doesn’t give anything back.

In this tutorial, I’ll show you exactly how to use the return statement effectively, using real-world scenarios you’ll encounter in data processing and web development.

Basics of the Python Return Statement

At its core, the return statement exits a function and optionally passes an expression back to the main program.

Think of it like a specialist contractor; you give them instructions (arguments), and they hand you back a finished product (the return value).

If you don’t include a return statement, Python automatically returns None, which can often lead to bugs in your logic.

Method 1: Return a Single Value (Tax Calculation Example)

The most common use case is performing a calculation and returning a single result, such as a Sales Tax calculation for a US state.

In this example, I’ll calculate the total price of an item, including the California state sales tax of 7.25%.

def calculate_ca_total(price):
    # California base sales tax is 7.25%
    tax_rate = 0.0725
    total = price + (price * tax_rate)
    return round(total, 2)

# Purchasing a laptop in San Francisco
laptop_price = 1200.00
final_bill = calculate_ca_total(laptop_price)

print(f"The final price after CA tax is: ${final_bill}")

You can refer to the screenshot below to see the output.

return function python

In this code, the function processes the input and “hands off” the final number to the final_bill variable.

I always recommend using round() when dealing with financial data to avoid floating-point precision issues common in Python.

Method 2: Return Multiple Values Using Tuples

One of my favorite features of Python is the ability to return multiple values at once without creating a complex object.

Suppose you are analyzing a real estate listing in New York and want to get both the price per square foot and the total area.

Python allows you to return these as a tuple, which you can then unpack directly into separate variables.

def analyze_nyc_listing(total_price, sq_ft):
    price_per_sqft = total_price / sq_ft
    property_status = "Luxury" if total_price > 2000000 else "Standard"
    return price_per_sqft, property_status

# A condo in Manhattan
price, status = analyze_nyc_listing(2500000, 1200)

print(f"Price per SqFt: ${price:.2f}")
print(f"Property Class: {status}")

You can refer to the screenshot below to see the output.

python return function

Notice how the function returns two distinct pieces of data; this keeps your code clean and prevents you from writing two separate functions for related data.

Method 3: Use Return to Exit Early (Validation Logic)

Experienced developers use the return statement as a “guard clause” to exit a function if certain conditions aren’t met.

This is much cleaner than nesting multiple if-else blocks, which can make your code hard to read.

Let’s look at a function that processes a US Zip Code and exits immediately if the input is invalid.

def process_us_zip(zip_code):
    # Guard clause: Check if the zip code is exactly 5 digits
    if len(str(zip_code)) != 5:
        return "Invalid Zip Code"
    
    # Logic for valid zip codes
    return f"Processing shipments for area: {zip_code}"

print(process_us_zip(90210))  # Valid
print(process_us_zip(123))    # Invalid - returns early

You can refer to the screenshot below to see the output.

python function return

I find this pattern incredibly helpful for data validation in web forms where you want to catch errors before the heavy processing starts.

Method 4: Return a List of Objects (US Tech Stocks)

Sometimes you need to return a collection of data, like a list of processed strings or objects.

In this scenario, we will filter a list of US tech companies and return only those that meet a specific criteria.

def get_top_tech_stocks(stocks_list):
    high_value_stocks = []
    for stock, price in stocks_list.items():
        if price > 200:
            high_value_stocks.append(stock)
    return high_value_stocks

nasdaq_prices = {
    "AAPL": 175.43,
    "MSFT": 405.12,
    "AMZN": 178.22,
    "NVDA": 875.30,
    "GOOGL": 154.20
}

portfolio_picks = get_top_tech_stocks(nasdaq_prices)
print(f"Stocks to watch: {portfolio_picks}")

You can refer to the screenshot below to see the output.

return function

Returning a list is perfect when the number of results is dynamic and depends on the input data.

Method 5: Return a Dictionary for Complex Data

When returning more than three values, I typically stop using tuples and start using dictionaries.

Dictionaries provide context to the data because each value is associated with a specific key.

Let’s look at an example of a payroll calculator for an employee in Texas (where there is no state income tax).

def calculate_payroll(hours_worked, hourly_rate):
    gross_pay = hours_worked * hourly_rate
    federal_tax = gross_pay * 0.15  # Simplified federal rate
    net_pay = gross_pay - federal_tax
    
    return {
        "gross": round(gross_pay, 2),
        "tax_deducted": round(federal_tax, 2),
        "take_home": round(net_pay, 2),
        "location": "Texas"
    }

employee_pay = calculate_payroll(40, 55.00)
print(f"Net Pay: ${employee_pay['take_home']}")

Using a dictionary here makes the code self-documenting, as the person reading the code knows exactly what employee_pay[‘take_home’] represents.

Method 6: Return Another Function (Closure)

In advanced Python development, you might encounter a situation where you need a function to return another function.

This is a powerful concept used in decorators and functional programming.

Imagine you are creating a custom discount calculator for a Black Friday sale at a US retailer.

def discount_generator(discount_percent):
    def apply_discount(price):
        return price * (1 - discount_percent)
    return apply_discount

# Create a specific 20% off function
black_friday_deal = discount_generator(0.20)

original_price = 500.00
final_price = black_friday_deal(original_price)

print(f"Holiday Sale Price: ${final_price}")

Here, the outer function “remembers” the discount percentage, allowing you to create multiple specific discount functions easily.

Best Practices for Using Return Statements

Throughout my years of coding, I’ve developed a few rules of thumb for using return statements.

First, consistency is key; if a function returns a value in one scenario, it should ideally return the same type of value in all scenarios.

Second, avoid returning too many values in a tuple; if you are returning more than four items, it’s time to use a dictionary or a class.

Finally, always remember that any code written after a return statement in the same block will never be executed.

I’ve seen many junior developers place logging or cleanup code after a return, only to wonder why it never runs.

Conclusion

The Python return statement is more than just a way to end a function; it is how you design the flow of your application.

Whether you are returning a simple tax calculation, a list of stocks, or a complex dictionary of payroll data, understanding how to pass data back to your main program is essential.

I hope this guide helps you write cleaner, more efficient Python code in your future projects.

You may read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.