如何让我的Python程序在输入无效时退出并显示错误信息?
这是我目前写的代码..
#solving a quadratic equation
#finding conjugate pair of imaginary roots if no real roots
import math
import sys
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
try:
# find the discriminant
d = (b**2)-(4*a*c)
if d < 0:
import cmath #importing complex math to find imaginay roots
x1 = (-b-cmath.sqrt(d))/(2*a)
x2 = (-b+cmath.sqrt(d))/(2*a)
print"This equation gives a conjugate pair of imaginary roots: ", x1, " and", x2
elif d == 0:
x = (-b+math.sqrt(d))/(2*a)
print "This equation has one solutions: ", x
else:
x1 = (-b+math.sqrt(d))/(2*a)
x2 = (-b-math.sqrt(d))/(2*a)
print "This equation has two solutions: ", x1, " and", x2
except:
SystemExit
我需要让我的程序能够处理用户输入的非数字数据。之前我尝试过用条件语句(if..elif..else)和异常处理。
我希望程序能显示一个错误信息,并提示用户再试一次。
求助
1 个回答
3
更新
你可能想把
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
变成
def get_input(s):
while True:
try:
return float(input('Enter %s: ' % s))
except ValueError:
print 'Error: Invalid Input.'
a = get_input('a')
b = get_input('b')
c = get_input('c')