What are the rules for defining variable parameters in Python?
In Python, variable parameters are a way to pass an indefinite number of parameters. The rules for defining variable parameters are as follows:
- Use an asterisk (*) to denote variable parameters. Placing the asterisk (*) before a parameter in the parameter list when defining a function indicates that the parameter can receive an indefinite number of arguments.
- Variable parameters will be treated as a tuple, even if no arguments are passed, it will be considered as an empty tuple.
- Variable parameters must be placed at the end of the parameter list.
Here is an example code demonstrating how to define and use variable parameters.
def foo(a, b, *args):
print("a =", a)
print("b =", b)
print("args =", args)
foo(1, 2, 3, 4, 5)
The output result is:
a = 1
b = 2
args = (3, 4, 5)
In the code above, the *args in the parameter list of function foo is used to accept a variable number of arguments. When calling foo(1, 2, 3, 4, 5), the passed arguments are treated as a tuple (3, 4, 5) and assigned to the args parameter.