我是Python初学者,并尝试首次使用try
和except
。我在问用户一个整数值,但是我不想一次又一次地问用户,直到给出整数为止,而不是结束该程序(如果用户输入了一个字符串)。
此刻,仅询问用户一次是否提供字符串,但如果再次输入错误,程序就会停止。
下面是我的意思的一个例子。
我在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)
答案 0 :(得分:0)
问题在于,一旦抛出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)
答案 1 :(得分:0)
问题是您的第二个输入没有异常处理。
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)
答案 2 :(得分:0)
@Luca Bezerras的回答很好,但是您可以使其更加紧凑:
_id:ObjectId("111111111111111111111112")
name: "Honda Civic" (String value)