【问题标题】:python nested loop with break带break的python嵌套循环
【发布时间】:2015-03-12 14:37:26
【问题描述】:

我正在学习 python,我正在尝试制作这种文本游戏,但我被卡住了 在 while 循环中......我想做的是列出可以使用的东西,并将用户的 raw_input 与该列表进行比较,如果他们在 5 次尝试中选择了正确的,则继续,否则会因消息而死。 这是我的代码:

def die(why):
    print why
    exit(0)

#this is the list user's input is compared to
tools = ["paper", "gas", "lighter", "glass", "fuel"]
#empty list that users input is appended to
yrs = []
choice = None
print "You need to make fire"

while choice not in tools:
    print "Enter what you would use:"
    choice = raw_input("> ")
    yrs.append(choice)
    while yrs < 5:
        print yrs
        die("you tried too many times")
    if choice in tools:
        print "Well done, %s was what you needeed" % choice
        break

但是选择没有被添加到列表yrs,它只适用于一个while循环 但是它会永远消失,或者直到工具列表中的一项作为用户输入输入, 但是我喜欢将其限制为 5 次尝试,然后输入:die("You tried too many times") 但它在第一次尝试后立即给了我死亡信息...... 我正在搜索这个论坛,没有找到满意的答案,请帮助我

【问题讨论】:

  • 这不是有效的 Python 语法。修正代码的缩进。

标签: python while-loop nested-loops


【解决方案1】:

试试

if len(yrs) < 5: 
   print yrs
else:
   die("you tried many times")

而不是一会儿。条件

yrs < 5

总是返回 false,因为 yrs 是一个列表,而您正在将它与一个整数进行比较。这意味着while yrs &lt; 5 循环永远不会被执行,因为条件yrs &lt; 5 永远不会为真。你的程序跳过这个循环并调用die() 函数,这使它立即退出。这就是为什么你应该把die放在一个条件语句中,就像上面的sn-p代码一样。

请注意,如果您改为写:

 while len(yrs) < 5:
     print yrs

这也是不正确的,因为条件len(yrs) &lt; 5 在第一次检查时将评估为True,因此您最终会陷入无限循环,用户将无法提供任何输入,取决于条件len(yrs) &lt; 5 的长度。

您可能希望在if 语句(如上所述)中将yrs 的长度 与5 进行比较,以查看用户的尝试是否超过5。如果他们不超过大于 5 时,代码流应在重复外部 while 循环之前继续进行最终检查 (if choice in tools...),以使用户能够再次尝试。

【讨论】:

    【解决方案2】:
        from sys import exit
    
        def die(why):
            print why
            exit()
    
        tools = ["paper", "gas", "lighter", "glass", "fuel"]
        choice = ''
        tries = 0  
    
        print 'You have to make fire'
    
        while choice not in tools:
            choice = raw_input('What do you want to do?-->')
            tries += 1
            if tries == 5:
                die('You tried too many times')
    
         print 'Well done you made a fire!'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 2011-04-23
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 2017-04-24
      • 1970-01-01
      相关资源
      最近更新 更多