Python Function Parameters Learning notes

Source: Internet
Author: User

When learning the Python function parameters, it is found that the Python function has a variety of parameter forms, it is necessary to record, understand the difference between them and use, mainly refer to Liaoche's basic Python tutorial: Https://www.liaoxuefeng.com/wiki /0014316089557264a6b348958f449949df42a6d3a2e542c000/001431752945034eb82ac80a3e64b9bb4929b16eeed1eb9000

1. Position parameters

For example: Beg xn

def Power (x, N):     = 1 while     n > 0:        = n-1        *= x    print(s) Power (/ C12>3, 4)  #  bayiPower (4, 3)  #  

As you can see, when you call a function, the values that you pass in are assigned x, N in order

How many values must be passed in when the function is called, or an error will be

Power (3)
Typeerror:power () Missing 1 required positional argument: ' n '

Note that the power () function lacks a required positional parameter ' n ', as can be seen from here, where the positional parameter is passed in sequence

2. Default parameters

Default parameter: Specify the value of the parameter directly when the function is defined

def Power (x, n=2):    = 1     while n > 0:        = n-1        *= X
    Print(s)

In this case, the power () function is given the default parameter n=2, in which case we just need to call the power () function to get the square of a number x, and when the function is called, it can only pass in the value of X

Power (3)  # 9

If we want to call the power () function for x 4, 5, 6 ... the second way, you can pass the value to the default parameter.

Power (3, 4)  # 81

As can be seen, the default parameter simplifies the invocation of a function, which is useful when certain parameters of a function do not need to be changed in most cases. For example: Print a class student's name (name), age, and hometown information

Generally speaking, a class of students are the same place of origin, if each call to pass the city parameter, will make the call complex, this time, you can set the city parameter as the default parameter

def Student (name, age, city='Chongqing'):    print('  Name:', name '    print('age:' ) , age)     Print (' city:', City) student ('fzp', 7)

Input Result:

7city:chongqing

There are a few things to note when setting default parameters:

1) The required parameter must be before the default parameter is

2) When the function has more than one parameter, put the change in the front, the change of the small parameter is placed behind. Parameters with small variations can be used as default parameters

Benefit: Reduce the difficulty of calling the function

3) When there are multiple default parameters, you can assign them sequentially, or you can assign them directly using parameter names

For the 3rd:

defStudent (name, age, city='Chongqing', gender=7):    Print('Name:', name)Print('Age :', age)Print('City :', city)Print('Gender:', gender) student ('frm', 7,'Chengdu', 6) #依顺序赋值student ('Fzp', 7, gender=7) #给gender参数赋值为7, in which case the city parameter is still the default ' Chongqing '

A typical problem with default parameters is to be aware of when you use them:

def func (lis=[]):    lis.append (1)    print(LIS) func () #[1] Func () #[1, 1]

"This is because when the interpreter executes the function definition , the default parameter value, Lis, is also computed, that is [] , because the default parameter, Lis is also a variable that points to [] the object, each time the function is called, and if the content is changed lis , the next time , the contents of the default parameters are changed, and are no longer defined by the function [] "reference to Liao's explanation

My understanding of the problem is that when the append () method is executed, it just adds a new element to the LIS and does not change its address

lis = []print(LIS) #2293538950856lis. Append (1)print(LIS) # 2293538950856

To solve this problem, you can use the None invariant object to achieve:

def func (lis=None):    if is None:        = []    lis.append ( 1)    print(LIS) func () #[1]func ( ) #[1]

"Why design str , None such an immutable object?" Since immutable objects are created, the data inside the object cannot be modified, which reduces the error caused by modifying the data. In addition, because the object is not changed, the simultaneous reading of objects in a multitasking environment does not require locking, while reading a little bit of a problem. when we write a program, if we can design a constant object, then try to design as immutable object "

1. Immutable objects: String (String), (numeric number), tuple (tuple), collection (set)
2. Variable object: Word typical (dictionary), list type

3. Variable parameters

Variable parameters: variable number of parameters passed in

Example: Given a set of numbers a,b,c ..., please calculate a2 + b2 + C2 + ..., to define this function, we must determine the input parameters. As the number of arguments is uncertain, we first think that we can put a,b,c ... Passed in as a list or tuple, so that the function can be defined as follows:

def result (Numbers):     = 0    for in  numbers:        + = n *    nreturn sum

When calling this method, you need to assemble a list or tuple first

Print (Result ([1, 2, 3]))  #14print(Result ((1, 2, 3, 4)))  #30

If you use variable parameters, you can directly pass in the parameters, do not need to first assemble the parameters, variable parameters with * identification

def result (*numbers):    = 0    for in  numbers:        + = n * N     return sum Print (Result (1, 2, 3, 4))  #30  = (1, 2, 3)print(Result (*tup)) #14  
4. Keyword parameters

Keyword parameter: Allows you to pass in any of the parameters (including 0) with parameter names, which are automatically assembled into a dict within the function, and the keyword parameters are identified with * *

def Student (name, age, ** Kwargs)    :print('name:') Age :"other:', Kwargs)

It can be seen that the student function can accept the keyword parameter Kwargs in addition to the required parameter name and age, and when calling the function, it is possible to pass only the required parameters

Student ('fzp', 24)

The output is:

Name:fzp age:24 Other: {}

As can be seen from the results, the keyword parameter is automatically assembled inside the function as a dict, where the keyword parameter is not passed, and all is an empty dictionary {}

Key parameter values can be used in the form of ' key ' = ' value '

Student ('fzp', +, address='Chongqing', sex='  man')

The output is:

Name:fzp age:24 Other: {'address'Chongqing'  'sex' ' Man'}

Of course, the keyword parameter value can be passed directly to a dict

DIC = {'address'Chongqing'sex'  'man'}student ('fzp', ' **dic ')

The output is:

Name:fzp age:24 Other: {'address'Chongqing'  Sex'man'}

Attention:

1, Kwargs obtained dict is only a copy of DIC, changes to Kwargs will not affect the outside of the function of DIC

2, directly into a dict, to add the * * before, otherwise the entire dict will be recognized as a positional parameter, as follows:

Student ('fzp', +, DIC)  
Typeerror:student () takes 2 positional arguments but 3 were given
Named keyword parameters

For the keyword argument, the caller of the function can pass in any unrestricted keyword argument. But, again, we might want to define the name of the keyword argument, and then we need to use the named keyword argument

Still take the student function as an example, if you want to accept only address and sex as arguments, you can define the following:

def Student (name, age, *, Address, sex):    print('name:' ' Age : ' ' Address: ' ' Sex: ', Sex)

Unlike keyword Parameters **kwargs , a named keyword parameter requires a special delimiter * , and * subsequent arguments are treated as named keyword arguments

The method is called as follows:

Student ('fzp', ' address= ','Chongqing', sex='  man')

Input result: Name:fzp age:23 address:chongqing Sex:man

Note: The named keyword parameter must give the value, as for why there is a must pass the positional parameters, but also must pass the named keyword parameters, I think there are two reasons:

1, the name of the keyword parameter by specifying the name of the parameter, you can clarify the meaning of the current parameter

2, the named keyword parameter does not have to pass the value in order as the positional parameter, the simultaneous value is more flexible

Of course, the named keyword argument can have a default value, so that when called, it is not necessary to pass it a value:

def Student (name, age, *, address, sex='man'):    print(  'name:' age:'address:'  'sex:', Sex)

Call this function:

Student ('fzp', address= 'Chongqing')

The output is: Name:fzp age:23 address:chongqing Sex:man
5. Parameter combination

To define a function in Python, you can use the required parameters, default parameters, variable parameters, keyword arguments, and named keyword parameters, which can all be combined using 5 parameters. Note, however, that the order of the parameter definitions must be: required, default, variable, named keyword, and keyword parameters

Example:

def func (A, B, c=3, *args, address, ** Kwargs)    :print('A:' ) ' B: ' ' C: ' ' args: ' ' Address: ' ' Kwargs: ', Kwargs)

Call this function:

Func (1, 2, 3, 4, 5, address='cq', d='char', e='  Dict')

Input result: a:1 b:2 c:3 args: (4, 5) Address:cq Kwargs: {' d ': ' char ', ' e ': ' Dict '}

The above functions can also be called through a tuple and dict:

Tup = (1, 2, 3, 4, 5= {'address''cq'Ax  'sg'}func (*tup, **kw)

The output is:

A:1 b:2 c:3 args: (4, 5) Address:cq Kwargs: {'ax''sg' }

So, for any function, it can be called in a similar func(*args, **kw) way, regardless of how its arguments are defined

Python Function Parameters Learning notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.