gpt4 book ai didi

python - 如果出现异常,请再次请求输入

转载 作者:行者123 更新时间:2023-11-28 21:21:15 24 4
gpt4 key购买 nike

我想做的是向用户询问两个输入,然后它调用输入上的一个函数,但如果它的结果​​引发异常而不是再次向用户询问输入。

这是我目前所拥有的:

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 block 来代替

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

关于python - 如果出现异常,请再次请求输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21943973/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com