如果输入了无效的输入,如何让python程序退出并显示错误消息?
这是我目前掌握的代码如果输入了无效的输入,如何让python程序退出并显示错误消息?,python,input,message,exit,equation,Python,Input,Message,Exit,Equation,这是我目前掌握的代码 #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
#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
求解二次方程
#如果没有实根,求虚根的共轭对
输入数学
导入系统
a=浮动(输入('输入a:'))
b=浮动(输入('输入b:'))
c=浮点(输入('Enter c:'))
尝试:
#找到判别式
d=(b**2)-(4*a*c)
如果d<0:
导入cmath#导入复杂数学以查找ImageAy根
x1=(-b-cmath.sqrt(d))/(2*a)
x2=(-b+cmath.sqrt(d))/(2*a)
print“这个方程给出了一对共轭的虚根:”,x1,“和”,x2
elif d==0:
x=(-b+数学sqrt(d))/(2*a)
打印“此方程有一个解:”,x
其他:
x1=(-b+数学sqrt(d))/(2*a)
x2=(-b-数学sqrt(d))/(2*a)
打印“此方程有两个解:”、x1和“、x2
除:
系统出口
我需要使我的程序对输入非数字数据的用户具有鲁棒性。我尝试过使用条件语句(if..elif..else)并尝试过异常处理
我需要程序显示一条错误消息,并提示用户重试
帮助已更新 你可能想转身
a = float(input('Enter a: '))
b = float(input('Enter b: '))
c = float(input('Enter c: '))
到
float
如果输入无法转换为float,则抛出一个ValueError
。使用while(True):
循环和try except
如果没有引发异常,请中断并继续。将其包装在while(True)
中,并删除exit()
,如果没有引发异常并且您已经回答了OP:-)中的问题,则添加break
。@FredrikPihl更新了答案。
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')