python 中自定义异常的错误处理
Error handling in python for custom exceptions
我正在尝试对这些运算符设置错误异常。基本上,如果输入的不是列表中的项目,我想抛出一个错误。我知道为什么这段代码不起作用,但我不确定如何修复它。请帮助我完成这项工作。谢谢
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')
希望这就是您要找的!
我正在尝试对这些运算符设置错误异常。基本上,如果输入的不是列表中的项目,我想抛出一个错误。我知道为什么这段代码不起作用,但我不确定如何修复它。请帮助我完成这项工作。谢谢
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')
希望这就是您要找的!