【发布时间】:2021-05-22 03:57:41
【问题描述】:
我试图让用户输入一个介于 1 和变量 ntopics 之间的整数,但是包括按“q”退出会导致问题。运行以下代码仅允许用户退出,如果“q”是第一个输入 - 它也只会在第二个输入后为用户打印一条错误消息。
def get_non_negative_int_or_q(prompt):
if input(prompt)=="q":
sys.exit()
else:
while True:
try:
value = int(input(prompt))
except ValueError:
print("Integers only.")
continue
if value < 1:
print(f"Sorry, your response must be an integer between 1 and {ntopics}.")
continue
if value > ntopics:
print(f"Sorry, your response must be an integer between 1 and {ntopics}.")
continue
else:
break
return value
your_number = get_non_negative_int_or_q("Enter your number (or q to quit):")
终端随后将如下所示:
Enter your number (or q to quit):r
Enter your number (or q to quit):r
Integers only.
Enter your number (or q to quit):r
Integers only.
Enter your number (or q to quit):q
Integers only.```
【问题讨论】:
标签: python python-3.x validation input while-loop