python - 如何添加一个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。但是,当我输入诸如11
和12
不带+
符号的输入时,它只是打印输入而没有给我一个错误。这是为什么?
解决方案
在 if / else if 链的末尾,只需添加:
else:
print("invalid")
tries += 1
用上面未注释的代码替换您当前在 while 循环中的所有内容,这应该可以工作。
推荐阅读
- python - 就 n 和 m 而言,以下算法的运行时复杂度是多少?
- vb.net - 从下拉框中选择项目时尝试激活特定的控制器功能
- php - httpful:当 JSON 属性值是 XML 中的字符串时,响应损坏
- exception - Keycloak 12.0.4 导出抛出异常
- html - 如何为不同的按钮组选择和更改颜色按钮?
- python - Python套接字如何添加多个客户端并向每个客户端发送字节
- javascript - ngx-dataTable 如何应用格式化功能
- node.js - 混淆 node_modules 被 .dockerignore 忽略
- python - arduino pyfirmata 模拟阅读
- php - 以编程方式设置发货 WooCommerce