What is Python Return Statement?

In this tutorial, I will explain what is Python return statement. As a Python developer working on a project for one of my clients, I often came across a scenario while working on functions to use a return statement. I researched more about the return statement and I will share my findings in this article with examples and screenshots of executed example code.

Return Statement in Python

The return statement in Python is used to exit a function and return a value to the caller. This is crucial for creating reusable and modular code. By using return , you can send the result of a function’s computation to other parts of your program.

Read Is Python a High Level Language?

Syntax of the Return Statement

The basic syntax of the return the statement is simple:

def function_name(parameters):
    # function body
    return value

Here’s a simple example to illustrate its use:

def calculate_tax(amount, tax_rate):
    tax = amount * tax_rate
    return tax

# Calling the function
total_tax = calculate_tax(100, 0.07)
print(total_tax)  # Output: 7.0

Output:

7.000000000000001

I have executed the above example code and added the screenshot below.

Python Return Statement

In this example, the calculate_tax function computes the tax for a given amount and tax rate, then uses the return statement to send the result back to the caller.

Check out Is Python a High Level Language?

Return Multiple Values

Python allows functions to return multiple values using tuples. This can be particularly useful when you need to return several pieces of related information from a function.

def user_info():
    name = "John Doe"
    age = 30
    city = "New York"
    return name, age, city

# Calling the function
name, age, city = user_info()
print(name) 
print(age)  
print(city)

Output:

John Doe
30
New York

I have executed the above example code and added the screenshot below.

What is Python Return Statement

In this example, the user_info function returns three pieces of information: name, age, and city. These values are then unpacked into separate variables.

Read Is Python a Compiled Language?

Use Return with Conditional Statements

The return statement can be used within conditional statements to exit a function early based on certain conditions. This is useful for handling edge cases or errors.

def find_discount(price):
    if price < 0:
        return "Invalid price"
    elif price > 100:
        return price * 0.10
    else:
        return price * 0.05

# Calling the function
discount = find_discount(150)
print(discount)

Output:

15.0

I have executed the above example code and added the screenshot below.

Python Return Statement with Conditional Statements

Here, the find_discount function checks the price and returns different discount values based on the conditions.

Check out Is Python an Interpreted Language?

Example: Calculate Mortgage Payments

Let’s take a real-world example that is relevant to our target audience in the USA. We will create a function to calculate monthly mortgage payments.

def calculate_mortgage(principal, annual_rate, years):
    monthly_rate = annual_rate / 12 / 100
    payments = years * 12
    if monthly_rate == 0:
        return principal / payments
    else:
        return principal * (monthly_rate * (1 + monthly_rate) ** payments) / ((1 + monthly_rate) ** payments - 1)

# Calling the function
principal = 300000
annual_rate = 3.75
years = 30
monthly_payment = calculate_mortgage(principal, annual_rate, years)
print(f"Monthly Payment: ${monthly_payment:.2f}")  # Output: Monthly Payment: $1389.35

In this example, the calculate_mortgage function computes the monthly mortgage payment based on the principal amount, annual interest rate, and loan term in years.

Check out Difference Between is and == in Python

Common Issues and Best Practices

1. Avoid Unintended None Returns

If a function does not explicitly return a value, it implicitly returns None. This can lead to unexpected behavior if not handled properly.

def check_even(number):
    if number % 2 == 0:
        return True

# Calling the function
result = check_even(5)
print(result)  # Output: None

In this example, check_even returns None when the number is not even. To avoid this, ensure that all possible code paths in your function include a return statement.

Read How to Comment Out Multiple Lines in Python?

2. Return Complex Data Structures

When dealing with complex data structures like lists or dictionaries, ensure that your function’s return value is well-documented and consistent.

def get_city_data():
    cities = {"New York": {"population": 8419000, "area": 468.9},
              "Los Angeles": {"population": 3980000, "area": 503},
              "Chicago": {"population": 2716000, "area": 589}}
    return cities

# Calling the function
city_data = get_city_data()
print(city_data["New York"]["population"])  # Output: 8419000

In this example, get_city_data returns a dictionary containing data about several cities. The structure of the returned data is clear and consistent.

Read Python vs C# [Performance Comparison]

Conclusion

In this tutorial, I have explained what is Python return statement. I discussed the syntax of return statements, how to return multiple values , how to use return with conditional statements and a real-time example. I also discussed common issues and best practices.

You may also like to 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.