In this Python tutorial, I will explain what is Python return function. I will explain different use cases of return statements in Python with examples.
Python is one of the most popular programming languages around the world, primarily because of its simplicity and versatility. One of its many features is the return statement, used in functions to send a result back to where the function was called in Python.
We will delve deep into the Python return function, elucidating its mechanics with relatable scenarios.
Before this, let’s get familiar with the function in Python.
A function in Python is a block of organized, reusable code that is used to perform a single, related action. Python functions provide better modularity for our application and a high degree of code reuse.
Syntax:
def function_name(parameters):
"""docstring"""
# code
return value
- def keyword: This is used to declare/define a function in Python.
- function_name: Represents the name of the Python function. It follows the same naming convention as variables in Python.
- parameters: These are the values we pass into the Python function. They are optional.
- docstring: Optional documentation string to describe what the Python function does.
- return: This is optional. It exits the Python function and passes back an expression to the caller.
Understanding Python Return Function
In Python, the return statement is used within a function to exit the function and send a value back to the location where the Python function was called. This returned value can then be used in different ways, such as storing it in a Python variable, using it in expressions, or passing it to other functions in Python.
If a function in Python doesn’t have a return statement, it returns None.
Basics of the Return Function in Python
When we create a function in Python, we often want it to produce a result. This result can be a value, an expression, or multiple values. The return statement is the way to send this result back to the place where the Python function was called. Essentially, the return statement accomplishes two main tasks:
Ending Function Execution | As soon as a return statement is encountered in a Python function, the execution of that function is halted. Any code written after the return statement (within the function) will not be executed unless the return is inside a conditional construct and the condition is not met in Python. |
Returning Value(s) to the Caller | The value or expression provided after the return keyword will be sent back (or returned) to the place where the Python function was called. If no value or expression is given with the return statement, the function returns None in Python. |
Let’s dive into the Use cases of the return function in Python.
Use cases of Python Return Statement
There are many different use cases of Python return statements.
- Basic Python return Function
- Functions Without a return Statement
- Python Return Function With Arguments
- Python Return Multiple Values
- Python Return to Exit a Function
- Python Return Function Object
Let’s leverage scenarios to provide a deeper understanding of each of the methods in Python here with an explanation.
Case 1: Basic Python Return Function
In a Python function, a return statement helps send back a value to where the function was called.
Scenario: Imagine walking into a store in New York to buy apples. The cost of each apple is fixed, and we want to know the total cost based on the number of apples we buy through Python.
The Python function calculate_cost receives the number of apples we want to buy. It then calculates the total cost and returns a value. When we call this function, we get back the amount we need to pay.
def calculate_cost(apples_count):
price_per_apple = 0.5
return apples_count * price_per_apple
apples_bought = 10
total_cost = calculate_cost(apples_bought)
print(f"The cost for {apples_bought} apples is ${total_cost}.")
Output: For every apple, we’re charged $0.50. Since we are buying 10 apples, the total cost is 10 * 0.50 = $5.0. The Python function returns the value, which is then printed using the print statement.
The cost for 10 apples is $5.0.
Python basic return function example.
Case 2: Python functions without a return statement
When a Python function does not have a return statement, it doesn’t send any specific value back. By default, such functions return None, which is a special constant in Python indicating the absence of a value.
Scenario: We visit the Lincoln Memorial in Washington, D.C., and there’s an audio guide that simply plays a welcome message without expecting any interaction from us through Python.
The Python function play_welcome_message just plays (prints) a welcome message. It doesn’t need to return anything. We assign this function’s output to a Python variable, the variable will hold the value None.
def play_welcome_message():
print("Welcome to the Lincoln Memorial!")
message = play_welcome_message()
print(message)
Output: This Python function’s purpose is straightforward: it prints a welcome message when invoked. There is no return value or calculation involved. When we call play_welcome_message(), it simply displays the message, “Welcome to the Lincoln Memorial!“. But, When we print the message Python variable it returns None.
Welcome to the Lincoln Memorial!
None
This way a Python function without return statement returns None.
Case 3: Python Return Function With Arguments
In Python, the return statement itself doesn’t directly accept arguments, but it does send a value (or multiple values) back from a Python function. This returned value can be based on the arguments that were passed to the Python function.
Here’s a breakdown:
- We define a Python function with parameters (placeholders for values you’ll provide later).
- Within the Python function, we can process these parameters.
- We use the return statement to send a value (often derived from the parameters) back to where the Python function was called.
Example 1: Calculating Sales Tax
In the USA, states have different sales tax rates. Here’s a Python function that takes the base price and the tax rate as arguments to the Python return function for the total price after tax:
def total_with_tax(price, tax_rate):
tax = price * (tax_rate / 100)
total_price = price + tax
return total_price
ny_total = total_with_tax(100, 8.875)
print(ny_total)
Output: Given the base price of a product and the sales tax rate for New York, the Python function calculates and returns the total price after tax.
108.875
Example 2: Finding the State Abbreviation
The USA has states with both full names and abbreviations. Let’s write a Python function that returns the abbreviation given the full state name:
def get_state_abbreviation(state_name):
abbreviations = {
'California': 'CA',
'Texas': 'TX',
'Florida': 'FL',
'New York': 'NY'
}
return abbreviations.get(state_name, 'Unknown')
abbreviation = get_state_abbreviation('California')
print(abbreviation)
Output:
CA
This way we can return Python function with arguments.
Case 4: Python Return Multiple Values
In many languages, a Python function can return only one value. However, Python allows us to return multiple values from a Python function. This is achieved by packing these values into a tuple and then unpacking them when we call the Python function.
Scenario: We’re in Silicon Valley and we’re interested in a startup’s financial data: both its earnings and expenses for the last quarter through Python.
The Python function get_financial_data returns both earnings and expenses of the startup. When we call this function in Python, we can unpack these values into separate variables for further analysis using Python return function.
def get_financial_data():
earnings = 100000
expenses = 75000
return earnings, expenses
last_quarter_earnings, last_quarter_expenses = get_financial_data()
print(f"Earnings: ${last_quarter_earnings}, Expenses: ${last_quarter_expenses}.")
Output: The Python function get_financial_data returns two values: earnings of $100,000 and expenses of $75,000. These values are unpacked into two separate variables: last_quarter_earnings and last_quarter_expenses. The print statement then displays these values. The result is an informative sentence sharing both the earnings and expenses.
Earnings: $100000, Expenses: $75000.
This way, return function in Python returns multiple values.
Case 5: Python Return to Exit a Function
Sometimes, we want to exit a Python function prematurely based on a condition or certain criteria. In such cases, we can use the return statement to exit the Python function even before all lines in the function have been executed.
Scenario: Consider a situation during the U.S. Presidential elections. Based on the votes a candidate receives in the electoral college, we want to determine if they’ve won, given that a candidate needs at least 270 electoral votes to win through Python.
The Python function has_candidate_won checks if the provided electoral votes are equal to or greater than 270. If the condition is met, the function immediately returns True, signaling a win. Otherwise, it returns False.
def has_candidate_won(electoral_votes):
if electoral_votes >= 270:
return True
return False
votes_received = 280
if has_candidate_won(votes_received):
print("The candidate has won!")
else:
print("The candidate has not won.")
Output: The has_candidate_won function in Python checks whether the number of electoral votes passed to it is greater than or equal to 270. Since the provided value is 280, which exceeds 270, the function returns True. The subsequent if-statement checks this returned value. Because it’s True, “The candidate has won!” is printed. If the candidate had received fewer than 270 votes, the Python function would return False, and “The candidate has not won.” would be printed instead.
The candidate has won!
This way, we can exit a function with the return statement.
Case 6: Python Return Function Object
In Python, everything is an object, including functions.
Let’s take the example of different USA states having their own state bird through Python:
class StateBird:
def __init__(self, state, bird):
self.state = state
self.bird = bird
def get_state_bird(state):
birds = {
"Alabama": "Yellowhammer",
"Alaska": "Willow ptarmigan"
}
return StateBird(state, birds.get(state, "Unknown"))
bird_obj = get_state_bird("Alabama")
print(f"The state bird of {bird_obj.state} is {bird_obj.bird}.")
Output: Here, the Python function get_state_bird returns an object of the StateBird class.
The state bird of Alabama is Yellowhammer.
This way, Python return function Object.
Conclusion
This tutorial explains what is Python return function and what are the different use cases of return statement in Python with examples.
The return statement is foundational to understanding function behavior in Python. It not only controls the flow of execution inside a function but also helps in producing meaningful outputs from a Python function. Recognizing how return works is a key step in writing efficient and modular Python code.
You may also like to read:
- How to Return Function Name in Python
- syntaxerror ‘return’ outside function Python error [Causes & How to Fix]
- What is Python typeof Function?
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.