Python how to check if input is a letter or character

前端 未结 4 592
暖寄归人
暖寄归人 2021-01-26 10:53

How can I check if input is a letter or character in Python?

Input should be amount of numbers user wants to check. Then program should check if input given by user be

相关标签:
4条回答
  • 2021-01-26 11:33

    This question keeps coming up in one form or another. Here's a broader response.

    ## 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}.")
    
    0 讨论(0)
  • 2021-01-26 11:34

    For your use, using the .isdigit() method is what you want.

    For a given string, such as an input, you can call string.isdigit() which will return True if the string is only made up of numbers and False if the string is made up of anything else or is empty.

    To validate, you can use an if statement to check if the input is a number or not.

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

    I suggest doing this validation when the user is inputting the numbers to be checked as well. As an empty string "" causes .isdigit() to return False, you won't need a separate validation case for it.

    If you would like to know more about string methods, you can check out https://www.quackit.com/python/reference/python_3_string_methods.cfm which provides information on each method and gives examples of each.

    0 讨论(0)
  • 2021-01-26 11:41

    You can check the type of the input in a manner like this:

    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')
    

    and if not an int was given it is wrong so you can state that the input is wrong. You could do the same for your initial n = int(input("How many numbers do you want to check:")) call, this will fail if it cannot evaluate to an int successfully and crash your program.

    0 讨论(0)
  • 2021-01-26 11:52

    You can use num.isnumeric() function that will return You "True" if input is number and "False" if input is not number.

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

    You can also use try/catch:

    try:
       val = int(num)
    except ValueError:
       print("Not an int!")
    
    0 讨论(0)
提交回复
热议问题