函数:函数是组织好的,可重复使用的,用来实现单一,或相关联功能的代码段。
函数的定义
定是函数使用def关键字
def myfunc(x):if x >= 0:return x else:return -x
空函数
def emptyfunc():pass
参数检查
def checkfunc(x):if not isinstance(x,(int,float)):raise TypeError("must be int or float type!")if x >= 0:return xelse:return -x
返回多个值
def price(x):apple=x*2banana=x*2.5return apple,banana a,b=price(1)
函数的参数
必选参数parameter
def printdetail1(name,age,telephone):print("姓名:",name)print("年龄:",age)print("电话:",telephone) printdetail1("Jack",12,12356435678)
默认参数parameter=value
def printdetail2(name,age,telephone,gender='fale'):print("姓名:",name)print("性别:",gender)print("年龄:",age)print("电话:",telephone) printdetail2("Jack",12,12356435678,gender='female')
可变参数*
1.不定长传参
def fun1(*number):for i in number:print(i)fun1(1,2,3,4,5,6,7,8)
2.元组和列表的压包
def fun2(*number):s=0for i in number:s+=iprint(s) fun2(*[1,2,3,4,5]) fun2(*(1,2,3,4,5))
关键参数**
使用方法一
def fun(id,name,**kargs):print("id:",id)print("name:",name)print("others:",kargs) fun(2,"xiaohua",sex="man",age='12')
使用方法二
extra={'sex': 'man', 'age': 12} def fun(id,name,**kargs):print("id:",id)print("name:",name)print("others:",kargs) fun(2,"xiaohua",sex=extra['sex'],age=extra['age'])
使用方法三
extra={'sex': 'man', 'age': 12} def fun(id,name,**kargs):print("id:",id)print("name:",name)print("others:",kargs) fun(2,"xiaohua",**extra)
关键字参数*
def fun(name,age,*,city,job,completion):print("name:",name)print("age:",age)print("city:",city)print("job:",job)print("completion:",completion) fun('Jack',12,city='shanghai',job='teacher',completion=True)
命名关键字参数需要一个特殊分隔符*,后面的参数被视为命名关键字参数
如果函数定义中已经有了一个可变参数,后面跟着的命名关键字参数就不再需要一个特殊分隔符*了
参数组合
def fun(parameter,*args,keyparameter,**kargs):print(parameter)print(args)print(keyparameter)print(kargs) fun(1,*(1,2,3,4),keyparameter=True,**{'id':2})
参数定义的顺序必须是:必选参数、默认参数、可变参数、命名关键字参数和关键字参数
函数的递归
#阶乘计算 def fact(n):if n == 1:return 1return n * fact(n-1)