Python learning Notes (functions)

Source: Internet
Author: User

#1#parameter contains only required parametersdeffunc (x, y): y.append (×)Print("%s"%y) func (1,[])#>>[1]Func (2,[])#>>[2]#2#parameter contains required and optional parameters, parameters with default values are optional#if the parameter default value is a Mutable object, the default parameter retains the modification of each function calldefFunc (x,y=[]): Y.append (x)Print("%s"%y) func (1)#>>[1]Func (2)#>>[1, 2]#to prevent this from happening, the default value is changed to None and the check code is added to the function bodydefFunc (x,y=None):ifY isnone:y=[] y.append (x)Print("%s"%y) func (1)#>>[1]Func (2)#>>[2]#3#function parameter invocation, there are two methods, one is to use positional parameters, one is to use the keyword parameterdeffoo (w,x,y,z):PassFoo (1,2,3,4) foo (1,2,Z=4,Y=3)#the order of parameters is not important when using keyword parameters#4#variable-length parameter list, using * and * * When defining functions#with *, all remaining parameters are placed as tuples in the args variable, and when other functions are called within a function, the args tuple is re-converted to the argument list and passed to the called function by using *argsdefFoo1 (x,*args):Print("foo1:p1=%s,p2=%s"%(X,args))defFoo (w,x,*args):Print("foo:p1=%s,p2=%s,p3=%s"%(W,x,args)) foo1 (x,*args) foo (1,2,3,4,5,6)#>>foo:p1=1,p2=2,p3= (3, 4, 5, 6)#>>foo1:p1=2,p2= (3, 4, 5, 6)#Use * * To put all remaining keyword arguments as dictionaries into the Kwargs variabledefFoo (w,x,**Kwargs):Print("foo:p1=%s,p2=%s,p3=%s"%(W,x,kwargs)) foo (1,x=2,y=3,z=4)#>>foo:p1=1,p2=2,p3={' y ': 3, ' Z ': 4}#use both * and * *defFoo (w,*args,**Kwargs):Print("foo:p1=%s,p2=%s,p3=%s"%(W,args,kwargs)) foo (1,2,3,y=4,z=5)#>>foo:p1=1,p2= (2, 3), p3={' y ': 4, ' Z ': 5}

Python learning Notes (functions)

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.