【问题标题】:How to verify if input is not a letter or string?如何验证输入是否不是字母或字符串?
【发布时间】:2016-03-05 21:51:24
【问题描述】:

我正在 IDLE 中编写一个带有 1 到 4 选项的菜单选项的基本程序。 如果用户输入除数字之外的任何其他内容,则会给出 ValueError: invalid literal for int() with base 10: 'a' 如何检查输入是否不是字母,如果是,打印我自己的错误消息?

【问题讨论】:

    标签: python-3.x input menu


    【解决方案1】:
    def isNumber (value):
        try:
            floatval = float(value)
            if floatval in (1,2,3,4):
                return True
            else:
                return False
        except:
            return False
    
    number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
    
    while isNumber(number_choice) == False:
        number_choice = input('Please choose a number: 1, 2, 3 or 4.\n')
    else:
        print('You have chosen ' + number_choice + '.\n')
    

    这将检查数字是 1、2、3 还是 4,如果不是,则要求用户再次输入数字,直到符合条件。

    【讨论】:

      【解决方案2】:

      我有点不清楚你是否希望测试某个东西是整数还是字母,但我正在回应前一种可能性。

          user_response = input("Enter an integer: ")
      
          try:
              int(user_response)
              is_int = True
          except ValueError:
              is_int = False
      
          if is_int:
              print("This is an integer! Yay!")
          else:
              print("Error. The value you entered is not an integer.")
      

      我对 python 还很陌生,所以很可能有更好的方法来做到这一点,但这就是我过去测试输入值是否为整数的方式。

      【讨论】:

      • 使用你的方法,如果它是 int 值,我可以让它打印出来。其他任何事情都会给我一个回溯错误。
      • 你想对它是否为整数的信息做什么?如果您发布您正在处理的代码可能会有所帮助。
      【解决方案3】:

      isalpha() - 它是一种字符串方法,用于检查输入的字符串是字母还是单词(只有字母,没有空格或数字)

              while True:
                  user_response = input("Enter an integer : ")
                  if user_response.isalpha():
                      print("Error! The value entered is not an integer")
                      continue
                  else:
                      print("This is an integer! Yay!")
                      break
      

      这个程序有无限循环,即在你输入一个整数之前,这个程序不会停止。我为此使用了 break 和 continue 关键字。

      【讨论】:

        猜你喜欢
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-29
        • 1970-01-01
        • 2018-08-18
        • 1970-01-01
        • 2010-11-13
        相关资源
        最近更新 更多