Python Forum
How to test if an input is any number?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to test if an input is any number?
#1
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.
Reply
#2
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)?
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Oh...
I had a different error in my code that prevented the is_number from being utilized properly, sorry.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Checking the number of input Chrilo06 3 2,026 Mar-14-2022, 07:31 PM
Last Post: deanhystad
  Divide a number - Multiple levels - Sum of all numbers equal to input number pythoneer 17 8,846 Apr-20-2018, 04:07 AM
Last Post: pythoneer
  User input only takes the last number Austin11 16 8,079 Nov-28-2017, 11:20 PM
Last Post: Prrz

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020