Python2,检查一个字符串是否只包含数字,与x.isdigit混淆()

问题描述:

查看了How do you check in python whether a string contains only numbers?,我知道string.isdigit()是测试一个字符串是否只包含数字而不是其他东西的有效方法。我正在使用Python 2.7。Python2,检查一个字符串是否只包含数字,与x.isdigit混淆()

但是,当我尝试在下面的代码中使用它时,当我输入数字和非数字的任意组合时,我的程序崩溃时出现“无效的int()基数为10的字面值”错误。 “fsd7sfd”或类似。 (该代码可以很好地处理数字字符串或仅字符串字符串。)

我不明白这是怎么发生的,因为据我所知,赋值为“how_much = int(choice) “应该不会发生,除非字符串只在第一位包含数字,而choice.isdigit()为True时。

有人可以帮我理解我错过了什么吗?作为一个侧面说明,该“打印”测试“”行似乎没有得到处理之前的错误,这增加了我的困惑。

(我试图提高从https://learnpythonthehardway.org/book/ex35.html的 “gold_room()” 功能,该代码的其余部分是有参考)

错误:

This room is full of gold. How much do you take? 
> sdfgsd8sd 
Traceback (most recent call last): 
File "ex35.py", line 79, in <module> 
start() 
File "ex35.py", line 71, in start 
bear_room() 
File "ex35.py", line 36, in bear_room 
gold_room() 
File "ex35.py", line 9, in gold_room 
how_much = int(choice) 
ValueError: invalid literal for int() with base 10: 'sdfgsd8sd' 

代码:

def gold_room(): 
    print "This room is full of gold. How much do you take?" 

    choice = raw_input("> ") 

    print "test" 

    if choice.isdigit() == False: 
     dead("Man, learn to type a number.") 

    else: 
     how_much = int(choice) 


    if how_much < 50: 
     print "Nice, you're not greedy, you win!" 
     exit(0) 

    else: 
     dead("You greedy bastard!") 
+0

此代码不能运行。如果我添加缺少的':',当我输入“fsd7sds”时,它会给我预期的'死'信息。 – AShelly

+0

这段代码对我来说可以正常使用这些冒号。由于'choice.isdigit()'返回一个布尔值,所以'else'永远不会运行。 – TemporalWolf

+0

谢谢你,你是对的,我忘记了我的冒号。也就是说,这段代码在没有它们的情况下确实运行,出乎意料的是,一旦我将它们添加进来,它就会给出相同的行为。= \ –

我不确定为什么这是失败的,但在我的猜测中,这样做的更pythonic方式是通过尝试除了语句来捕获值错误:

try: 
    #The following will fail with an non-numeric input 
    how_much = int(choice) 
except ValueError: 
    dead('Man, learn to type a number.') 
#Note that the else statement is not necessary as it will never execute anyway 
+0

谢谢;事实证明,我的实际问题与我最终试图测试的代码无关,但与我在做什么无关,这是一个有益的改进。 =) –

你需要做死功能脚本

def dead(message): 
    print(message) 
choice = raw_input("> ") 
print "test" 
if choice.isdigit() == False: 
    dead("Man learn to type a number") 
+0

提供了“dead()”函数,并在我正在使用的脚本的其他地方工作,我只是想突出显示似乎抛出错误的函数。不过谢谢。 –

+0

如果choice.isdigit()==假: –

+0

使用带有'tab'按钮的空间,请不要忘记:':' –