
保举教程:《python视频教程》
python自界说函数实例有哪些?
python自界说函数实例有:
一、甚么是函数?
函数是组织好的,可反复应用的,用来完成繁多,或相干联性能的代码段。函数能进步使用的模块性,以及代码的反复行使率。
二、函数的界说办法:
def test(x):
'函数界说办法'
x+=1
return x诠释:
def:界说函数要害字
test:函数名
():可界说形参
'':文档形容
x+=1:代码块或顺序解决逻辑
return:完结并前往值
函数为何要有前往值?
经过前往值接纳函数的执行后果,后续的逻辑需求经过此后果执行其对应操作。
(1)、实例:给一个文件写入日记信息
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()(2)、函数前往值阐明:
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)(3)、形参:界说的参数叫形参(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)
(4)、默许值参数:
# 默许值参数
def test_default(x,y=2):
'默许值参数'
z = x + y
return z
print(test_default(2)) #print(tesst_default(2,2))
(5)、参数组(没有定长参数):
# 参数组,承受地位参数,将多个实参存入一个元组中
# 界说格局:*变量名(普通标准为 *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')保举相干文章:《python教程》
以上就是python自界说函数实例有哪些?的具体内容,更多请存眷资源魔其它相干文章!
标签: Python python教程 python编程 python使用问题 自定义函数
抱歉,评论功能暂时关闭!