【问题标题】:learn python the hard way exercise 35 help艰难地学习python练习35帮助
【发布时间】:2011-03-14 15:12:42
【问题描述】:

由于某种原因,当游戏进入黄金房间时,它无法正常运行。当我输入任何数字时,我都会收到死亡信息“伙计,学习输入数字”

谢谢

from sys import exit

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 how to type a number')


    if how_much < 50:
        print 'nice! your not too greedy. you win!'
        exit(0)
    else:
        dead('you greedy bastard!')


def bear_room():
    print 'there is a bear here.'
    print 'the bear has a bunch of honey'
    print 'the fat bear is in fromt of another door'
    print 'how are you going to move the bear?'
    bear_moved = False


    while True:
        next = raw_input('> ')

        if next == 'take honey':
            dead('the bear looks at you then pimp slaps you in the face')
        elif next == 'taunt bear' and not bear_moved:
            print 'the bear has moved from the door now. you can go through.'
            bear_moved = True
        elif next == 'taunt bear' and bear_moved:
            dead('the bear gets pissed off and chews your crotch off')
        elif next == 'open door' and bear_moved:
            gold_room()
        else:
            print 'i have no idea what that means.'


def bolofumps_room():
    print 'here you see the great evil bolofump'
    print 'he, it whatever stares at you and you go insane'
    print 'do you flee for your life or eat your head?'

    next = raw_input('> ')
    if 'flee' in next:
        start()
    elif 'head' in next:
        dead('well, that was tasty!')
    else:
        bolofumps_room()

def dead(why):
    print why, 'good job!'
    exit(0)


def start():
    print 'you are in a dark room'
    print 'there is a door to your left and right'
    print 'which one do you take?'

    next = raw_input('> ')

    if next == 'left':
        bear_room()
    elif next == 'right':
        bolofumps_room()
    else:
        dead('you stumble around the room until you starve to death')


start()

编辑:输入 1 有效,但 2 无效

【问题讨论】:

  • 在gold_room函数的if语句前加上print next会得到什么输出?
  • @GWW 它打印我输入的数字,然后进入死亡信息
  • 这很令人困惑,为什么 if how_much

标签: python


【解决方案1】:

你在gold_room

next = raw_input('> ')
if '0' in next or '1' in next:
    how_much = int(next)
else:
    dead('man, learn how to type a number')

它只检查'0' in next or '1' in next,所以'2'不起作用并不奇怪,对吧?

你想要的都是这样的

next = raw_input('> ')
try:
    how_much = int(next)
except ValueError:
    dead('man, learn how to type a number')

在没有例外的情况下这样做也是可能的,但请记住,避免像例外一样重要和基本的事情是一个非常糟糕的主意。我希望这本书以后至少能说明这一点。

无论如何,所以我们知道int 只接受数字,所以我们只需检查一下:

if next.isdigit():
    how_much = int(next)

【讨论】:

  • 哦,是的,额外的信用是这样说的:gold_room 有一种奇怪的方式让您输入数字。这种方式的所有错误是什么?你能做得比只检查数字中是“1”还是“0”更好吗?看看 int() 如何寻找线索。
  • 但我怀疑我是否打算使用 try,因为这本书甚至还没有涉及到这一点
【解决方案2】:

如果您考虑一下本教程中您现在应该知道的内容,其中包括

  • 解析参数
  • 读取用户输入
  • 使用 if/loop/while,
  • 函数,
  • 打印
  • 列表及其具体功能

您不能使用捕捉错误或使用“isdigit()”等神奇功能。

通过尝试另一个示例,我发现在字符串上使用“排序”可以分隔所有字符,我将在这里使用它。

我的想法是,我对数字的定义将是“一个仅包含 0 到 9 字符的字符串”。足够锻炼的需要了。

所以我的方法是从输入中删除所有数字并检查它是否结束为空。如果是这种情况,它是一个int,否则如果有剩余的字符,它不是。

def remove_all_occurences(char_list, item):
    value = "%d" % item  # convert to string
    while char_list.count(value) != 0:
        char_list.remove(value)
    return char_list


def is_int(input):
    """Personnal function to test if something is an int"""
    # The sort separates all the characters of the list
    characters_list = sorted(input)

    for num in range(0,10):
        characters_list = remove_all_occurences(characters_list, num)
    return len(characters_list) == 0

【讨论】:

    【解决方案3】:

    我可能会遗漏一些东西,但这就是我改变它的方式。代码少,运行良好。

    Def gold_room():
           Print("This room is full of gold. How much do you take?")
    
           choice = input('  ')
           next = int(choice)
           If next > 50:
                dead("Man, learn to type a number.")
           else:
                 print("your not greedy. Good job!")
                 exit(0)
    

    【讨论】:

    • 不知道为什么它没有从def开始,即使我在发布时将它放在盒子里。
    【解决方案4】:

    next 是一个内置的 Python 函数,因此您应该避免在它之后命名变量...可能不是问题的原因,但请尝试更改该变量的名称。

    【讨论】:

    • The documentation 不同意你的观点。
    • 您之前在回答中提到了“关键字”。并且某种类型的内置函数不会阻止他使用该名称。但是,应该更改以避免混淆。
    • 不只是为了避免混淆......如果它恰好没有被定义(作为变量),或者如果您确实需要使用next()并且将其用作改为变量...例如,您永远不会使用 int 作为变量名,尽管您可以...
    【解决方案5】:

    我对数字 Extra Credit 的解决方案检查输入的字符是否是像 cladmi 一样的整数,但会检查每个字符以查看它是否是整数(通过可能过于钝的布尔运算 - 只需检查它是否在'123456789'),将布尔值记录在一个列表中,然后使用 and 运算符进入此列表,如果所有字符都在,则返回 True。我对这一切都很陌生。我认为它相当新颖,仅使用我们目前所学的知识,它可能对其他陷入 Neil 问题的人有所帮助:

    def is_integer(input):
        bool_list = [] # to hold the b
        truth = True 
        for i in input: 
            # tests if i is an integer, records the boolean in bool_list
            bool_list.append(i in str(range(0, 10)) and i != " " and i != ",")
        for t in bool_list: 
            truth = truth and t # 'adds' each boolean in bool_list 
        return truth # True if all are integers, False if not.
    

    【讨论】:

      【解决方案6】:

      我个人在 gold_room 函数中做了这个。这将有助于您放置的任何范围。我希望这不会过期。

      元素 = [ ] 对于范围内的 i (0, 61): 元素.append(i) 下一个 = int(raw_input("> ")) 如果元素中的下一个: how_much = int(下一个) 其他:

      【讨论】:

        【解决方案7】:

        我浪费了几天时间认真思考如何解决这个问题以获得额外的功劳。我阅读了可以为我解决这个问题的两种不同的东西:异常和 isdigit。起初,我决心在不学习任何新东西的情况下弄清楚如何解决这个问题,只使用我们在书中所涵盖的内容以及我可以从 pydoc 中挤出的关于 int 的信息。我想出了一个解决方案,其中包含大量令人费解的列表、循环、布尔值和等等等等,最终它有 60 行长,而且绝对令人头疼。我心想,如果 Zed 看着这段代码并将其与我最终得到的结果进行比较,他会对这段代码有什么看法。我认为这里的一些人,也许包括我自己,能够想出复杂的、创造性的和创造性的方法来解决这个问题,因为解决问题显然对我们来说是一项必要的技能,然而,这个乱七八糟的代码与我现在认为的他所得到的代码相比是不费吹灰之力的。你认为他打算让你浪费大量时间写一些丑陋且难以理解的东西吗?或者,根据我们听到他说的内容,你认为他宁愿你只用 3 或 4 行非常简单易读的代码寻找一种方法来以一种整洁的方式完成它吗?我最终对此感到满意:

        def gold_room():
            print "This room is full of gold! How much do you take?"
            try:
                next = float(raw_input(">"))
            except ValueError:
                dead("Man, learn to type a number.")
            if (next) < 50:
                print "Nice, you're not greedy, you win!"
                exit(0)
            elif(next) >= 50:
                dead("You greedy bastard!")
        

        任何东西都可以在其中工作,并且不会搞砸。只需自己学习新事物即可。

        【讨论】:

          【解决方案8】:

          我也使用了 try 和 except 语句,但我认为您不需要在 (next) 周围加上括号。您也可以只使用 else 代替 elif 来保持代码更简洁。

          def gold_room():
          print "This room is full of gold! How much do you take?"
          try:
              next = float(raw_input(">"))
          except ValueError:
              dead("Man, learn to type a number.")
          if next < 50:
              print "Nice, you're not greedy, you win!"
              exit(0)
          else:
              dead("You greedy bastard!")
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2015-05-01
            • 2013-04-06
            • 2011-12-04
            • 2016-06-28
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-05-16
            相关资源
            最近更新 更多