【问题标题】:How to check if input is digit and in range at the same time? Python如何检查输入是否同时是数字和范围? Python
【发布时间】:2017-12-25 09:57:02
【问题描述】:

我想同时检查我的输入是否是数字并且在范围(1,3)内并重复输入直到我得到满意的答案。 现在我以这种方式执行此操作,但代码相当不干净和容易......有没有更好的方法来做到这一点? 也许有while循环?

def get_main_menu_choice():
    ask = True
    while ask:
        try:
            number = int(input('Chose an option from menu: '))
            while number not in range(1, 3):
                number = int(input('Please pick a number from the list: '))
            ask = False
        except: # just catch the exceptions you know!
            print('Enter a number from the list')
   return number

将不胜感激。

【问题讨论】:

    标签: python python-3.x loops input


    【解决方案1】:

    如果您的 整数 数字介于 1 和 2 之间(或者它在范围 (1,3) 内),则它已经意味着它是 一个数字!

    while not (number in range(1, 3)):
    

    我会简化为:

    while number < 1 or number > 2:
    

    或

    while not 0 < number < 3:
    

    您的代码的简化版本仅在 int(input()) 周围有 try-except:

    def get_main_menu_choice():
        number = 0
        while number not in range(1, 3):
            try:
                number = int(input('Please pick a number from the list: '))
            except: # just catch the exceptions you know!
                continue # or print a message such as print("Bad choice. Try again...")
        return number
    

    【讨论】:

    • 但是当有人输入空字符串(Enter)或字母时,我需要保护。我需要让他们输入,直到他们输入数字 1 或 2。
    • 啊,我误解了你的问题。看来您有兴趣处理except!
    • @JeyKey 我已经添加了您的代码的简化版本。
    【解决方案2】:

    看看这是否有效

    def get_main_menu_choice():
        while True:
            try:
                number = int(input("choose an option from the menu: "))
                if number not in range(1,3):
                    number = int(input("please pick a number from list: "))
            except IndexError:
                number = int(input("Enter a number from the list"))
        return number
    

    【讨论】:

      【解决方案3】:

      如果您还需要对非数字进行验证,则必须添加几个步骤:

      def get_main_menu_choice(choices):
          while True:
              try:
                  number = int(input('Chose an option from menu: '))
                  if number in choices:
                      return number
                  else:
                      raise ValueError
              except (TypeError, ValueError):
                  print("Invalid choice. Valid choices: {}".format(str(choices)[1:-1]))
      

      然后您可以通过传递有效选项列表将其重用于任何菜单,例如get_main_menu_choice([1, 2]) 或 get_main_menu_choice(list(range(1, 3)))。

      【讨论】:

        【解决方案4】:

        我想最干净的方法是删除双循环。但是如果你想要循环和错误处理,无论如何你都会得到一些令人费解的代码。我个人会去:

        def get_main_menu_choice():
            while True:    
                try:
                    number = int(input('Chose an option from menu: '))
                    if 0 < number < 3:
                        return number
                except (ValueError, TypeError):
                    pass
        

        【讨论】:

          【解决方案5】:

          我会这样写:

          def get_main_menu_choice(prompt=None, start=1, end=3):
              """Returns a menu option.
          
              Args:
                  prompt (str): the prompt to display to the user
                  start (int): the first menu item
                  end (int): the last menu item
          
              Returns:
                  int: the menu option selected
              """
              prompt = prompt or 'Chose an option from menu: '
              ask = True
              while ask is True:
                  number = input(prompt)
                  ask = False if number.isdigit() and 1 <= int(number) <= 3 else True
             return int(number)
          

          【讨论】:

            【解决方案6】:
            def user_number():
            
                # variable initial
                number = 'Wrong'
                range1 = range(0,10)
                within_range = False
            
                while number.isdigit() == False or within_range == False:
                    number = input("Please enter a number (0-10): ")
            
                    # Digit check
                    if number.isdigit() == False:
                        print("Sorry that is not a digit!")
            
                    # Range check
                    if number.isdigit() == True:
                        if int(number) in range1:
                            within_range = True
                        else:
                            within_range = False
            
                return int(number)
            
            print(user_number())
            ``
            

            【讨论】:

            • 不鼓励在 SO 上仅使用代码回答。高质量的答案通常包括解释,允许用户快速关注并了解代码的相关部分如何解决 OP 的问题。随着未来的访问者学到一些可以用来解决他们自己的编码问题的东西,随着时间的推移,大多数支持都会获得。考虑编辑以添加解释或上下文。感谢您的贡献,欢迎来到 SO。
            猜你喜欢
            • 2021-10-12
            • 2013-12-04
            • 1970-01-01
            • 2015-11-28
            • 1970-01-01
            • 1970-01-01
            • 2011-01-09
            • 1970-01-01
            • 2021-04-05
            相关资源
            最近更新 更多