0

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 belongs to tribonacci sequence (0,1,2 are given in task) and in case user enter something different than integer, program should continue to run.

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
Dominika
  • 11
  • 1
  • 1
  • 2

5 Answers5

1

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!")
Gaming.ingrs
  • 271
  • 1
  • 13
0

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

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}.")
user702432
  • 11,898
  • 21
  • 55
  • 70
0

If using int, as I am, then I just check if it is > 0; so 0 will fail as well. Here I check if it is > -1 because it is in an if statement and I do not want 0 to fail.

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

just a reminder.

bauderr
  • 47
  • 10
-1

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.

Marc
  • 1,539
  • 8
  • 14