The path to python: wupeiqi
1. Non-fixed function parameters
* Args * kwargs
1 def test (* args): 2 print (args) 3 4 test (1, 2, 3, 4, 5) 5 test (* [1, 2, 3, 4, 5]) # * args = * [1, 2, 3, 4, 5] args = tuple ([1, 2, 4, 5]) 6 l = [1, 2, 3] 7 test (* l) 8 9 def test1 (x, * args): 10 print (x) 11 print (args) 12 test1 (1, 2, 3, 4, 5, 6, 7) 13 14 # ** kwargs, convert n keyword parameters to the dictionary in the following way: 15 def test2 (** kwargs): 16 print (kwargs) 17 test2 (name = 'jiachen', age = 27) 18 d = {'name': 'jiachen', 'age': 27} 19 test2 (** d) 20 21 def test3 (x, * args, ** kwargs ): 22 print (x) 23 print (args) 24 print (kwargs) 25 test3 (1, * [2, 3, 4], ** {'name': 'jiachen ', 'age': 27 })View Code
2. Global and local variables
1 # global variable 2 school = 'lianhedaxue '3 4 def test (name ): 5 # force modify the global variable 6 global school 7 school = 'hahaha' 8 print ('before change', name, school) 9 name = 'jack' # This function is the scope of this variable 10 print ('after change', name) 11 12 name = 'Tom '13 test (name) 14 print (name) 15 print (school)View Code
3. recursive functions
Recursive Function. A function calls itself internally.
There must be a clear termination condition
Each time you enter a deeper layer of recursion, the problem scale should be reduced compared to the previous recursion.
Inefficient, too many recursive layers lead to Stack Overflow
1 def calc(n):2 print (n)3 if int(n/2) > 0:4 return calc(int(n/2))5 print ("->",n)6 calc(10)View Code
4. High-Order Functions
A variable can point to a function. If a function parameter can receive a variable, a function can receive another function as a parameter. This function becomes a high-order function.
1 def add(x,y,f):2 return f(x) + f(y)3 4 res = add (-1,2,abs)5 print (res)
View Code