首页 > 解决方案 > 尽管 Python 中没有说明这样的条件,但控制流正在退出 while 循环

问题描述

有编码经验,但对 python 不熟悉,正在尝试使用 python 制作井字游戏。直到现在我还不知道如何在 jupyter notebook 中调试。因此,寻求一些帮助以了解我在这里做错了什么。

下面是我的代码:

    while game_on:
         player1 = input('Enter the choice for player1(X/O):')
         if player1.upper() == 'X':
             print("Player 1 will go first and choice made is 'X'")
             player1_turn = True
             player2 = 'O'
         else:
             print("Player 1 will go first and choice made is 'O'")
             player1_turn = True
             player2 = 'X'
         while player1_turn:
             display_board(board)
             position = int(input("player1: Enter the position where you want to place an 'X' or 'O'(1-9):"))
             board[position] = player1.upper()
             list1.append(position)
             player1_turn = False
             player2_turn = True 
             player_win = win(board)
             if player_win:
                display_board(board)
                player1_turn = False
                player2_turn = False
                game_st = input('Would you like to play another game(y/n):')
                if game_st.upper() == 'Y':
                    game_on = True
                else:
                    game_on = False
             break  
         else:
             display_board(board)
             position = int(input("Player2: Enter the position where you want to place an 'X' or 'O' (1-9):"))
             board[position] = player2.upper()
             list1.append(position)
             player1_turn = True
             player2_turn = False

当我正在执行我的代码并且控件在第二个语句(以粗体标记)之后进入内部 while 循环的“else”部分时,控件将自动转到外部 while 循环的第一个语句(以粗体标记) ,尽管它应该回到内部的while循环以再次轮到玩家1。

请指导和帮助理解。非常感谢 MK

标签: pythonwhile-loopcontrolsbreakflow

解决方案


您的代码的问题是(我认为!)您将其else用作 while 循环的一部分。仅当第一次不满足 while 循环的条件时,python 中的 while 循环中的 else 语句才会执行。当你进入,然后break它不会执行。尝试以下操作以查看行为:

while True:
    print("Runs!!!")
    break
else:
    print("Doesn't???")

while False:
    print("But this doesn't!!!")
    break
else:
    print("And this does???")

请注意,在第一种情况下,while 块中的 print 运行,而在第二种情况下,只有 else 块运行。

在您的情况下,您可能想要做一些不同的事情,而不是使用 else 语句。也许玩家 2 的第二个 while 循环会起作用?我不想过多地指导你应该如何做,但如果它有帮助,我可以编辑给出一个工作示例。


推荐阅读