Home >Backend Development >Python Tutorial >How to use return value in Python
Python return value return usage is that when the function executes the return statement, execution will stop immediately and the specified value will be returned to the place where the function was called. Detailed usage: 1. Return a single value; 2. Return multiple values; 3. Return a null value; 4. End the execution of the function early.
#The return statement in Python is used to return a value in a function. When the function executes to the return statement, it will immediately stop execution and return the specified value to the place where the function was called.
In Python, the return statement can be used in the following ways:
Return a single value:
def add(a, b): return a + b result = add(3, 4) print(result) # 输出:7
In the above example, the add function Accepts two parameters a and b and returns their sum. The result variable receives the return value of the function and prints it out.
Return multiple values:
def divide(a, b): quotient = a // b remainder = a % b return quotient, remainder result = divide(10, 3) print(result) # 输出:(3, 1)
In the above example, the divide function accepts two parameters a and b, and assigns their quotient and remainder to quotient and remaining variables. Then, separate the two variables with a comma and return them as a tuple. The result variable receives the return value of the function and prints it out.
Return a null value:
def print_hello(): print("Hello") result = print_hello() print(result) # 输出:None
In the above example, the print_hello function does not return any value, so there is no return statement at the end of the function. When this function is called, it prints "Hello", but the return value of the function is None. None means null or no value.
End the execution of the function early:
def check_positive(num): if num <= 0: return False else: print("Positive number") return True result = check_positive(-5) print(result) # 输出:False
In the above example, the check_positive function accepts a parameter num. If num is less than or equal to 0, use the return statement to return False , and execution of the function terminates immediately. If num is greater than 0, print "Positive number" and then use the return statement to return True.
It should be noted that when the function executes the return statement, it will stop execution immediately, and subsequent code will not be executed. Therefore, if the return statement is inside a loop or conditional statement, it will end the execution of these statements early.
Summary:
The return statement is used to return a value in a function, and can be used in the following ways: return a single value, return multiple values, return null value and terminate the execution of the function early.
The above is the detailed content of How to use return value in Python. For more information, please follow other related articles on the PHP Chinese website!