-1

I want to check if the input is a number(float with 0,one or two decimals) and greater than 0

def getnumber():
    print ( "write a number: \n")
    isValid = False
    while not isValid:
        try:
            number = float(raw_input().replace(",","."))
            if number >= 0:
                isValid=True
            else:
                print ("Number not valid")
                isValid = False
                getnumber()
        except:
            print ("Number not valid")
    return number

I have the following problems:

1- I don't know how to check if there are only two decimals

2- The code doesn't return the number if first I introduce a negative number

Does anyone know how to fix it?

Thanks a lot

Jessica
  • 1
  • 1

1 Answers1

1

The reason why your code isn't working with negative numbers is because the function calls itself recursively when the number is negative, but the value of isValid is always false after that call, so the loop repeats.

There isn't really any need for the Boolean variable.

That leaves you with the issue of detecting two decimal places. In order to be able to do that at string level you would have to retain the string that you converted to a floating-point number. Supposing you store it as s you could use some test like len(s) > 3 and s[-3] == '.'` to verify it.

This would give you a solution like:

def getnumber():
    while True:
        try:
            s = raw_input("Write a number:").replace(",",".")
            number = float(s)
            if number >= 0 and len(s) > 3 and s[-3] ==".":
                return number
            else:
                print("Negative or not two decimal places")
        except Exception:
            print("Invalid number")

print(getnumber())
holdenweb
  • 33,305
  • 7
  • 57
  • 77
  • And of course you could split the test up if you wanted different error messages for negative numbers and wrong number of places. – holdenweb Jun 15 '16 at 17:11
  • Though why use a `try...except` at all? This doesn't bring anything to the invalid number detection and may hide other Exceptions that should be handled explicitely instead. – zezollo Jun 15 '16 at 17:28
  • Ups, sorry. I didn't explain myself well. If a number has 0,1 or 2 I want to return the number. I guess that code doesn't check it. It was my fault. Sorry – Jessica Jun 15 '16 at 17:32
  • @Jessica then you should explicitely write something like `except ValueError:` to catch only the errors related to the nature of the input. You shouldn't use bare `except:` clauses, it will lead you to ununderstandable errors and endless headaches! – zezollo Jun 15 '16 at 17:45
  • I used `except Exception` because I wanted to catch even unanticipated errors, though still allowing things like `KeyboardInterrupt` through. It would almost certainly be better to use `except ValueError`. I agree that a bare `except` is _exceptionally_ bad practice – holdenweb Jun 15 '16 at 18:06