如何在要求用户输入的 while 循环中使用 try-except 命令

How to use the try-except command in a while loop asking for user input

我是 Python 初学者,第一次尝试使用 tryexcept。我要求用户输入一个整数值,但如果用户输入例如一个字符串,我不会结束程序,我想一次又一次地询问用户,直到给出一个整数。

目前,如果用户输入字符串,则只要求他给出另一个答案一次,但如果他再次输入错误,程序将停止。

下面举例说明我的意思。

我在 Whosebug 上浏览了类似的问题,但我无法用任何建议解决它。

travel_score = 0

while True:
    try:
        travel_score = int(input("How many times per year do you travel? Please give an integer number"))
    except ValueError:
        travel_score = int(input("This was not a valid input please try again"))


print ("User travels per year:", travel_score)

问题是,一旦你抛出 ValueError 异常,它就会被捕获在 except 块中,但如果再次抛出,就没有更多的 except 可以处理了捕获这些新错误。解决方案是仅在 try 块中转换答案,而不是在给出用户输入后立即转换。

试试这个:

travel_score = 0
is_int = False
answer = input("How many times per year do you travel? Please give an integer number: ")

while not is_int:    
    try:
        answer = int(answer)
        is_int = True
        travel_score = answer
    except ValueError:
        answer = input("This was not a valid input please try again: ")


print ("User travels per year:", travel_score)

问题是你的第二个输入没有异常处理。

travel_score = 0

while True:
    try:
        travel_score = int(input("How many times per year do you travel? Please give an integer number"))
    except ValueError:
        # if an exception raised here it propagates
        travel_score = int(input("This was not a valid input please try again"))


print ("User travels per year:", travel_score)

处理此问题的最佳方法是,如果用户的输入无效,则将信息性消息返回给用户,并允许循环 return 到开头,然后以这种方式重新提示:

# there is no need to instantiate the travel_score variable
while True:
    try:
        travel_score = int(input("How many times per year do you travel? Please give an integer number"))
    except ValueError:
        print("This was not a valid input please try again")
    else:
        break  # <-- if the user inputs a valid score, this will break the input loop

print ("User travels per year:", travel_score)

@Luca Bezerras 的回答很好,但你可以把它写得更紧凑一点:

travel_score = input("How many times per year do you travel? Please give an integer number: ")

while type(travel_score) is not int:    
    try:
        travel_score = int(travel_score)
    except ValueError:
        travel_score = input("This was not a valid input please try again: ")


print ("User travels per year:", travel_score)