Detailed Explanation of python on Multivalued Parameters

  • 2021-11-14 06:21:30
  • OfStack

Description

1. The number of parameters that need 1 function to handle is uncertain, so multivalued parameters can be used.

2. python has two multivalued parameters, and adding 1 * before the parameter name can receive tuples. Adding two * before the parameter name can receive the dictionary.

Instances


def demo(num, *args, **kwargs):
 
    print(num)
    print(args)
    print(kwargs)
 
 
demo(1, 2, 3, 4, 5, name=" Xiao Ming ", age=18, gender=True)

Expansion of knowledge points:

Multivalued parameter

Defining a function that supports multiple parameters may sometimes require that the number of parameters that a function can handle is uncertain. At this time, multi-valued parameters can be used.
There are two kinds of multivalued parameters in python: one can be received tuple is added before the parameter name; Add two acceptable dictionaries before the parameter name; 1 When naming multivalued parameters. Usually use the following two names:

args: Stores tuple parameters; There is one in front; * kwargs holds dictionary parameters, with two in front;

Args is the abbreviation of variable arguments, which has the meaning of variable; Kw is required by keywad, and kwargs can remember key-value pair parameters;


  def demo(num,*args,**kwargs):
    print(num)
    print(args)
    print(kwargs)


demo(1,2,3,4,5,name=" Xiao Ming ",gender = " Male ")

Running result

1 (2, 3, 4, 5) {'name': 'Xiaoming', 'gender': 'Male'}

Multivalued Parameter Case-Calculating the Sum Requirements of Any Multiple Numbers:

1. Define a function sum_numbers that can accept any number of integers

2. Functional requirements: Accumulate all the numbers passed and return the accumulated results.

Above is the python on the multivalued parameter example detailed explanation of the detailed content, more about python multivalued parameter is what information please pay attention to this site other related articles!


Related articles: