参数检查
def my_abs(x):
if not isinstance(x,(int,float)):
raise TypeError('Bad operand type')
if x >= 0:
return x
else:
return -x
a = my_abs(-10)
print(a)
- 使用了isinstance函数进行数据类型的检查
默认参数
- 例:
def power_n(x,n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
a = power_n(5,3)
print(a)
- 如果不写3默认函数power_n的参数为2