How to use the Python return Statement
In this tutorial, you'll learn how to use the Python return statement with examples.
What is the return statement in Python?
A return statement is a statement that occurs in a function definition used to return a value to a function call.
The return Statement Syntax
The following illustrates the syntax of the return statement:
def function_name:
return [expression_list]
Remarks
- The express_list can be a variable or a function call.
- If the expression_list omitted, the function call returns None, otherwise, returns a value.
Examples
Example 1:
Sums two numbers and returns a total:
#sums 2 numbersdef sum(a, b):return a + btotal = sum(100, 200)print(total)
Output:
300
Example 2:
Returns a value of an expression of comparing two numbers:
#compares 2 numbersdef compare(a, b):return a > bprint(compare(10, 20))
Output:
False
Example 3:
Returns None:
#returns Nonedef get_name(name):returnprint (get_name("James"))
The function get_name returns None since the express_list omitted.
Example 4:
Calls one function inside another function:
#call one function inside another functiondef sum1(a, b):return a + bdef sum2(a, b, c):return sum1(a, b) + cprint(sum2(10, 20, 30))
Output:
60
Example 5
#returns OK or NGdef example_if(a):if a > 10:return "OK"print("Print this line if a <= 10")return "NG"print(example_if(10))
Output:
Print this line if a <= 10
NG
If you change the value of parameter a to something else that is larger than 10, the output will look like this:
OK
Read more:
- Python break statement
- Python continue statement
- for loop statement in Python
- while loop statement in Python
- Python if-else statement
In this tutorial, you've learned how to use the Python return statement.