我试图让用户输入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.```
您需要移动while
循环中的以下代码块:
if input(prompt)=="q":
sys.exit()
你可以在except块中这样做:
while True:
try:
user_input = input(prompt)
value = int(user_input)
except ValueError:
if user_input == "q":
break # break out of loop
else:
print("Integers only.")
continue