[英]Can't break out of a while loop
我正在寫一個糟糕的基於文本的冒險,我無法弄清楚如何打破這個循環。 我會嘗試在這里發布相關的東西。 如果我的評論沒有充分解釋我正在嘗試做什么,請告訴我。
chained = 1
finished = 0
# home() and club() act as rooms in the game
def home():
while chained == 1:
# there's a way to unchain yourself that works
chained = 0
while chained == 0:
print 'your are in the room'
input = raw_input('> ')
if 'exit' in input or 'leave' in input or 'club' in input:
current_room = 'club'
break
def club():
print "this works"
# These sort of move you around the rooms.
# current_room keeps track of what room you're in
current_room = 'home'
while finished == 0:
if current_room == 'home':
home()
if current_room == 'club':
club()
預期的行為是我將“退出”或“離開”或“俱樂部”輸入到輸入中,home()函數將結束,並且club()函數將啟動。 實際發生的是終端只是繼續打印“你在房間里”,並不斷給我輸入。
如果我必須的話,我會發布完全未刪節的代碼,但我不願意,因為實際的冒險並不完全......專業。
什么break
正在打破home()
函數中的循環。 因此,當它破裂時,它將回到開頭
while finished == 0:
並將繼續重復這一輸入。
你必須在home()
(和club()
)之后提供break
:
while finished == 0:
if current_room == 'home':
home()
break
if current_room == 'club':
club()
break
順便說一句,你的代碼非常混亂。 雖然循環不應該用於這樣的事情(除非你試圖獲得exit
或leave
的輸入)
你也可以擺脫最后的循環。
我認為你需要讓current_room
成為一個全局變量。 因為home()
的變量current_room
和while finished
的變量具有不同的范圍。
以下是我想要實現的目標。 查看python變量范圍
chained = 1
finished = 0
current_room = 'home'
# home() and club() act as rooms in the game
def home():
global chained
# without the following line current_room has local scope and updating its value will not be
# reflected in the while at the end
global current_room
while chained == 1:
# there's a way to unchain yourself that works
chained = 0
while chained == 0:
print 'your are in the room'
input = raw_input('> ')
if 'exit' in input or 'leave' in input or 'club' in input:
current_room = 'club'
break
def club():
print "this works"
# These sort of move you around the rooms.
# current_room keeps track of what room you're in
while finished == 0:
if current_room == 'home':
home()
if current_room == 'club':
club()
雖然我從來沒有真正理解代碼對於這個有效的解決方案的意義。 您還沒有聲明變量是全局變量還是本地變量,為什么在使用簡單的if-else語句時會使用循環
chained = 0
finished = 0
# home() and club() act as rooms in the game
def home():
global chained,current_room
if chained == 1:
# there's a way to unchain yourself that works
chained = 0
if chained == 0:
print 'your are in the room'
input = raw_input('> ')
if 'exit' in input or 'leave' in input or 'club' in input:
current_room = 'club'
club()
# Not sure if finished is a local or global variable
def club():
global finished,current_room
print "this is messy code!!"
# These sort of move you around the rooms.
# current_room keeps track of what room you're in
current_room = 'home'
if finished == 0:
if current_room == 'home':
home()
if current_room == 'club':
club()
home()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.