I. Definition of functions
def function name (argument list): function body return statement
Return statement does not write or no object behind it is return None
Two. Parameters of the function
No parameters
Def func1 (): print ("No parameters")
A parameter
Def func1 (a): return a
Multiple parameters
def func1 (a,b,c): return A+b+c
Required Parameters
Parameters must be passed in the correct order and quantity
def func1 (name,age,job): print ("name:%s age:%d job:%s"% (name,age,job)) func1 ("Sfencs", "IT")
Keyword parameters
def func1 (name,age,job): print ("name:%s age:%d job:%s"% (name,age,job)) func1 (age=20,name= "Sfencs", job= "IT")
Default parameters
The default parameter must be placed after the required parameter
def func1 (name,age,job= "IT"): print ("name:%s age:%d job:%s"% (name,age,job)) func1 ("Sfencs") func1 ("Alan", 25, "Teacher")
Indefinite length parameter
Parameter with an asterisk *
def func1 (*args): print (args) func1 ("Sfencs") # (1, 2, 3, ' Sfencs ') saved as tuples
Parameter with two asterisk * *
def func1 (**args): print (args) func1 (age=20,name= "Sfencs", job= "it") #{' age ': ' Name ': ' Sfencs ', ' job ': ' It '} Save in dictionary form
When defining parameters for a function, define the parameter in the order of the required parameter, default parameter, indeterminate length parameter with an asterisk, indefinite length parameter with two asterisks
Three. Parameter passing
Immutable types
Def func1 (a): a=5b=10func1 (b) print (b) #输出为10
Variable type
def func1 (list1): list1.append ("Sfencs") list2=[1,2,3]func1 (list2) print (List2) #[1, 2, 3, ' Sfencs ']list2 will change
Four. Variable scope
L (local) local scope
In functions outside of the E (enclosing) closure function
G (Global) scope
B (built-in) built-in scopes
Search in order of l-->e-->g-->b
Internal scope modifies external scope variables
Global
Count=20def function (): global count# No such sentence will be error print (count) #20 count=5 Print (count) #5function () Print (count) #5
Nonlocal
modifying nested scopes
Def function1 (): count=20 def function2 (): nonlocal count count=5 Print (count) #5 Function2 () print (count) #r此时输出为5, Output is 20function1 () if nonlocal count is not added
Five. Recursive functions
#斐波那契数列为0, 1,1,2,3,5,8,13,21,34.......def Fibon (n): if n<=2: return n-1 return Fibon (n-1) +fibon (n-2) Print (Fibon (7)) #输出数列中第七个数, 8
Python Basic Learning----function