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

编程入门 行业动态 更新时间:2024-10-07 14:33:27
本文介绍了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如何只接受数字作为输入

本文发布于:2023-11-28 08:12:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641616.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数字   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!