更新时间:2023-02-19 10:26:05
一种相当常见的方法是使用而True
循环将无限期运行, break
输入有效时退出循环的语句:
A fairly common way to do this is to use a while True
loop that will run indefinitely, with break
statements to exit the loop when the input is valid:
print "pick a number, 1 or 2"
while True:
a = int(raw_input("> ")
if a == 1:
print "this"
break
if a == 2:
print "that"
break
print "you have made an invalid choice, try again."
此处还有一个很好的方法来限制重试,例如:
There is also a nice way here to restrict the number of retries, for example:
print "pick a number, 1 or 2"
for retry in range(5):
a = int(raw_input("> ")
if a == 1:
print "this"
break
if a == 2:
print "that"
break
print "you have made an invalid choice, try again."
else:
print "you keep making invalid choices, exiting."
sys.exit(1)