1.python中使用def定义函数,函数定义格式为:
def 函数名(参数列表):
代码块
return 返回值
2.如果没有return语句,函数也会有返回值,返回None
3.若要从其他py文件中引用对应的方法,需要使用from语句,具体用法如下:
from 文件名(不加.py) import 函数名
4.空函数(钩子函数):什么也不做的函数。在函数代码块中使用pass,实际上pass是一个占位符
5.参数检查
a.如果传给函数参数的个数不对,python解释器会自动检查并抛出TypeError
b.如果参数个数正确,但是参数类型不对,python解释器就不能帮我们做检查了,但是可以借助内置的isinstance函数帮助我们检测参数的类型
def dowork(inta,intb): if(isinstance(inta,(int,float))&isinstance(intb,(int,float))): return inta+intb else: print('bad agrs type!') print(dowork(11,25)) print(dowork(11,'a'))
36
bad agrs type!
None
6.函数返回多个值,一个return语句,多个返回值用逗号分隔,多个返回值将被放入一个tuple中作为整体返回。
import math def dowork(a,b): return math.pow(a,2),math.pow(b,3) result = dowork(2,4) print('result:%s,type is %s'% (result,type(result))) c,d=dowork(2,5) print('c=%d,d=%d'% (c,d))
result:(4.0, 64.0),type is <class 'tuple'>
c=4,d=125