Python Forum

Full Version: How to test if an input is any number?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
This isn't a required part of a program, but I wanted to learn how to do this so I don't break my program everytime I input an incorrect value. I tried using
def is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False
but this code does not work for negative numbers. How could I test if a user input is ANY number?
such as testing if a is a number where a=input("Type a number here: ")
currently, if the input is -1 I have no way of checking if that's a number.
Works for me:

>>> def is_number(s):
...     try:
...         float(s)
...         return True
...     except ValueError:
...         return False
...
>>> is_number(-2)
True
>>> is_number('-2')
True
>>> is_number('-2.71828')
True
>>> is_number(input('Enter a number: '))
Enter a number: -25823.8289
True
>>> is_number("Bob")
False
What exactly is the number that won't work? What happens when your try float() on that number (without the try/except)?
Oh...
I had a different error in my code that prevented the is_number from being utilized properly, sorry.