Python Learning note Three

Source: Internet
Author: User

Reference Tutorial: Liao Xuefeng official website https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000

Definition of a function

Defining a function in Python requires the use of a DEF statement, which in turn determines the function name, parameters, and function body contents:

# a function to find the absolute value def my_abs (x):     if x>0:        return  x    Else:        return -X

If there is no return statement in the function body, none is returned. Return none can be shortened to return.

If you want to define a function that does nothing (an empty function), you can use the PASS statement, or the pass can be used in the IF statement:

def NOP ():     Pass def nopx (n):     if n>0:        pass    else:        return

* Functions that return multiple values

# gives the length and width of the rectangle, the output area and perimeter def Sqcount (l,w):    area =l*w    length=2* (l +w    )return area, Length

You can add some statements to see what this returns:

X,y=sqcount (3,4)print(x, y)# here output 12,14r=sqcount (5,6)  Print(r)# output here (30,22)

As can be seen from the above code, although it appears that the function returns more than one value, in essence, it returns a value, but the type of the value is a tuple!

Second, the parameters of the function

(i) Position parameters

The parameters in the previously defined My_abs () and Sqcount () are positional parameters, which are parameters that must be passed when the function is called, and are passed to the corresponding parameters in the order they were defined.

(ii) Default parameters

In some cases, some parameters in the parameters in most cases are a certain value, this time can be defined when the function is set down, at the time of invocation if the parameter value and definition of the corresponding parameter value is the same, you can not write, at different times you need to write down the specific value of the surrogate function.

#By default, nationality is set to ChinadefPerson_info (name,age,country=' China'):    Print('name=', Name,'age=', Age,'country=', Country)returnTrue#Zhanghua nationality may not be passed into the nationality parameterPerson_info ('Zhanghua', 26)#Tom Nationality is United States, you need to setPerson_info ('Tom', 29,'America')

It is important to note that when there are multiple default parameters, the default parameters can be supplied sequentially when called, or the parameter names can be added to specify the correspondence between the default parameters.

defEnroll (name, Gender, age=6, city='Beijing'):    Print('Name:', name)Print('Gender:', gender)Print('Age :', age)Print('City :', city)#The Age information parameter is passed in the third order by definition#so you can not add parameter namesEnroll'Bob','M', 7)#The age here uses the default value when defined, so do not write#but the city needs to be set up, and the positional relationship is inconsistent with the definition.#so we need to write ' city= '.Enroll'Adam','M', city='Tianjin')

You must also be aware of the default parameters, such as:

# defines when the default parameter L is used, pointing to an empty list def Testa (l=[]):    l.append ('END')    return  Lprint (testa ())# output [' END ']print( Testa ())# output [' End ', ' End ']

Two times the same call, why the output is not the same? at the time of definition, the value of the default parameter L is computed, that is, pointing to [],l is also a variable, and if the content of L is changed (pointing) at each invocation, the default parameter naturally changes. So: the default parameter must point to the immutable object!

The above code can be modified with none:

def Testa (l=None):    if is none:        L=[]    l.append ( ' END ' )    return L

(c) Variable parameters

Variable parameter refers to the number of parameters passed in can be changed, any one. The case for designing this parameter is that when the function is defined, it is not known how many parameters are called, such as: list, tuple, and so on. It is possible to set the parameters as a whole as a list or a tuple, and Python does not need to specify the type for the variable, so the simple procedure is as follows:

def Calc (numbers):    sum=0    for in  numbers:        sum=sum+i     return sum

However, the method described above must pass data of type iteration type, such as list, such as passing other types such as numeric type typeerror: ' int ' object is not iterable error.

# normal operation, output 6x=[1,2,3]print(calc (x))# Error: Parameter non-iterative type y= 2Print(Calc (y))

For functions defined above, you can also pass in values directly:

Print (Calc ([+])) Print (Calc ((2,3,5,7,11))

This is not a convenient time to use, because it needs to be assembled into a list or tuple before it can be used, if you want to invoke the method that can be used to use variable parameters as follows:

Cal (1,3,5,7,9,11)

You can change a parameter to a variable parameter when you define it: add ' * ' before the argument:

def Calc (*numbers):    sum=0    for in  numbers:        sum =sum+i    return sum

This makes it possible to call directly through Cal (1,3,5,7,9,11), and if it is a list or tuple, it can be easily called by adding ' * ' to the list or tuple name before the parameter is passed:

Print (Calc (1,3,5,7,9,11)) x=[1,2,3]print(Calc (*x)) y= (2,3,5,7)Print (Calc (*y))

Regardless of the type of argument before it is passed, whether it is a direct numeric pass or a list or tuple, the inside of the function is to assemble the mutable parameters into a tuple after the function has passed in.

(iv) Keyword parameters

The keyword parameter allows you to pass in any parameter with a parameter name that is automatically assembled into a dictionary (dict) inside the function:

# The first two parameters are positional parameters, which represent name and age information # The third parameter defines the optional keyword parameter, which allows the caller to provide additional information def person (name,age,**kw):    Print(name,'-', age,  '-', kw)

#调用者可以只提供必选的位置参数信息
#输出: LiNa-32-{}
Person (' LiNa ', 32)
#调用者提供一个信息: Country
#输出: Jenny-35-{' Country ': ' British '}
Person (' Jenny ', 35,country= ' British ')
#调用者提供两个信息: Country and gender
#输出: Tom-39-{' Gender ': ' M ', ' Country ': ' Holland '}
Person (' Tom ', 39,gender= ' M ', country= "Holland")

If you already have a dict, you can simply add ' * * ' to the dictionary name and pass it as a keyword argument:

#output: LiNa-32-{' coutry ': ' China ', ' gender ': ' F ', ' food ': ' Reganmian '}lina_info={'coutry':' China','Gender':'F',' Food':'Reganmian'}person ('LiNa', 32,**lina_info)

(v) named keyword parameters

In the keyword argument, the caller can set the parameter name passed to the keyword parameters, such as the above Country,gender and food are optional and can set their own, if you want to limit the name of the keyword parameter, you need to use the named keyword parameter:

#keyword parameter only accepts name City and jobdefPerson (name,age,*, city,job):Print(Name,'-', Age,'-', City,'-', Job)#there will be an error, because the job parameter is not passedPerson'Mengfei', 50,city='Nanjing')    #normal operation, output: Wanggang-60-beijing-actorPerson'Wanggang', 60,city='Beijing', job='Actor')

A named keyword parameter can have a default value, so the argument can be not explicitly specified at the time of invocation:

defPerson (name,age,*,city='Beijing', Job):Print(Name,'-', Age,'-', City,'-', Job)#Output: Wanggang-60-beijing-actorPerson'Wanggang', 60,job='Actor')

When there are mutable parameters in the function argument list, the named keyword argument followed is no longer required to have a special symbol ' * ':

def person (name, age, *args, City, job):    Print(name, age, args, city, job)
#A, B is required for positional parameters#c is an optional default parameter#args is an optional variable parameter#kw is an optional keyword parameterdefF1 (a,b,c=0,*args,**kw):Print('a='A'b='B'c='. cn'args=', args,'kw=', kw)#when a function is called, the interpreter is automatically passed by parameter position and parameter name#only two positional parameters, default c is 0#output: a= 1 b= 2 c= 0 args= () kw= {}F1 ()#positional parameters plus custom default parameter values#output: a= 1 b= 2 c= 3 args= () kw= {}F1 (1,2,c=3)#positional parameters + default parameters + variable parameters#If you have a keyword argument, you need to add a name#output: a= 1 b= 2 c= 3 args= (' A ', ' B ') kw= {}F1 (A'a','b')#output: a= 1 b= 2 c= 3 args= (' A ', ' B ') kw= {' x ': £ ©F1 (A'a','b', x=99)

Python Learning note Three

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.