jou*_*ral 1 python while-loop nested-loops
好我即时学习python和我试图制作这种文本游戏而且我坚持在循环中......我想要做的是有可以使用的东西列表,并将用户的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
Run Code Online (Sandbox Code Playgroud)
但是选择没有被添加到列表中yrs,它只使用一个while循环但是它会永远或者直到工具列表中的一个项目作为用户输入输入,但是id喜欢将其限制为5次尝试然后输入:die("You tried too many times")
但它在第一次尝试后直接给我留言......我正在搜索这个论坛,没有找到满意的答案,请帮助我
尝试
if len(yrs) < 5:
print yrs
else:
die("you tried many times")
Run Code Online (Sandbox Code Playgroud)
而不是.条件
yrs < 5
Run Code Online (Sandbox Code Playgroud)
总是返回false,因为它yrs是一个列表,你将它与一个整数进行比较.这意味着while yrs < 5循环永远不会执行,因为条件yrs < 5永远不会成立.你的程序跳过这个循环并调用该die()函数,这使它立即退出.这就是为什么你应该放入die一个条件语句,就像上面的代码片段一样.
请注意,如果您改为写道:
while len(yrs) < 5:
print yrs
Run Code Online (Sandbox Code Playgroud)
这也是不正确的,因为条件len(yrs) < 5将True在第一次检查时进行评估,因此您将最终处于无限循环中,在该循环中用户将无法提供任何输入,其长度len(yrs) < 5将取决于条件.
你会希望比较yrs的长度以5在if声明(如上文写的),看看如果用户的尝试都超过5个.如果他们不超过5码流应该去到最后的检查(if choice in tools... )在重复外while循环之前,为了使用户能够再次尝试.
| 归档时间: |
|
| 查看次数: |
248 次 |
| 最近记录: |