我在python 3.5中使用此代码作为'二次公式';
def quad(a,b,c):
d = (b**2) - (4*a*c)
num1 = (-b+math.sqrt(d))/(2*a)
num2 = (-b-math.sqrt(d))/(2*a)
print ("Your solutions are", num1, "and", num2)
代码工作正常,但是当num1和num2的值显示为" ValueError时,有没有办法让我添加一个显示的打印功能(" Math Error")数学域错误"
我在找这样的东西......
if num1 or num2 = ValueError: # I can't figure out how to 'word' this
print ("Math Error")
答案 0 :(得分:0)
只使用普通的普通异常处理程序
import sys
def quad(a,b,c):
try:
d = (b**2) - (4*a*c)
num1 = (-b+math.sqrt(d))/(2*a)
num2 = (-b-math.sqrt(d))/(2*a)
print ("Your solutions are", num1, "and", num2)
except ValueError as e:
print("Math error", e, file=sys.stderr)