Frage

I apologise if this turns out to be a duplicate, but I couldn't find anything on this...

(Python 2.7.6)

In essense, I'm using variants of the code below:

def isnum(a):
    try:
        float(a)
        return True
    except ValueError:
        return False

that determines if the user input is indeed a number or not.

isnum(3)
True

isnum("3")
True

If I use the below code:

def input():
    while True:
        a = raw_input("Please enter a number:")
        if isnum(a):
            print float(a)
            break
        else:
            print "Please enter only numbers!",a,'is invalid'

input()

I'd also like to note that I tried isnum(a) == True as well...

I get an the 'enter only numbers' error when I input "3" when prompted!.

Please enter a number:"3"
Please enter only numbers! "3" is invalid

Thanks in advance.

War es hilfreich?

Lösung

"3" is a string containing 3. But when you send it to raw_input, it becomes '"3"' which is 3 surrounded by quotes, which is not a number.

Andere Tipps

You are giving "3" as input and not 3.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top