函数 function
1.函数创建
def function(arg1,arg2):
#关键字 函数名(参数):
#缩进表明语句与逻辑的从属关系,Python特点之一
return 'something'
2.函数创建练习
摄氏度转换华氏度
def fahrenheit_converter(C):
fahrenheit=C*9/5+32
return str(fahrenheit)+'℉'
#计算结果为int类型,需要先转换
C2F=fahrenheit_converter(C)
#调用方法并传入参数
3.参数传递
def trapezoid_area(base_up,base_down,height):
return 1/2*(base_up+base_down)*height
trapezoid_area(1,2,3)
1对应参数base_up,2对应base_down,3对应height。
传入参数的方式:位置参数
trapezoid_area(height=3,base_down=2,base_up=1)
函数参数反序传入,因为使用关键字参数,所以可以运行。
传入参数的方式:关键字参数
trapezoid_area(height+3,base_down=2,1)
#报错
前2个使用关键字传参,第3个使用位置参数,如何按照位置传入,最后一个是height的位置与前面冲突。
3.参数默认值
def trapezoid(base_up,base_down,height=3):
#height参数设定默认值
return 1/2*(base_up+base_down)*height
trapezoid(1,2)
trapezoid(1,2,15)
#默认值可以在传入参数时修改