Check if user input is a string or number in Python
In this tutorial, we will learn how to check if user input is a string or number in Python.
We have some tricks to check user input.
Type 1: type(num) to check input type in Python
num = input("Enter Something:") print(type(num))
Output:
Enter Something: 5
<class ‘int’>
Enter Something: abc
<class ‘str’>
Type2: isnumeric() function to check if a number is integer or not in Python
Thing = input("Enter Something:") if Thing.isnumeric(): print("Entered Thing is Integer:", Thing) else: print("Entered Thing is Not an Integer")
Output:
Enter Something: 123 Entered Thing is Integer: 123 Enter Something: abc Entered Thing is Not an Integer
Type3:
In this type, we define is_Int as True, if the user entered input, it tries to convert into the integer in that there is a non-numeric character then it goes to the ValueError. In the if condition statement is_Int is True.
thing = input("Enter Something:") is_Int = True try: int(thing) expect ValueError: is_Int = False if is_Int: print("Entered thing is Integer") else: print("Entered thing is not an Integer")
Output:
Enter Something: 123 Entered thing is Integer Enter Something: abc Entered thing is not an Integer
Type4: isdigit() function in Python
thing = 123 if thing.isdigit(): print("It is Integer") else: print("It is Not a Integer")
Output:
It is Integer
isdigit() function for string in Python
Also read: Python program to check whether given number is Hoax Number
Leave a Reply