2015-01-14 92 views
1

以及即时通讯学习蟒蛇和即时通讯尝试使这种文本游戏和即时通讯卡 on 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循环 但随后去去永远存在,直到工具列表中的项目之一输入为用户输入然而 ID喜欢它限制在5次尝试,然后用输入:die("You tried too many times") 但它给我死的消息第一次尝试后直... 我正在寻找这个论坛,没有找到令人满意的答案,请大家帮我

+2

这是无效的Python语法。修复代码的缩进。 –

回答

5

尝试

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

而不是while。条件

yrs < 5 

总是返回假的,因为yrs是列表,你比较它的整数。这意味着while yrs < 5循环从未执行,因为条件yrs < 5从来没有成立。您的程序跳过此循环并调用die()函数,该函数立即退出。这就是为什么你应该把die放在一个条件语句中,就像上面的代码片段一样。

请注意,如果你不是这样写道:

while len(yrs) < 5: 
    print yrs 

,这也将是不正确的,因为条件len(yrs) < 5将评估为True第一次被选中,所以你会在一个无限循环结束用户将不能提供任何输入,其条件len(yrs) < 5将取决于其长度。

你会想yrs长度if语句比较5(如上面写的),看看如果用户的尝试都超过5个。如果他们不超过5码流应该去到最后一次检查(if choice in tools ...),然后重复循环外部while,以便用户再次尝试。

0
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!'