1

I am trying to validate a user input, and the user input is required to be positive integers including floating point numbers. I tried with isdigit(), it validated all the non-numeric inputs and negative integers as well but could not validate the floating point numbers. Below is my code

 def is_number(s):
     while (s.isdigit() == False):
       s = input("Enter only numbers, not less than 0 : ")
 return float(s)

#method call

 while('true'):
      membershipFee = is_number(input('Enter the base membership fee, or zero to quit: '))
              

4 Answers4

1

You can try the conversion and catch any errors. If python's happy, you're happy.

def is_number(s):
    while True:
        try:
            retval = float(s)
            if s >= 0.:
                return s
        except ValueError:
            pass
        s = input("Enter only numbers, not less than 0 : ")
tdelaney
  • 73,364
  • 6
  • 83
  • 116
0

If you want to use isdigit(), you can't use it on a float. One possible solution is to use a regex to validate your floats.

Using isdigit for floats?

jreiss1923
  • 464
  • 3
  • 11
0

You can try to do something like this:

#check if there is only one decimal place and check if it is not negative
s = input('Enter the number :')
if s.replace('.','',1).isdigit() and '-' not in s:
    print ('OK to process')
else:
    print ('not OK to process')

This will ensure that you will have the kind of numbers you need.

Joe Ferndz
  • 8,417
  • 2
  • 13
  • 33
0

You should try this

def isNumber(f):
    return all([p.isdigit() for p in [f[:f.find('.')], f[f.find('.')+1:]] if len(p)])

print(isNumber('12.543'))
print(isNumber('185'))
print(isNumber('.2341'))
print(isNumber('163.'))
print(isNumber('14.356.67'))
Kuldip Chaudhari
  • 1,112
  • 4
  • 8