How to Check if Input is a Number in Python?

Estimated read time 2 min read

To check if an input is a number in Python, you can use the isdigit() method for strings or use exception handling to attempt conversion to a numeric type. Here are two approaches:

  1. Using isdigit() for strings:
user_input = input("Enter something: ")

if user_input.isdigit():
    print("Input is a number")
else:
    print("Input is not a number")

In this example, we use the input() function to prompt the user to enter something. The input is stored in the user_input variable.

We then use the isdigit() method to check if the user_input consists only of digits. If the input is composed entirely of digits, the isdigit() method returns True, and we print “Input is a number”. Otherwise, if the input contains non-digit characters, we print “Input is not a number”.

Note that isdigit() is applicable only for strings and checks if all characters in the string are digits.

  1. Using exception handling for numeric conversion:
user_input = input("Enter something: ")

try:
    float(user_input)
    print("Input is a number")
except ValueError:
    print("Input is not a number")

In this approach, we use the float() function to attempt to convert the user_input to a floating-point number. If the conversion succeeds without raising a ValueError exception, we consider the input as a number and print “Input is a number”. Otherwise, if a ValueError is raised, we conclude that the input is not a number and print “Input is not a number”.

You can modify the conversion function (float() in this case) based on your specific needs, such as int() for checking integer inputs.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply