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:

  1. 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.
  2. Variable parameters will be treated as a tuple, even if no arguments are passed, it will be considered as an empty tuple.
  3. 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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds