Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how to only accept numbers as a input

mark= eval(raw_input("What is your mark?"))
try:
    int(mark)
except ValueError:
    try:
        float(mark)
    except ValueError:
        print "This is not a number"

So I need to make a python program that looks at your mark and gives you varying responses depending on what it is.

However I also need to add a way to stop random text which isn't numbers from being entered into the program.

I thought I had found a solution to this but it won't make it it past the first statement to the failsafe code that is meant to catch it if it was anything but numbers.

So pretty much what happens is if I enter hello instead of a number it fails at the first line and gives me back an error that says exceptions:NameError: name 'happy' is not defined.

How can I change it so that it can make it to the code that gives them the print statement that they need to enter a number?

like image 899
noel pearce Avatar asked Oct 31 '25 14:10

noel pearce


1 Answers

remove eval and your code is correct:

mark = raw_input("What is your mark?")
try:
    int(mark)
except ValueError:
    try:
        float(mark)
    except ValueError:
        print("This is not a number")

Just checking for a float will work fine:

try:
    float(mark)
except ValueError:
    print("This is not a number")
like image 120
Padraic Cunningham Avatar answered Nov 03 '25 07:11

Padraic Cunningham