控制流从while循环中出来,尽管在Python中没有这样的条件

具有编码经验,但对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循环(以标记为in)的第一条语句粗体),尽管它应该返回并返回内部while循环以再次使玩家1转向。

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

Hilda_Chen 回答:控制流从while循环中出来,尽管在Python中没有这样的条件

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

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

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

请注意,在第一种情况下,运行while块中的打印,而在第二种情况下,仅运行else块。

在您的情况下,您可能想做一些不同的事情,而不是使用else语句。也许玩家2的第二次while循环会起作用?我不想说明您应该怎么做,但是如果有帮助,我可以编辑以给出一个可行的示例。

本文链接:https://www.f2er.com/3036848.html

大家都在问