[英]How to use the try-except command in a while loop asking for user input
我是一个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)
问题是,一旦你抛出了ValueError
异常,就会在except
块中捕获它,但是如果再次抛出它, except
s 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)
处理此问题的最佳方法是,如果输入无效,则将信息性消息发回给用户,并允许循环返回到开头并以此方式重新提示:
# 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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.