Article Directory
1. The definition and calling of functions
What is a function: A function is a piece of code that executes any specific function to complete a specific function.
Why is a function needed:
1. Reuse code
2. Hide implementation details
3. Improve maintainability
4. Improve readability and facilitate debugging
#创建与调用
def add_ab(a,b):
c=a+b
return c
result=add_ab(1,2)
print(result) #3
2. The parameter passing of the function
#创建与调用
def add_ab(a,b): #a,b 为形参,定义处
c=a+b
return c
result=add_ab(1,2) # 1,2 为实参,调用处
print(result) #3
# = 左侧的变量名称称为关键字参数
def add_ab(a,b): #a,b 为形参,定义处
c=a+b
print(a,b) #a 1
return c
result=add_ab(b=1,a=2) # 1,2 为实参,调用处
print(result) #3
#形参和实参的定义可以不相同
def fun(arg1,arg2):
print('arg1',arg1) #arg1 11
print('arg2',arg2) #arg2 [111, 222, 333]
arg1=100
arg2.append(19)
print('arg1',arg1) #arg1 100
print('arg2',arg2) #arg2 [111, 222, 333, 19]
return
n1=11
n2=[111,222,333]
fun(n1,n2)
3. The return value of the function
def fun(num):
odd=[] #奇数
even=[] #偶数
for i in num:
if i%2:
odd.append(i) #!=0
else:
even.append(i)
return odd,even
lst=[10,20,30,11]
print(fun(lst)) #([11], [10, 20, 30])
'''
函数的返回值
(1)如果没有返回值,可以省略return
(2)函数的返回值,只有1个,直接返回类型
(3)函数的返回值,如果是多个,返回的结果为元组
'''
4. The definition of function parameters
4.1 Default parameter
'''
函数的参数定义
函数定义默认值参数
函数定义时,给形参设置默认值,只有与默认值不符的时候才需要传递实参
'''
def fun(a,b=19):
print(a,b)
fun(100) #100,19
fun(20,30) #20,30
print('hello',end='\t')
print('world') #hello world
4.2 Variable positional parameters and keyword parameters
'''
函数的参数定义
个数可变的位置参数
定义函数时,无法事先确定传递的位置实参个数,使用可变的位置参数
使用*定义个数可变的位置形参
结果为一个元组
个数可变的关键字形参
定义函数时,无法事先确定传递的关键字实参个数,使用可变的关键字参数
使用**定义个数可变的关键字形参
结果为一个字典
'''
#可变的位置参数,只能有1个
def fun(*args):
print(args)
fun(10)
fun(10,39) #(10, 39)
fun(30,406,40)
#可变的关键字参数,只能有1个
def fun1(**args):
print(args)
fun1(a=10) #{'a': 10}
fun1(a=20,b=20,c=30) #{'a': 20, 'b': 20, 'c': 30}
'''
既有可变的位置参数和关键字参数,只能用以下形式,位置参数得在前
'''
def fun2(*args,**args1):
pass
5. Summary of the parameters of the function
def fun(a,b,c): #a,b,c函数的定义处,所以是形式参数
print('a=',a)
print('b=',b)
print('c=',c)
fun(10,20,30)
'''
a= 10
b= 20
c= 30
'''
lst=[11,22,33]
fun(*lst)
'''
a= 11
b= 22
c= 33
'''
fun(a=100,c=300,b=200)
'''
a= 100
b= 200
c= 300
'''
dic={
'a':111,'b':222,'c':333}
fun(**dic)
'''
a= 111
b= 222
c= 333
'''
6, the scope of variables
#变量域
def fun(a,b):
c=a+b #c是局部变量,a,b为函数的形参,相当于局部变量
print(c)
name='XCsss98' #函数内部和外部都可以使用
print(name)
def fun2():
print(name)
fun2()
def fun3():
global age #用global声明,可以变成全局变量
age=20
print(age)
fun3()
print(age)
7, recursive function
#递归函数
def fac(num):
if num==1:
return 1
else:
return num*fac(num-1)
print(fac(6)) #720