Python如何只接受数字作为输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27516093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:54:10  来源:igfitidea点击:

Python how to only accept numbers as a input

pythonpython-2.x

提问by noel pearce

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.

所以我需要制作一个 python 程序来查看你的标记并根据它的内容给你不同的响应。

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 helloinstead of a number it fails at the first line and gives me back an error that says exceptions:NameError: name 'happy' is not defined.

所以几乎发生的事情是,如果我输入hello而不是数字,它会在第一行失败并给我一个错误,上面写着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?

我怎样才能改变它,以便它可以使它成为代码,为他们提供他们需要输入数字的打印语句?

回答by Reut Sharabani

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

您可以简单地执行floatint捕获异常(如果有)。您正在使用被认为很差的 eval 并且您添加了很多冗余语句。

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

“为什么不使用 eval?” 你问,好吧......试试来自用户的这个输入:[1 for i in range (100000000)]

回答by Padraic Cunningham

remove eval and your code is correct:

删除 eval 并且您的代码是正确的:

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"

回答by GLHF

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

实际上,如果您要使用eval(),则必须定义更多内容。

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

它是eval()的基本控制机制。

回答by hariK

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"

回答by break-pointt

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

您可以使用名为 isnumeric 的 String 对象方法。它比 try-except 方法更有效。看下面的代码。

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