Discuss / Python / 在for循环中通过函数isinstance()对参数逐个遍历,检查每个参数的参数类型。

在for循环中通过函数isinstance()对参数逐个遍历,检查每个参数的参数类型。

Topic source

def quadratic(a,b,c):

for n in (a,b,c):
    if not isinstance(n,(int,float)):
        raise TypeError('bad operand type')

r = b**2 - 4*a*c
if r > 0:
    x1 = (-b + math.sqrt(r))/2*a
    x2 = (-b - math.sqrt(r))/2*a
    return x1,x2
elif r == 0:
    x = (-b)/2*a
    return x
else:
    return "无解"

print('quadratic(1,3,-4) =', quadratic(1,3,-4))


  • 1

Reply