Knowledge point one: function basics
1. Function definition
def 函数名(参数):
函数体
无参函数:
def func1():
print('hello world!')
单参函数:
def func2(a):
print(a*3)
多参函数:
def func3(a,b):
print(a*b)
2. Function call
Call directly using function name
func1()
func2(23)
func3(4,5)
3. Parameters
The parameters of the function are divided into formal parameters (formal parameters) and actual parameters (actual parameters)
Formal parameters: parameters in the function definition phase. The scope is limited to the function definition position and has no meaning outside the function.
Actual parameters: parameters in the function call phase, used to pass in data for processing inside the function
How to set parameters:
1. Positional parameters
Pass parameters according to the parameter position defined by the function
The order of positions must be the same as when defined
def f(a,b,c):
print(a+b*c)
f(1,2,3)
2. Keyword parameters
Directly use keywords to pass parameters
The position order can be different from the definition
def f(a,b,c):
print(a+b*c)
f(b=2,a=1,c=3)
3. Parameter default values
If the function sets a default value, no parameters can be passed when calling.
def f(a,b,c=3):
print(a+b*c)
f(1,2,3)
f(1,2)
f(1,2,4) # 如果不传参,参数使用默认值,如果传参,使用新参数值
4. Mixing positional parameters and keyword parameters
Positional parameters come first, keyword parameters come last
def f(a,b,c):
print(a+b*c)
f(1,2,c=3) # 正确调用方式
f(c=3,1,2) # 错误调用方式
5. Variable parameters
1) # Adding * in the formal parameter will save the overflow position actual parameter in the form of a tuple when calling the function, and then assign the variable name after *
def foo(x, y, *z):
print(x, y)
print(z)
print(*z)
foo(1, 2, 3, 4, 5, 6)
2) # Disperse the actual parameters
# Sequence types can be * broken up
foo(1, *(2, 3))
foo(1, 2)
foo(*[1, 2, 3])
3) # With ** in the formal parameter: the overflow keyword actual parameter when calling the function will be saved in the form of a dictionary, and then the variable name after ** will be assigned.
def foo(x,y,**z):
print(x,y)
print(z)
# **只能接受关键字实参
4) # Actual parameters can be broken up into dictionaries and turned into keyword actual parameters for parameter passing
a = {'x':1,'y':2,'z':3}
foo(**a)
4. Return value
The return value is the processing result of a function return
After the function runs, the function itself is equal to the return value
def s(a,b):
c=a+b
return c
m=s(2,5)
print(m)
'''
1.函数内可以有多个return,但只要执行一次,整个函数就会结束运行,默认return None
2.return 的返回值无类型限制,即可以是任意数据类型、表达式
3.return 的返回值无个数限制,即可以用逗号分隔开多个任意类型的值
4.return关键字:return也可以作为函数结束的标志
'''
5. Local variables and global variables
Variables assigned inside a function are in the "local scope" of the function and are local variables.
Variables assigned outside a function are in the "global scope" of the function and belong to global variables.
A variable is either a local variable or a global variable. You cannot have your cake and eat it too.
Note: Different local scopes are independent of each other. One local scope cannot use variables in other local scopes.
1.# Variables inside the function cannot be accessed from the outside
def f():
a=12
print(a)
2.# Variables outside the function can be accessed from inside the function
a=12
def f():
b=a*2
return b
print(f())
3.# Variables outside the function cannot be modified in the function, and an error will be reported.
a=12
def f():
a = a + 1
f()
print(a)
4.# But external variables can be read inside the function
a=12
def f():
b = a + 1
print(b)
f()
print(a)
5.# Variable types can be modified inside the function
# 但是不可以重新赋值
a=[1,2,3]
def f():
a.append(4)
f()
print(a)
6.# global allows us to modify the value of global variables in a function
def f():
global a
a = a + 1
f()
print(a)
7.# nonlocal allows nested functions to modify values outside the nested function
def f():
a = 12
def ff():
nonlocal a
a += 1
print(a)
f()
Four rules of scope judgment:
1. If a variable is used in the global scope (outside all functions), it is a global variable
2. If there is a global statement for the variable in a function, it is a global variable
3. Otherwise, if the variable is assigned inside the function, it is a local variable.
4. But if the variable is not used in an assignment statement inside the function, it is a global variable
def f1():
global a
a = 12 # 全局变量a
print('我是全局变量%d' % a)
def f2():
a = 12 # 局部变量a
print('我是局部变量%d' % a)
def f3():
print('我也是全局变量%d' % a)
a = 12 # 全局变量
print('我也是全局变量%d' % a)
6. Commonly used built-in functions
# Find the absolute value
print(abs(-2))
# Find the maximum value
nums=[1,3,5,3,2,5,7,4]
print(max(nums))
# Find the minimum value
nums=[1,3,5,3,2,5,7,4]
print(min(nums))
# Sum
nums=[1,3,5,3,2,5,7,4]
print(sum(nums))
#Convert characters to encoding
print(ord('a'))
#Convert encoding to characters
print(chr(65))
# Zipper function
l1=[1,2,3,4,5]
l2=['a','b','c','d','e','f']
print(zip(l1,l2)) # 返回的是<zip object at 0x000001CED5496640>对象
print(list(zip(l1,l2))) # 转换成列表
print(dict(zip(l1,l2))) # 转换成字典
#Execute the expression in the string
print(eval('2+3'))
# Execute the statements in the string
exec('print("hello world")')
Knowledge point 2: Advanced functions
1. Anonymous functions
1.1 What is an anonymous function?
An anonymous function means that you no longer use the standard form of def statement to define a function.
Python uses lambdas to create anonymous functions. Lambda is just an expression, and the function body is much simpler than def.
The body of lambda is an expression, not a code block, and only limited logic can be encapsulated in lambda expressions.
Note: The lambda function has its own namespace and cannot access parameters outside its own parameter list or in the global namespace.
The syntax of the lambda function only contains one statement, which is as follows:
lambda 参数:表达式(返回值)
1.2 How to apply anonymous functions
Example 1: Find the sum of two numbers
Use def statement:
def func(x, y):
return x + y
Use lambda expressions:
lambda x, y: x + y
As you can see from the above code, using lambda expressions requires less code than using def statements. It's not obvious here, let's look at an example with more code.
Example 2: Find elements greater than 3 in a list.
Method 1: Implemented through procedural programming, which is also a conventional method.
list_1 = [1, 2, 3, 4, 5]
list_2 = []
for i in list_1:
if i > 3:
list_2.append(i)
print('列表中大于3的元素有: ', list_2)
Method 2: Implemented through functional programming, using filter built-in function + list comprehension to give a judgment condition:
def func_filter(x):
return x > 3
f_list = filter(func_filter, [1, 2, 3, 4, 5])
print('列表中大于3的元素有: ', [item for item in f_list])
Method 3: Using anonymous functions will make it more streamlined, just one line of code:
print('列表中大于3的元素有: ', [item for item in filter(lambda x: x > 3, [1, 2, 3, 4, 5])])
As can be seen from the above operations, lambda is generally used in functional programming, the code is concise, and it is often used in combination with functions such as filter.
1.3 Anonymous function usage scenarios
1. When the program is used once and does not need to define a function name, using anonymous functions can save the space occupied by defined variables in memory.
2. If you want to make the program more concise, you can use anonymous functions.
#Anonymous function usage rules:
1. Generally there is a line of expression, which must have a return value.
2. There can be no return.
3. It can have no parameters or one or more parameters.
1.4 Anonymous function example
Anonymous function without parameters:
t = lambda : True
t()
Anonymous function with parameters:
lambda x: x ** 3
lambda x, y, z: x + y + z
lambda x, y = 3: x * y
2. Closure function
Sometimes a function can also return a function, which is a self-defined function inside the function.
Example:
def outer(*args):
def inner():
s = 0
for n in args:
s = s + n
return s
return inner
print(f'调用外部函数的结果: {outer(1, 2, 3, 4)}')
inner = out(1, 2, 3, 4)
print(f'调用内部函数的结果: {inner()}')
In this example, the function inner is defined in the function outer, and the inner function inner can refer to the parameters and local variables of the outer function outer. When outer returns function inner, relevant parameters and variables are saved in the returned function, which is called a closure. This program structure is extremely powerful. Let’s understand it first, and we will explain it in detail later.
3. Recursive functions
3.1 What is a recursive function?
If a function calls itself internally, it is called a recursive function.
A simple definition of a recursive function is as follows:
def fun():
print('hello')
return fun()
Let’s look at a recursive example to calculate the factorial n=1×2×3×…×n, represented by the function fact(n):
def fact(n):
if n == 1:
return 1
return n * fact(n - 1)
print(f'调用递归函数执行结果为: {fact(5)}')
When calculating fact(5), you can see the calculation process according to the function definition:
===> fact(5)
===> 5 * fact(4)
===> 5 * (4 * fact(3))
===> 5 * (4 * (3 * fact(2)))
===> 5 * (4 * (3 * (2 * fact(1))))
===> 5 * (4 * (3 * (2 * 1)))
===> 5 * (4 * (3 * 2))
===> 5 * (4 * 6)
===> 5 * 24
===> 120