如果Python中的isinstance语句为True但它没有通过

时间:2016-06-18 21:00:25

标签: python python-2.7 input

我正在努力从“艰难学习Python”一书中获得额外的练习35。根据之前评论中提供的建议(learn python the hard way exercise 35 help),我尝试了两种方法:

from sys import exit

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

    next_move = raw_input("> ")
    if isinstance(next_move, int):
        how_much = int(next_move)
    else:
        dead("Man, learn to type a number.")


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

我的问题是:if isinstance...行永远不会通过!它总是被跳过。我总是得到Man, learn to type a number(即使我输入一个数字)。

我确实成功完成了以下代码:

next_move = raw_input("> ")
char = list(str(next_move))
for v in char:
    if v in str(range(0, 10)) and v != " " and v != ",":
        how_much = int(next_move)
    else:
        dead("Man, learn to type a number.")

但是,我想了解为什么第一个选项不起作用:(

1 个答案:

答案 0 :(得分:0)

原始输入将是一个字符串,因此测试失败是正常的。更加pythonic的方法是:

next_move = raw_input("> ")
try:
    how_much = int(next_move)
except ValueError:
    dead("Man, learn to type a number.")