Discuss / Python / 为什么判断输入是否为数字的那段代码失效了?如果输入没问题的话运行是测试成功,但是报错的时候并没有按预计的报输入错误,还有输入a等于0的时候按预计报错了

为什么判断输入是否为数字的那段代码失效了?如果输入没问题的话运行是测试成功,但是报错的时候并没有按预计的报输入错误,还有输入a等于0的时候按预计报错了

Topic source

-- coding: utf-8 --

import math

def quadratic(a, b, c):

for n in (a,b,c):
    if not isinstance(n, (int,float)) or a==0:
        raise TypeError('输入错误')
d=b*b-4*a*c
if d>0:
    d=math.sqrt(d)
    x1=(-b+d)/(2*a)
    x2=(-b-d)/(2*a)
    return x1,x2
elif d==0:
    x0=-b/2*a
    return x0
else:
    print('无解')

r=quadratic(10q,3,1) print(r)

测试:

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

if quadratic(2, 3, 1) != (-0.5, -1.0): print('测试失败') elif quadratic(1, 3, -4) != (1.0, -4.0): print('测试失败') else: print('测试成功')

梁展豪M

#2 Created at ... [Delete] [Delete and Lock User]

你好,解决了吗?我试过教程上my_abs的代码,也出不来TypeError‘bad operand type’那个结果,估计是教程上的代码就是有偏颇

梁展豪M

#3 Created at ... [Delete] [Delete and Lock User]

你输入a时的报错是name 'a' is not defined么,是的话原因就是我们在输入时得输入‘a’而不能是a,前者才是字符串,后者只是变量,而这个变量是没有被定义的。 也就是说这里只有输入quadratic('a', 1, 1)时,报错才会是TypeError。


  • 1

Reply