In Python, a function can return a value to the calling code using the return keyword. Here's an example of a function that returns the sum of two numbers:
def add_numbers(x, y): return x + yresult = add_numbers(3, 4)print(result) # Output: 7 |
In this example, the add_numbers function returns the sum of x and y using the return keyword. When the function is called with add_numbers(3, 4), the result is returned and assigned to the result variable.
A function can also return multiple values by returning them as a tuple. Here's an example:
def divide_numbers(x, y): quotient = x / y remainder = x % y return quotient, remainderresult = divide_numbers(10, 3)print(result) # Output: (3.3333333333333335, 1) |
In this example, the divide_numbers function returns two values, quotient and remainder, as a tuple. When the function is called with divide_numbers(10, 3), the tuple (3.3333333333333335, 1) is returned and assigned to the result variable.
You can also use the return keyword without any arguments to exit a function early and return None. Here's an example:
def check_number(x): if x < 0: return 'Negative' elif x == 0: return 'Zero' else: return 'Positive'result = check_number(-2)print(result) # Output: Negative |
In this example, the check_number function returns a string indicating whether the input x is negative, zero, or positive. If x is negative, the function returns 'Negative' using the return keyword, which exits the function early. If x is not negative, the function continues executing and eventually returns 'Zero' or 'Positive' depending on the value of x.