2015-07-20 141 views
0

我有以下的代码:如何确定原始输入是一个整数还是不是在python中?

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

好像if "0" in choice or "1" in choice被用来确定原始输入的选择是否是整数或没有。为什么?我只是有点好奇。非常感谢您的时间和关注。

编辑。这似乎是一个类似的问题已经存在。见How to check if string input is a number?。非常感谢以下不同的答案。我很好奇的是:为什么我们可以使用如果选择“0”或选择“1”来确定原始输入是否是python中的数字。

+2

看起来像是试图检查int()调用是否成功或产生错误。但是,它将无法捕获像''0qwer''这样的无效输入。只需使用'try..except'构造就容易了。 – TigerhawkT3

回答

1
#!python 
try: 
    choice = raw_input("> ") 
except (EnvironmentError, EOFError), e: 
    pass # handle the env error, such as EOFError or whatever 
try: 
    how_much = int(choice) 
except ValueError, e: 
    dead("Man, learn to type a number.") 

它也可以这样来包围输入和转换过程在一个更复杂的try:块:

#!python 
try: 
    choice = int(raw_input('> ')) 
except (ValueError, EOFError, EnvironmentError), e: 
    dead('Man, learn to type a number') 
    print >> sys.stderr, 'Error: %s' % e 

...这里我也显示出使用捕获异常对象的一种方式以显示与该异常相关的特定错误消息。 (也可以用更高级的方式使用这个对象......但是这对于简单的错误处理就足够了)。

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

无法检测到很多数字,如23

How do I check if a string is a number (float) in Python?可以帮到你。

+1

如果选择'a0bc'会怎么样? – ozgur

+0

@ozgur [我如何检查一个字符串是否是一个数字(浮点数)在Python?](http://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is- a-number-float-in-python)显示了很多解决方案。 – letiantian

+1

但你的不是解决方案。 – ozgur

0

您可以使用isdigit()函数。

choice = raw_input("> ") 
if choice.isdigit(): 
    how_much = int(choice) 
else: 
    dead("Man, learn to type a number.") 
相关问题