本文资料来源链接:
python中函数定义方法:
def test(x): #test是函数名
'the function definitions' #注释
x += 1 #代码块(可以有n行)
return x #返回结果
运行方式:
y = test(3)
print(y)
一个例子:
while True:
if cpu利用率 > 90%:
#发送邮件提醒
连接邮箱服务器
发送邮件
关闭连接
if 硬盘使用空间 > 90%:
#发送邮件提醒
连接邮箱服务器
发送邮件
关闭连接
if 内存占用 > 80%:
#发送邮件提醒
连接邮箱服务器
发送邮件
关闭连接
但是这种方式会使得代码量增大
如果用函数的话:
def 发送邮件(内容)
#发送邮件提醒
连接邮箱服务器
发送邮件
关闭连接
while True:
if cpu利用率 > 90%:
发送邮件('CPU报警')
if 硬盘使用空间 > 90%:
发送邮件('硬盘报警')
if 内存占用 > 80%:
发送邮件('内存报警')
总结使用函数的好处:
1.代码重用
2.保持一致性,易维护
3.可扩展性
【过程】
解释:过程定义:过程就是简单特殊没有返回值的函数
对比举例:
-------------------这是一个过程-------------------
def test01():
msg='hello The little green frog'
print(msg) #hello The little green frog
print(test01()) #返回值是None
-------------------这是一个函数-------------------
def test02():
msg='hello WuDaLang'
print(msg) #hello WuDaLang
return msg #hello WuDaLang
总结:
返回值数=0:返回None
返回值数=1:返回object
返回值数>1:返回tuple(见下面的例子)
定义的函数可以返回多个值,以元组的形式输出
def test():
print('alex')
return 1,2,3,[4,5],None,('a','b'),{'name':'tom'}
print(test())
#输出结果:
#alex
#(1, 2, 3, [4, 5], None, ('a', 'b'), {'name': 'tom'})
【函数的参数】
1.形参变量只有在被调用时才分配内存单元,在调用结束时,即刻释放所分配的内存单元。因此,形参只在函数内部有效。函数调用结束返回主调用函数后则不能再使用该形参变量
2.实参可以是常量、变量、表达式、函数等,无论实参是何种类型的量,在进行函数调用时,它们都必须有确定的值,以便把这些值传送给形参。因此应预先用赋值,输入等办法使参数获得确定值
def test(x,y):
c = x*y #形参
return c
print(test(2,3)) #实参
3.位置参数和关键字(标准调用:实参与形参位置一一对应;关键字调用:位置无需固定;位置参数和关键字参数混合调用时,位置参数必须在关键字的左边)
def test(x,y,z):
c = x*y*z
return c
test(2,3,4) #位置参数
test(y=3,x=2,z=4) #关键字参数
test(2,4,z=3) #混合
4.默认参数
5.参数组
def test(x,*args): #位置参数传值
print(x)
print(args)
print(args[0])
test(1,2,3,4,5,6)
输出为:
1
(2, 3, 4, 5, 6)
2
def test(x, **kwargs): #关键字参数传值
print(x)
print(kwargs)
test(1,y=2,z=3)
输出为:
1
{'y': 2, 'z': 3}
混合
def test(x,*args,**kwargs):
print(x)
print(args)
print(kwargs)
test(1,2,3,4,5,y=2,z=3)
test(1,*[2,3,4,5],**{'y':2,'z':3})
输出为:
1
(2, 3, 4, 5)
{'y': 2, 'z': 3}
1
(2, 3, 4, 5)
{'y': 2, 'z': 3}