Python return
The return keyword in Python is used inside a function to terminate its execution and send a value back to the caller.
Syntax
def function_name():
return value
The return statement is used inside a function defined using the def keyword. It must be written in lowercase (return). Using incorrect casing like Return or RETURN will result in a SyntaxError.
Example 1
In this example, the sum() function returns the sum of the two input values:
def sum(a, b):result = a + breturn resultprint (sum(3, 4))
The output of this code is:
7
Example 2
In this example, the get_user() function demonstrates returning multiple values by separating them with commas:
def get_user():firstname = "Jane"lastname = "Doe"age = 30return firstname, lastname, ageuser_firstname, user_lastname, user_age = get_user()print(user_firstname)print(user_lastname)print(user_age)
The output of this code will be:
JaneDoe30
Codebyte Example
The return keyword can be used to exit a function early. When used without a value, it implicitly returns None (which means no value is returned). The following code is demonstrating the same:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours