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



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

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

下面是我的意思的例子。

我在Stackoverflow上浏览了类似的问题,但我无法通过任何建议来解决它。

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)

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

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)

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

# 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)
<</div> div class="one_answers">

问题是,一旦你抛出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)

最新更新