首页 > 解决方案 > 如何添加一个While循环来检测python输入中的错误

问题描述

所以,我正在尝试编写一个代码,不仅可以做算术方程,还可以在出现错误时提供反馈,并最多给我 3 次尝试。有什么建议吗?

arithmetic=input("Enter an arithmetic operation:")
arithmetic= arithmetic.replace(" ", "")  
w=arithmetic.split('/')
x= arithmetic.split('-')  
y=arithmetic.split('+')
z=arithmetic.split('*')
if ("+" in arithmetic):
    a= int(y[0])
    b= int(y[1])
    sum = a + b
    print("The result is = " + str(sum))
elif ("*" in arithmetic):
    a= int(z[0])
    b= int(z[1])
    result = a * b
    print("The result is = " + str(result))            
elif ("/" in arithmetic):
    a= int(w[0])
    b= int(w[1])
    result = a / b
    result = round(result,3)
    print("The result is = " + str(result)) 
    
elif ("-" in arithmetic) and (len(x)==3):  
    a= int(x[1])
    b= int(x[2])
    result = a + b                    
    result = result  * (-1)
    print("The result is = " + str(result))    
    
elif ("-" in arithmetic) and (len(x)==2):  
    a= int(x[0])
    b= int(x[1])  
    result = a - b
    print("The result is = " + str(result)) 
#tries = 0
#while(tries  < 3):
#    arithmetic=input("Enter an arithmetic operation:")
#    match = arithmetic.find('+')
#    print(match)
#    if(match == -1): 
#        print ("Invalid")
#        tries += 1
#    else:
#        tries= 3

我试图在开始时添加while。但是,当我输入诸如1112不带+符号的输入时,它只是打印输入而没有给我一个错误。这是为什么?

标签: pythonpython-3.x

解决方案


在 if / else if 链的末尾,只需添加:

else:
    print("invalid")
    tries += 1

用上面未注释的代码替换您当前在 while 循环中的所有内容,这应该可以工作。


推荐阅读