In Python, you can define a function with multiple parameters and return values. Here's an example:
def add_and_multiply(x, y): """ Adds two numbers and returns their sum and product. """ return x + y, x * y |
In this example, the function add_and_multiply takes two parameters x and y, and returns a tuple of two values: the sum of x and y, and the product of x and y.
You can call this function and unpack its return values like this:
sum, product = add_and_multiply(3, 4)print(sum) # Output: 7print(product) # Output: 12 |
In this example, the values 7 and 12 are unpacked from the tuple returned by the add_and_multiply function and assigned to the variables sum and product.
You can also call a function with a variable number of arguments using the *args and **kwargs syntax. Here's an example:
def multiply_numbers(*numbers): """ Multiplies any number of numbers together. """ result = 1 for number in numbers: result *= number return resultproduct = multiply_numbers(2, 3, 4, 5)print(product) # Output: 120 |
In this example, the function multiply_numbers takes any number of arguments and multiplies them together. The *numbers syntax in the function definition creates a tuple of all the arguments passed to the function, which can then be iterated over in the for loop.