A bunch of prepared codes that can be called when needed
Disadvantages represented by repeated code: redundancy, poor maintainability
So, to pack multiple lines of code into one whole: the function
In Python, use the keyword def to declare a function
# def 函数名():# 函数要执行的操作
After the function is defined, it will not be executed automatically
Need to use the function name (parameter) to call
A function name is also an identifier
Composed of numbers, letters, and underscores, cannot start with a number, and is strictly case-sensitive; keywords cannot be used
Comply with the naming convention and use an underscore to connect; as the name implies: the logic executed by the function should preferably be consistent with the name of the function
function parameters
When a function is declared, the parameters in parentheses are called formal parameters, or formal parameters for short.
The value of the formal parameter is indeterminate, it is only used as a placeholder
When calling a function, you can pass formal parameters
The parameters passed in when the function is called are the real data involved in the operation, which we call actual parameters
When the function is called, the actual parameters will be passed to the formal parameters in one-to-one correspondence.
You can also specify the variable name and pass the actual parameter to the formal parameter
function return value
The return value is the execution result of the function, but not all functions must have a return value
defadd(a,b):
c = a+b # 变量C在外部是不可见的,只能在函数内部使用return c # return 表示一个函数的执行结果
result = add(1,2)print(result **4)
If a function does not return a value, it will return None
Documentation for the function
Use a pair of three quotation marks, in the function body, to indicate the description of the function
When writing a function, add: int after the formal parameter to specify the type of the actual parameter you want to pass in
defadd(a:int,b:str):# 希望a的类型是int,b的类型是strpass
function call function
In function 2, function 1 can be called directly. When function 2 is called, function 1 will be called according to the position of function 1 in the code of function 2. The demonstration is as follows:
deffunction_1():print('函数1开始了')print('函数1结束了')deffunction_2():print('函数2开始了')print('开始调用函数1')
function_1()print('函数1调用结束')print('函数2结束了')
function_2()# 函数2开始了# 开始调用函数1# 函数1开始了# 函数1结束了# 函数1调用结束# 函数2结束了# 求m阶乘的和deffac(n):
x =1for i inrange(1,n+1):
x *= i
return x
defsum(m):
x =0for i inrange(1,m+1):
x += fac(i)return x
print(sum(5))
Global and local variables
Python can use functions to separate scopes
Variables defined outside the function are global variables and can be accessed throughout the py file
The variable defined inside the function is a local variable, which is a local function and can only be used inside the function
The built-in function globals() locals() can print the global variables and local variables in the function
a =100# a是全局变量
word ='hello'deftest():
b =80# b是局部变量
a =10print(a)# 如果在函数内部声明了一个与外部全局变量相同名称的变量,会新建一个函数内部的局部变量# 而不是修改外部的全局变量# 如果需要修改全局变量,可以使用global关键字global word
word ='thank'print(word)print('locals = {},globals = {}'.format(locals(),globals()))# ocals = {'b': 80, 'a': 10},globals = {'__name__': '__main_........ 全局变量非常多
test()# 10print(a)# 100print(word)# thank
Function multiple return values
return indicates the end of a function
Under normal circumstances, a function will only execute at most one return statement
In special cases (finally statement), the next function may execute multiple return statements
deftest(a,b):
x = a // b
y = a % b
# return x # return y# 以上代码只会执行一个return# return {'x':x,'y':y} # 以字典的形式返回# return [x,y] # 以列表的形式返回# return (x,y) # 以元组的方式返回return x,y # 返回的本质实际上就是返回一个元组print(test(12,5))# (2, 2)
Use of default parameters
The parameters of some functions, if you pass parameters, use the passed parameters, if you do not pass parameters, use the default value
How to set the default value of a formal parameter: When defining a function, directly give a value to the formal parameter at the formal parameter that needs a default value
If no parameter is passed, the default value will be used. If the parameter is passed, the passed parameter will be used, as follows
In some programming languages, function duplication is allowed, but function duplication is not allowed in Python
If the function has the same name, the latter function will overwrite the previous one
In Python, a function name can also be understood as a variable name
Therefore, when defining a function, do not have the same name as the built-in function
function recursion
Simply put, recursion means that the function itself calls itself
The most important thing about recursion is to find the exit (stop condition)
# 使用函数递归求1-n的和
x =0defget_sum(n):global x
x += n
n -=1if n >=1:
get_sum(n)return x
print(get_sum(100))# 5050# 递归方法2defget_sum2(n):if n ==0:return n
return n + get_sum2(n-1)print(get_sum2(100))# 5050# 使用函数递归求n!defget_num(n):if n ==0:return1return n * get_num(n-1)print(get_num(0))# 1# 斐波那契数列的第N个数字defget_fi(n):if n ==2or n ==1:return1return get_fi(n-2)+ get_fi(n-1)print(get_fi(8))# 21
anonymous function
defadd(a,b):return a+b
x = add(1,2)# 函数名(实参)作用是调用函数,获取到行数的执行结果并赋值给变量 x
fn = add # 相当于给函数add起了一个别名叫fn
Using the keyword lambda can be used to define a function
Anonymous function, used to express a simple function
How to call an anonymous function:
The first: define a name for him (rarely used like this)
The second: pass this function as a parameter to another function to use