Python how to only accept numbers as a input

…衆ロ難τιáo~ 提交于 2019-11-28 12:26:28

问题


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?


回答1:


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"



回答2:


You can simply cae to float or int and catch the exception (if any). Youre using eval which is considered poor and you add a lot of redundant statements.

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

"Why not use eval?" you ask, well... Try this input from the user: [1 for i in range (100000000)]




回答3:


you can use the String object method called isnumeric. it's more efficient than try- except method. see the below code.

def getInput(prompt):
    value = input(prompt)
    while not value.isnumeric():
        print("enter a number")
        value = input("enter again")
    return int(value)



回答4:


import re

pattern = re.compile("^[0-9][0-9]\*\\.?[0-9]*")

status = re.search(pattern, raw_input("Enter the Mark : "))

if not status:

        print "Invalid Input"



回答5:


Actually if you going to use eval() you have to define more things.

acceptables=[1,2,3,4,5,6,7,8,9,0,"+","*","/","-"]
try:
    mark= eval(int(raw_input("What is your mark?")))
except ValueError:
    print ("It's not a number!")
if mark not in acceptables:
    print ("You cant do anything but arithmetical operations!")

It's a basically control mechanism for eval().



来源:https://stackoverflow.com/questions/27516093/python-how-to-only-accept-numbers-as-a-input

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!