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")
但它在第一次尝试后直接给我留言......
我正在搜索这个论坛,没有找到满意的答案,请帮帮我
答案 0 :(得分:5)
尝试
if len(yrs) < 5:
print yrs
else:
die("you tried many times")
而不是。条件
yrs < 5
始终返回false,因为yrs
是一个列表,您将它与整数进行比较。这意味着永远不会执行while yrs < 5
循环,因为条件yrs < 5
永远不会成立。你的程序跳过这个循环并调用die()
函数,这使它立即退出。这就是为什么你应该将die
放在条件语句中的原因,就像上面的代码片段一样。
请注意,如果您改为写道:
while len(yrs) < 5:
print yrs
这也是不正确的,因为条件len(yrs) < 5
在第一次检查时会评估为True
,所以你最终会陷入一个无限循环,用户将无法在提供条件len(yrs) < 5
所依赖的任何输入。
您希望将yrs
&#39> 长度与if
语句中的5进行比较(如上所述)以查看用户是否尝试次数超过5.如果它们不超过5,则在重复外部if choice in tools
循环之前,代码流应继续进行最终检查(while
...),以便启用用户再次尝试。
答案 1 :(得分: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!'