def quadratic(a,b):
if not isinstance((a,b),(int,float)):
raise TypeError('bad operand type');
delt = b*b - 4 * a * c;
if delt < 0 :
return 'error';
else :
x1 = (-b + math.sqrt(delt))/(2*a);
x2 = (-b - math.sqrt(delt))/(2*a);
return x1,x2
quadratic(1,2,3)
错误代码:
Traceback (most recent call last): File "", line 1, inquadratic(2,3) File "", line 3, in quadratic
raise TypeError('bad operand type');
TypeError: bad operand type
上面的代码我也不知道是哪里的问题,将上面检查变量类型的代码改为下面的程序就可以了,有没有哪位大神知道是为什么,求指导。
def quadratic(a,b,c):
for i in (a,b,c):
if not isinstance(i,(int,float)):
raise TypeError('bad operand type');
delt = b*b - 4 * a * c;
if delt < 0 :
return 'error';
else :
x1 = (-b + math.sqrt(delt))/(2*a);
x2 = (-b - math.sqrt(delt))/(2*a);
return x1,x2
quadratic(1,2,3)
返回:'error'
quadratic(1,5,3)
返回:(-0.6972243622680054, -4.302775637731995)