return
In Python, the return
keyword exits a function and returns a value back to the caller. It allows you to send results back from a function so that you can use them elsewhere in your program. If no value is specified, return
will return None
by default.
Python return
Keyword Examples
Here’s an example to illustrate how the return
keyword is used in Python:
>>> def add(a, b):
... return a + b
...
>>> result = add(3, 5)
>>> result
8
In this example, the add()
function takes two numeric values as arguments and returns their sum. The return
keyword sends the result of a + b
back to where the function was called and stores it in the variable result
, which you can access in your code.
Python return
Keyword Use Cases
- Returning results from a function to be used in further computations or operations
- Exiting a function early if a certain condition is met
- Returning multiple values from a function using tuples
- Implementing recursive functions
Related Resources
Tutorial
The Python return Statement: Usage and Best Practices
In this step-by-step tutorial, you'll learn how to use the Python return statement when writing functions. Additionally, you'll cover some good programming practices related to the use of return. With this knowledge, you'll be able to write readable, robust, and maintainable functions in Python.
For additional information on related topics, take a look at the following resources:
- Defining Your Own Python Function (Tutorial)
- How to Use Type Hints for Multiple Return Types in Python (Tutorial)
- Python's Self Type: How to Annotate Methods That Return self (Tutorial)
- Using the Python return Statement Effectively (Course)
- The Python return Statement (Quiz)
- Defining and Calling Python Functions (Course)
- Defining Your Own Python Function (Quiz)
- Using Type Hints for Multiple Return Types in Python (Course)