我想做的是问用户两个输入,然后它在输入上调用一个函数,但是如果它的结果引发异常,则要再次询问用户输入。
这是我到目前为止的内容:
class Illegal(Exception):
pass
def add_input(first_input, second_input):
if first_input + second_input >= 10:
print('legal')
else:
raise Illegal
first_input = input("First number: ")
second_input = input("Second number: ")
while add_input(int(first_input), int(second_input)) == Illegal:
print("illegal, let's try that again")
first_input = input("First number: ")
second_input = input("Second number: ")
但是到目前为止,我所遇到的问题是,由于它从函数中引发了该错误,因此它停止了所有操作,并且不再要求用户再次输入。我想知道如何解决此问题。
您无需通过将相等性与异常类进行比较来检查异常。你用try..except
块代替
while True: # keep looping until `break` statement is reached
first_input = input("First number: ")
second_input = input("Second number: ") # <-- only one input line
try: # get ready to catch exceptions inside here
add_input(int(first_input), int(second_input))
except Illegal: # <-- exception. handle it. loops because of while True
print("illegal, let's try that again")
else: # <-- no exception. break
break
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句