[英]Python while loop inside while loop does not break
這是一個井字游戲。 在本節中,function 檢查板上是否有未填充的單元格(第一個 while 循環,它工作),然后檢查 o 是否贏了(第二個 while 循環,它工作)。
如果 o 贏了,它會中斷循環並打印“yey o”。 檢查 x 是否贏了也是一樣,第三個循環也可以工作,只是當它中斷時,它將“恭喜 x”打印到無窮大。
我嘗試在第二個循環的級別上添加一個 break 語句(如“x won so break x, break o”)但沒有成功。我做錯了什么?
def place_marker():
while any(isinstance(x, int) for x in board):
while not win_check_o():
while not win_check_x():
# does stuff
else:
print("congrats x")
break
else:
print("yey o")
break
print(board)
break
語句僅從其包含循環中退出。 如果在內循環中有兩個嵌套循環和一個break
語句,您將 go 回到外循環。
while True:
while True:
break
print('This will repeat forever.')
要修復它,請將您的循環放入函數中並使用return
語句。
break
只從一個循環中中斷。 您應該將您的邏輯扁平化為一個循環 - 您可以制作一些布爾值並標記它們以記住完全爆發(非常糟糕的風格):
a, SomeOtherCondition, thatCondition, SomeThing = True, True, True, True
# contrieved bad example
while a and SomeOtherCondition:
while a and thatCondition:
while a and SomeThing:
a = False
print("Breaking")
break
# any code here will be executed once
print("Ops")
# any code here will also be executed once
print("Also ops")
輸出:
Breaking
Ops
Also ops
最好構造你的代碼並扁平化你的循環:
def any_tile_left(board):
return any(isinstance(x, int) for x in board)
def win_check(who, board):
conditions = [(0,1,2),(3,4,5),(6,7,8), # horizontal
(0,3,6),(1,4,7),(2,5,8), # vertical
(0,4,8),(2,4,6)] # diagonal
for c in conditions:
if all(board[i] == who for i in c):
return True
return False
def print_board(board):
for row in range(0,9,3):
print(*board[row:row + 3], sep = " ")
whos_turn = "X"
boardrange = range(1,10)
board = list(boardrange)
while True:
print_board(board)
try:
pos = int(input(whos_turn + ": Choose a tile? "))
except ValueError:
print("impossible move. ", whos_turn, "is disqualified and lost.")
break
if pos in boardrange and str(board[pos-1]) not in "XO":
board[pos-1] = whos_turn
if win_check(whos_turn, board):
print(whos_turn, " won.")
break
whos_turn = "O" if whos_turn=="X" else "X"
else:
print("impossible move. ", whos_turn, "is disqualified and lost.")
break
if not any_tile_left(board):
print("Draw")
break
它應該適用於井字游戲。 小心不要輸入不可能的東西,否則你會松懈。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.