我正在学习Python,下面是一个python游戏函数,它包含一个while循环,但是这个循环是一个无限循环,我无法理解它是如何工作的以及它应该如何工作。
任何人都可以帮我解释一下while循环的含义,以及“bear_move = False”变量和循环条件“WHILE TRUE”之间的关系是什么。我在这里循环构造和条件时无法理解这一点,并且这个while循环条件与之相关。
def bear_room():
print "There is a bear here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
bear_moved=False
while True: #What is this while loop means here
next=raw_input("You should write take honey or taunt bear: >")
if next=="take honey":
print "The bear looks at you then pimp slaps your face off."
elif next=="taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved=True
elif next=="taunt bear" and bear_moved:
print "The bear gets pissed off and chews your crotch off."
elif next=="open door" and bear_moved:
gold_room()
else:
print "I got not I dea what that means."
答案 0 :(得分:3)
你的if
不在循环中,在python中,缩进很重要:
def bear_room():
print "There is a bear here."
print "The bear has a bunch of honey."
print "The fat bear is in front of another door."
print "How are you going to move the bear?"
bear_moved=False
while True: #What is this while loop means here
next=raw_input("You should write take honey or taunt bear: >")
# here you have to move all your block to the
# right, so it would be inside the while loop
if next=="take honey":
print "The bear looks at you then pimp slaps your face off."
elif next=="taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved=True
elif next=="taunt bear" and bear_moved:
print "The bear gets pissed off and chews your crotch off."
elif next=="open door" and bear_moved:
gold_room()
else:
print "I got not I dea what that means."
基本上它是什么,它在无限循环中读取输入并根据此操作执行一些操作。您可以在循环中添加exit
命令,以便随时退出:
if next=="take honey":
print "The bear looks at you then pimp slaps your face off."
elif next=="taunt bear" and not bear_moved:
print "The bear has moved from the door. You can go through it now."
bear_moved=True
elif next=="taunt bear" and bear_moved:
print "The bear gets pissed off and chews your crotch off."
elif next=="open door" and bear_moved:
gold_room()
elif next=="exit":
break # exit from cycle
else:
print "I got not I dea what that means."
答案 1 :(得分:1)
while True: #What is this while loop means here
while True
是一个无限循环。经常使用这些循环。如果您编写这样的循环,则必须检查每次迭代,游戏是否已达到手动停止的条件。您可以使用关键字break
从内部停止循环。有关python
在您的代码中,您可能希望在这一点上休息一下:
elif next=="open door" and bear_moved:
gold_room()
break
因此,如果门打开并且熊已移动,则循环将结束。