Python's functions and methods, defined by Def:
Features of the function:
- Reduce duplicate code
- To make the program extensible
- Make programs easier to maintain
The difference between a function and a method: The function has a return value, the method does not
Syntax Definitions:
Def sayhi (): #函数名 print ("Hello, I ' m nobody!") Sayhi () #调用函数
can take parameters
#下面这段代码a, b = 5,8c = A**bprint (c) #改成用函数写def calc (x, y): res = x**y return res #返回函数执行结果 c = Calc (b) # result assigned to c variable Print (c)
Note: The function parameter description, the parameter in the definition function is called the formal parameter, the parameter in the calling function is called the argument.
def test (x, y): print x print yx=1y=2test (y=y, x=x) >>1>>2
The argument to the same number in the formal parameter, under normal circumstances, to the function parameters to order, do not want to order the key parameters can be used, just specify the parameter name, But remember a requirement is that the key parameters must be placed after the position parameter.
See details: http://www.cnblogs.com/alex3714/articles/5740985.html
Non-fixed parameters
If your function is not sure how many parameters the user wants to pass in the definition, you can use the non-fixed parameter
def stu_register (Name,age,*args): # *args will turn multiple incoming parameters into a tuple form print (Name,age,args) stu_register ("Alex") #输出 #alex () #后面这个 () is args, just because there is no value, so the empty Stu_register ("Jack", "+", "cn", "Python") #输出 # jack (' cn ', ' Python ')
can also have a **kwargs
def stu_register (Name,age,*args,**kwargs): # *kwargs will turn multiple incoming parameters into a dict form print (Name,age,args,kwargs) stu_ Register ("Alex", "#alex") #输出 () {} #后面这个 {} is Kwargs, just because there is no value, so the empty Stu_register ("Jack", "+", "CN", "Python", sex= "Male", Province= "Shandong") #输出 # Jack (' CN ', ' Python ') {' Province ': ' Shandong ', ' sex ': ' Male '}
Parameter groups include: *args (change the multiple-pass positional parameter into a tuple form), **kwargs (will change the multiple-pass keyword parameter into a dictionary form)
Note: The default parameter is written to the front of the **kwargs parameter group, and the argument passed to **kwargs must be a keyword argument.
def test (x,*y): print x print ytest (2,3,4) >>2>> (3, 4)
def test (x,f=18,**y): print x print F print ytest (2,z=3,m=4) >>2>>18>>{' Z ': 3, ' m ': 4}
Note: The function definition module is written to the front of the calling function.
Python basic functions, methods