- Function creation and call
- What is a function?
A function is code that performs a specific task to accomplish a specific function.
- What is a function?
- Why do I need a function
Reuse code, hide implementation details, improve maintainability, improve readability, and facilitate debugging. - def function name ([input parameter]):
Function body
[return xxx]
def calc(a,b): c=a+b return c result=calc(10,20) print(result)#30
- Parameter passing of function call
def calc(a,b):#a. B is called formal parameter, which is called formal parameter for short. The position of formal parameter is at the definition of function c=a+b return c result=calc(10,20)#10 and 20 are called the value of the actual parameter, which is called the actual parameter for short. The position of the actual parameter is where the function is called print(result)#30 res=calc(b=10,a=20)#=The name of the variable on the left is called a keyword parameter print(res)
- Memory analysis of function parameter transfer
def fun(arg1,arg2): print('arg1=',arg1)#Step two print('arg2',arg2) arg1=100 arg2.append(10) print('arg1=',arg1)#Step 3 print('arg2=',arg2) n1=11 n2=[22,33,44] print('n1=',n1)#First step print('n2=',n2) fun(n1,n2) #Pass the position to the parameter. arg1 and arg2 are the formal parameters at the function definition, and n1 and n2 are the actual parameters for the function call. In summary, the name of the actual parameter and the name of the formal parameter can be different. print('n1=',n1)#Step 4 print('n2=',n2)
In the process of function call, parameters are passed.
If it is an immutable object, the modification in the function body will not affect the value of the argument.
Changing arg1 to 100 will not affect the value of n1.
If it is an immutable object, the modification in the function body will not affect the value of the argument.
The modification of arg2, append (10), will affect the value of n2.
- Return value of function
- When the function returns multiple values, the result is a tuple
def fun(num): odd=[]#Save odd number even=[]#Save even number for i in num: if i%2: odd.append(i) else: even.append(i) return odd,even #Function call lst=[10,29,34,23,44,53,55] print(fun(lst))
Return value of function
(1) If the function has no return value [after the function is executed, there is no need to provide data to the caller], return can be left blank.
(2) The return type of the function. If it is 1, it returns the type directly.
(3) The return value of the function. If it is multiple, the returned result is tuple.
def fun1(): print('hello') #return fun1() def fun2(): return 'hello' res=fun2() print(res) def fun3(): return 'hello','world' print(fun3()) #Whether a function needs to return a value when it is defined depends on the situation
- Parameter definition of function
- Function definition default value parameter: when defining a function, set the default value for the formal parameter. Only when it is inconsistent with the default value, the actual parameter needs to be passed.
def fun(a,b=10):#b is called the default value parameter print(a,b) #Function call fun(100) #100 10 fun(20,30) #20 30
- Variable number parameter
1 'position parameters with variable number
When defining a function, you may not be able to determine the number of positional arguments passed in advance. Use variable positional parameters.
Use * to define a variable number of location parameters.
The result is a tuple.
def fun(*args): print(args) print(args[0]) fun(10) fun(10,30) fun(30,405,50)
2 'variable number of keyword parameters
When defining a function, you may not be able to determine the number of keyword arguments passed in advance. Variable keyword parameters are used.
Use * * to define a variable number of keyword parameters.
The result is a dictionary.
def fun1(**args): print(args) fun1(a=10) fun1(a=20,b=30,c=40)
def fun2(*args,*a): pass #For the above code, the program will report an error. The number of variable location parameters can only be 1 def fun2(**args,**args): pass #For the above code, the program will report an error. The variable number of keyword parameters can only be 1 def fun3(*arg1,**arg2): pass #In the process of defining a function, there are both a variable number of location parameters and a variable number of keyword parameters. It is required that the variable number of location parameters be placed before the variable number of keyword parameters
def fun(a,b,c):#a. B and C are at the definition of the function, so they are formal parameters print('a=',a) print('b=',b) print('c=',c) #function call fun(10,20,30) lst=[11,22,33] fun(*lst)#* must be added, otherwise an error will be reported. When calling the function, convert each element in the list into a position parameter fun(a=100,b=300,b=200)#Keyword argument dic={'a':111,'b':222,'c':333} fun(**dic)#When a function is called, each element in the dictionary is converted into a keyword parameter
def fun(a,b=10):#b is at the definition of the function, so b is a formal parameter and assigned value, so b is the default formal parameter print('a=',a) print('b=',b) def fun2(*args):#Variable number of position parameters print(args) def fun3(**args2):#Variable number of keyword parameters print(args2) fun2(10,20,30,40) fun3(a=11,b=22,c=33,d=44,e=55) def fun4(a,b,*,c,d):#Parameters after * are passed by keyword parameters during function call print('a=',a) print('b=',b) print('c=',c) print('d=',d) #fun4(10,20,30,40) #Position argument passing fun4(a=10,b=20,c=30,d=40)#Keyword argument passing fun4(10,20,c=30,d=40)#The first two parameters are passed by location arguments, while cd is passed by keyword arguments
- Scope of variable
- The area where the program code can access the variable
- According to the effective range of variables, they can be divided into local variables (defined and used in the function, which are only valid inside the function. If global declaration is used, the variables will become global variables) and global variables (variables defined outside the function can act inside and outside the function)
def fun(a,b): c=a+b#c. It is called a local variable, because C is the variable defined in the function body, a and b are the formal parameters of the function, and the scope of action is also within the function, which is equivalent to a local variable print(c) #print(c) #Because a and c are out of scope #print(a) name='yang'#The scope of name is external and internal to the function, and it is a global variable print(name)#yang def fun2(): print(name) fun2()#yang def fun3(): global age #The variables defined inside the function, local variables, and local variables are declared with global. In fact, this variable becomes a global variable age=20 print(age) fun3()#20 print(age)#20
- Recursive function
- If the function itself is called in the function body of a function, the function is called a recursive function
- Components of recursion: recursive call and termination conditions
- Every time a function is called recursively, a stack frame will be allocated in the stack memory. Each time the function is executed, the corresponding space will be released.
- Advantages of recursion: simple thinking and code; Disadvantages of recursion: it takes up too much memory and is inefficient
- Calculate factorials using recursion
def fac(n): if n==1: return 1 else: return n*fac(n-1) print(fac(6))#720
- Fibonacci sequence
def fib(n): if n==1: return 1 else n==2: return 1 else: return fib(n-1)+fib(n-2) #Output the 6th digit print(fib(6)) #8 #Output the first six digits for i in range(1,7): print(fib(i))