【问题标题】:Having a user input an integer, or quitting by pressing 'q' in python让用户输入一个整数,或在 python 中按“q”退出
【发布时间】: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


    【解决方案1】:

    您需要在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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-01-11
      • 1970-01-01
      • 2018-03-07
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多