Python如何只接受数字作为输入 [英] Python how to only accept numbers as a input

查看:55
本文介绍了Python如何只接受数字作为输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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.

因此,如果我输入 hello 而不是数字,它会在第一行失败并返回一个错误,内容为 exceptions:NameError: name 'happy' is未定义.

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?

推荐答案

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

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

只需检查浮动即可:

try:
    float(mark)
except ValueError:
    print("This is not a number")

这篇关于Python如何只接受数字作为输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆