Python how to only accept numbers as a input

守給你的承諾、 提交于 2019-12-02 08:24:50

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"

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)]

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"

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)

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().

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