学习Python艰难的方法,Ex35,练习5

时间:2015-07-24 17:24:44

标签: python

在LPTHW中,exercise 35的研究练习5要求:

  

gold_room有一种奇怪的方式让你输入一个数字......你能不能只检查数字中是否有“1”或“0”?看看int()如何为线索工作。

以下是相关的gold_room代码:

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

    next = raw_input("> ")
    if "0" in next or "1" in next:
        how_much = int(next)
    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!")

我尝试使用0到9的数字列表。不完全是“更好”的方式,但我想不出别的:

next = raw_input("> ")
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
if next in numbers:
    how_much = int(next)

与原始代码中的“0”和“1”一样,我希望每个数字都可以用作关键字。不幸的是,它不适用于9以上的任何数字。

我搜索了其他解决方案并找到了使用.isdigit()try:except ValueError:来解决问题的人,但是这本书尚未涵盖这些,所以我会喜欢避免使用它们。我正在寻找任何其他建议,特别是作者提到的int()。感谢。

[edit]:这已被标记为重复。这不是重复的。仔细阅读我的回答和问题;有警告。链接的答案使用try和其他我想避免的事情,因为它们尚未涵盖在本书中。

2 个答案:

答案 0 :(得分:0)

这可能对你有所帮助:

isanumber

这基本上会遍历next中的每个项目(作为一个字符),并且如果它找到不是数字的东西,它将停止for循环。如果是一个数字,for循环将一直进行,True仍然是numbers。如果其中包含非数字字符(通过检查该字符是否在isanumber中),则会将False设置为next,而无需再进行任何检查。

但请注意:{{1}}实际上是built-in function。拥有与内置函数同名的变量通常是一个坏主意。

答案 1 :(得分:0)

int()会在转换失败时抛出异常,因此您可以:

try:
    how_much = int(next)
except:
    dead("Man, learn to type a number.")

无需拥有要迭代的数字列表等。

编辑: 要明确这个功能,那就是:

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

    next = raw_input("> ")
    try:
        how_much = int(next)
    except:
        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!")