Python function variable parameters

Python functions also receive a type of parameter called a variable parameter, which means any number of parameters. Variable parameters are usually represented by *args.

def func(*args):
    print('args length = {}, args = {}'.format(len(args), args))

func('a') # ==> args length = 1, args = ('a',)
func('a', 'b') # ==> args length = 2, args = ('a', 'b')
func('a', 'b', 'c') # ==> args length = 3, args = ('a', 'b', 'c')

Note that in use, Python will define a variable parameter as a tuple, so in the function, the variable parameter can be used as a tuple, for example, the corresponding element can be retrieved through the position index.
The length of a variable parameter may be 0. When the length is 0, a division by 0 error will occur. Therefore, the logic of protection needs to be added

Tuple has certain limitations in its use. For example, sometimes if you want to find a parameter at a specific location, you can only find it by subscript. If the order changes, the subscript will become invalid, and the function logic must be modified and implemented.

Python treats variable keyword parameters as a dict; for variable keyword parameters, it is generally represented by **kwargs.
For example, if you want to print the information of a classmate, you can do it like this:

def info(**kwargs):
    print('name: {}, gender: {}, age: {}'.format(kwargs.get('name'), kwargs.get('gender'), kwargs.get('age')))

info(name = 'Alice', gender = 'girl', age = 16)

A function that accepts three lists of keyword parameters names, gender, and age, which contain the name, gender, and age of classmates. Please print out each classmate’s name, gender, and age.

def info(**kwargs):
    names = kwargs['names']
    gender_list = kwargs['gender']
    age_list = kwargs['age']
    index = 0
    for name in names:
        gender = gender_list[index]
        age = age_list[index]
        print('name: {}, gender: {}, age: {}'.format(name, gender, age))
        index += 1

info(names = ['Alice', 'Bob', 'Candy'], gender = ['girl', 'boy', 'girl'], age = [16, 17, 15])

Guess you like

Origin blog.csdn.net/angelsweet/article/details/114639215