什么是函数?
函数是组织好的, 可重复使用的, 用来实现单一, 或相关联功能的代码段. 函数能提高应用的模块性, 和代码的重复利用率.
函数的定义方法:
- def test(x):
- '函数定义方法'
- x+=1
- return x
解释:
def: 定义函数关键字
test: 函数名
(): 可定义形参
'': 文档描述
x+=1: 代码块或程序处理逻辑
return: 结束并返回值
函数为什么要有返回值?
通过返回值接收函数的执行结果, 后续的逻辑需要通过此结果执行其对应操作.
实例: 给一个文件写入日志信息
- import time
- # 定义函数
- def test1():
- '函数练习: 添加日志记录'
- log_time = time.strftime('%Y-%m-%d %X')
- with open('file_a','a') as f:
- f.write(log_time+':log msg\n')
- # 调用函数
- test1()
函数返回值说明:
return 返回值数量 = 0: 返回一个空值 (None)
返回值数量 = 1: 返回一个对象 (object)
返回值数量 > 1: 返回一个元组 (tuples)
实例:
- # 函数返回类型
- def test_None():
- print('返回一个空值')
- x=test_None()
- print(x)
- def test_object():
- print('返回一个对象')
- return 0
- y=test_object()
- print(y)
- def test_tuples():
- print('返回一个元组')
- return 1,'hello world',['qwe','asd'],{'001':'simple'}
- z=test_tuples()
- print(z)
形参: 定义的参数叫形参 (x,y)
实参: 实际传入的参数叫实参 (1,2)
不指定参数的情况下: 实参与形参位置一一对应
实例:
注: 位置传参与关键字传参共用时, 关键字参数不能写在位置参数之前
- def test_sum(x,y):
- '两数之和'
- z = x + y
- return z
- t_sum=test_sum(1,2) #实参与形参位置一一对应
- print(t_sum)
- t_sum2=test_sum(x=1,y=2) #与形参位置无关
- print(t_sum2)
- t_sum3=test_sum(1,y=2) # 错误方式: test_sum(x=1,2) 位置传参与关键字传参共用时, 关键参数不能写在位置参数之前
- print(t_sum3)
默认值参数:
- # 默认值参数
- def test_default(x,y=2):
- '默认值参数'
- z = x + y
- return z
- print(test_default(2)) #print(tesst_default(2,2))
参数组 (不定长参数):
- # 参数组, 接受位置参数, 将多个实参存入一个元组中
- # 定义格式:* 变量名 (一般规范为 *args)
- def test_group(*args):
- '参数组'
- print(args)
- test_group(1,2,3,4,5,6)
- def test_group2(x,*args):
- '参数组与位置参数混用'
- print(x)
- print(args)
- test_group2(1,2,3,4,5,6)
- # 接受关键字参数组, 转换成字典
- def test_group3(**kwargs):
- '参数组键值对形式'
- print(kwargs['name'])
- test_group3(name='simple',age=25,sex='m')
- def test_group4(name,**kwargs):
- '参数, 参数组键值对混用'
- print(name)
- print(kwargs)
- test_group4('simple',age=25,sex='m')
- # 注: 参数组必须放在位置参数, 默认参数之后
- def test_group5(name,age=25,**kwargs):
- '参数, 默认参数, 参数组键值对混用'
- print(name)
- print(age)
- print(kwargs)
- test_group5('simple',age=3,sex='m',game='lol')
- def test_group6(name,age=25,*args,**kwargs):
- '参数, 默认参数, 参数组, 参数组键值对混用'
- print(name)
- print(age)
- print(*args)
- print(kwargs)
- test_group5('simple',age=3,sex='m',game='lol')
来源: http://www.bubuko.com/infodetail-2784283.html