让用户输入一个整数,或者在python中按“q”退出

2024-06-02 08:56:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图让用户输入一个介于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.```


Tags: ortointegers用户numberonlyyourif
1条回答
网友
1楼 · 发布于 2024-06-02 08:56:14

您需要在while循环中移动以下块:

if input(prompt)=="q":
    sys.exit()

除块外,您可以按以下方式执行此操作:

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

相关问题 更多 >