python中自定义异常的错误处理



我正试图在这些运算符上设置一个错误异常。基本上,如果输入了列表上项目以外的任何内容,我想抛出一个错误。我知道为什么这个代码不起作用,但我不知道如何修复它。请帮助我使这个工作。谢谢

while True:
sign = ["+", "-" , "/" , "*"]
try:
operation_type=(input("what operation type you want to do?"))
for i in range (len(sign)) :

if (operation_type!= sign[i]):
print ("pass")
raise Invalid
i+=1
break
except Invalid:
print("Please input + or - or / or *")

以下是我发现效果最好的内容(我包含了应该解释一切的注释(:

sign = ["+", "-" , "/" , "*"]
while True:
operation_type=input("what operation type you want to do?")
if operation_type in sign:#If the input is in one of the operations in sign, then quit.
print(operation_type, 'passed')
break#Break out of checking loop, as the requirement is met
print('that is not the required operation')#Essentially your exception

print('program done')

我希望这就是你想要的!

最新更新