繁体   English   中英

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

[英]Control flow is coming out of while loop though no such condition is stated in 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 循环的第一条语句(以粗体标记) ,尽管它应该返回内部 while 循环以再次轮到玩家 1。

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

您的代码的问题是(我认为!)您将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 循环会起作用? 我不想指导您应该如何做太多,但如果有帮助,我可以编辑以提供一个工作示例。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM