除了 'try...except' 和 '.isdigit()' 之外,还有其他方法可以检查 Python 2 中的用户输入吗? [英] Is there a way other than 'try...except' and '.isdigit()' to check user input in Python 2?

查看:50
本文介绍了除了 'try...except' 和 '.isdigit()' 之外,还有其他方法可以检查 Python 2 中的用户输入吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试通过 Learn Python The Hard Way 学习 Python 2.7,但有一个关于 练习 35 的练习 5.

I am currently trying to learn Python 2.7 via Learn Python The Hard Way, but have a question about Study Drill 5 of Exercise 35.

我正在查看的代码是:

choice = raw_input("> ")
if "0" in choice or "1" in choice:
    how_much = int(choice)
else:
    dead("Man, learn to type a number.")

学习练习询问是否有比检查数字是否包含 0 或 1 更好的方法,并查看 int() 如何为线索工作.

The study drill asks if there is a better way than checking if the number contains zero or one, and to look at how int() works for clues.

我显然希望能够在解除字符串时接受用户给出的任何数字,并且我理解 int() 转换了 raw_input() 中给出的内容变成一个数字.

I obviously want to be able to accept any number given by the user while dismissing strings, and I understand that int() converts what was given in raw_input() into a number.

因此,我尝试了几种修改 if 语句的方法,该语句在键入字符串时会抛出致命错误,但一直在努力寻找合适的方法.我尝试了以下代码的变体,现在明白为什么它们不起作用了:

So, I tried a couple of ways of amending the if statement which threw up fatal errors when typing a string, but struggled to find anything suitable. I tried variations of the following code, and now understand why they don't work:

choice = int(raw_input("> "))

if choice > 0:

搜索后,我发现了 这个答案有两种方法可以解决这个问题,但是 try...except.isdigit() 不是书中提到的.

After searching SO I discovered this answer which gives two ways to solve the problem, however try...except and .isdigit() aren't something mentioned in the book at this point.

是否有其他方法可以实现接受用户输入,必要时将其转换为整数,如果不适合本书的这一阶段,则返回错误?

Is there any other ways to achieve taking user input, converting it to an integer if necessary, and returning an error if not that is appropriate for this stage of the book?

推荐答案

所以,首先阅读 jonrsharpe 在评论中链接的内容 接受 try-except 是最好的方法.

So, firstly read what jonrsharpe linked to in the comments and accept that try-except is the best way of doing this.

然后考虑整数意味着什么:

Then consider what it means to be an integer:

  • 一切都必须是数字(也不能有小数点)

这就是您要检查的内容.你希望一切都是数字.

So that's what you check for. You want everything to be a digit.

因此,对于 represents_integer(string) 函数:

for every letter in the string:
    check that it is one of "0", "1", "2", ..., "9"
    if it is not, this is not a number, so return false

if we are here, everything was satisfied, so return true

请注意,检查是其中之一 可能需要另一个循环,尽管有更快的方法.

Note that the check that is is one of might require another loop, although there are faster ways.

最后,考虑 "",它在此方法(或 GregS')中不起作用.

Finally, consider "", which won't work in this method (or GregS').

这篇关于除了 'try...except' 和 '.isdigit()' 之外,还有其他方法可以检查 Python 2 中的用户输入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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