【问题标题】:Python how to check if input is a letter or characterPython如何检查输入是字母还是字符
【发布时间】:2020-03-20 23:56:04
【问题描述】:

如何在 Python 中检查输入是字母还是字符?

输入应该是用户想要检查的数字数量。 然后程序应该检查用户给出的输入是否属于 tribonacci 序列(0,1,2 在任务中给出),如果用户输入的不是整数,程序应该继续运行。

n = int(input("How many numbers do you want to check:"))
x = 0

def tribonnaci(n):
    sequence = (0, 1, 2, 3)
    a, b, c, d = sequence
    while n > d:
        d = a + b + c
        a = b
        b = c
        c = d
    return d

while x < n:
    num = input("Number to check:")
    if num == "":
        print("FAIL. Give number:")
    elif int(num) <= -1:
        print(num+"\tFAIL. Number is minus")
    elif int(num) == 0:
        print(num+"\tYES")
    elif int(num) == 1:
        print(num+"\tYES")
    elif int(num) == 2:
        print(num+"\tYES")
    else:
        if tribonnaci(int(num)) == int(num):
            print(num+"\tYES")
        else:
            print(num+"\tNO")
    x = x + 1

【问题讨论】:

  • 使用inif 语句,如if variable in numers

标签: python input integer character sequence


【解决方案1】:

您可以使用 num.isnumeric() 函数,如果输入是数字,则返回“True”,如果输入不是数字,则返回“False”。

>>> x = raw_input()
12345
>>> x.isdigit()
True

你也可以使用 try/catch:

try:
   val = int(num)
except ValueError:
   print("Not an int!")

【讨论】:

    【解决方案2】:

    为了您的使用,使用.isdigit() 方法是您想要的。

    对于给定的字符串,例如输入,您可以调用string.isdigit(),如果字符串仅由数字组成,则返回True;如果字符串由其他任何内容组成或为空,则返回False .

    要进行验证,您可以使用if 语句来检查输入是否为数字。

    n = input("Enter a number")
    if n.isdigit():
        # rest of program
    else:
        # ask for input again
    

    我建议在用户输入要检查的数字时也进行此验证。由于空字符串"" 导致.isdigit() 返回False,因此您不需要单独的验证案例。

    如果您想了解更多关于字符串方法的信息,可以查看https://www.quackit.com/python/reference/python_3_string_methods.cfm,它提供了每种方法的信息并给出了每种方法的示例。

    【讨论】:

      【解决方案3】:

      这个问题不断以一种或另一种形式出现。这是一个更广泛的回应。

      ## Code to check if user input is letter, integer, float or string. 
      
      #Prompting user for input.
      userInput = input("Please enter a number, character or string: ") 
      while not userInput:
          userInput = input("Input cannot be empty. Please enter a number, character or string: ")
      
      #Creating function to check user's input
      inputType = '' #See: https://stackoverflow.com/questions/53584768/python-change-how-do-i-make-local-variable-global
      def inputType():
          global inputType
          
      def typeCheck():
          global inputType
          try:
              float(userInput) #First check for numeric. If this trips, program will move to except.
              if float(userInput).is_integer() == True: #Checking if integer
                  inputType = 'an integer' 
              else:
                  inputType = 'a float' #Note: n.0 is considered an integer, not float
          except:
              if len(userInput) == 1: #Strictly speaking, this is not really required. 
                  if userInput.isalpha() == True:
                      inputType = 'a letter'
                  else:
                      inputType = 'a special character'
              else:
                  inputLength = len(userInput)
                  if userInput.isalpha() == True:
                      inputType = 'a character string of length ' + str(inputLength)
                  elif userInput.isalnum() == True:
                      inputType = 'an alphanumeric string of length ' + str(inputLength)
                  else:
                      inputType = 'a string of length ' + str(inputLength) + ' with at least one special character'
      
      #Calling function         
      typeCheck()
      print(f"Your input, '{userInput}', is {inputType}.")
      

      【讨论】:

        【解决方案4】:

        如果像我一样使用 int,那么我只检查它是否 > 0;所以 0 也会失败。在这里我检查它是否 > -1,因为它在 if 语句中,我不希望 0 失败。

        try:
            if not int(data[find]) > -1:
                raise(ValueError('This is not-a-number'))
        except:
            return
        

        只是一个提醒。

        【讨论】:

          【解决方案5】:

          您可以通过以下方式检查输入的类型:

          num = eval(input("Number to check:"))
          if isinstance(num, int):
              if num < 0:
                  print(num+"\tFAIL. Number is minus")
              elif tribonnaci(num) == num: # it would be clean if this function also checks for the initial correct answers. 
                  print(num + '\tYES')
              else:
                  print(num + '\NO')
          else:
              print('FAIL, give number')
          

          如果没有给出 int 则错误,因此您可以声明输入错误。您可以对初始 n = int(input("How many numbers do you want to check:")) 调用执行相同的操作,如果它无法成功评估为 int 并导致程序崩溃,则会失败。

          【讨论】:

          猜你喜欢
          • 2013-08-05
          • 2012-12-23
          • 1970-01-01
          • 2018-05-03
          • 2011-09-01
          • 1970-01-01
          • 1970-01-01
          • 2013-10-09
          • 1970-01-01
          相关资源
          最近更新 更多