Python – Check if Variable is a Number
In this tutorial, we are going to see how to check if a variable is a Number in Python. As you know, Python’s input() function always converts the user input to a string. i.e. the user input type is always a string. Now let’s look at how to check if the user input is a number or a string. When we say a number, it means that it can be an integer or a float.
Method 1: Convert the input to int or float
In this approach, we can verify that the input is a number or a string by converting the input to “int” type. If the input is an integer, it can be successfully converted to “int”, and we can say that the input is a number. Otherwise, you get a valueError exception and we can say that the input is a string.
nbr = input ("Enter a number: ") try: val = int(nbr) print("The input value is an integer = ", val) except ValueError: print("It is not an integer!")
Output:
Enter a number: 2 The input value is an integer = 2 Enter a number: c It is not an integer!
Method 2: Use the isdigit() method to check if the input is a number or a string
nbr = input ("Enter a number: ") if( nbr.isdigit()): print("The input value is a number") else: print("The input value is a string")
Output:
Enter a number: 10 The input value is a number Enter a number: char The input value is a string