首页 > 解决方案 > 如何修复Python中的重复while循环

问题描述

我正在尝试使用 while 循环在两个用户之间交替轮换,但我的代码卡在“while first_player_move is True:”循环中。我怎样才能解决这个问题,让我的 while 循环遍历两个玩家的回合。

我尝试在不同的地方添加“继续”和“中断”,并尝试向上切换布尔值,但似乎没有任何效果。

word_fragment = ''
        first_player_move = True
        while True:
            while first_player_move is True:
                added_letter = input('Which single letter would you like to add to the fragment? ')
                word_fragment += added_letter
                print('The current word fragment is: ' + word_fragment)
                print('It is now ' + player2_name + "'s turn.")
                if word_fragment in open('data.txt').read() and len(word_fragment) > 3:
                    print('I am sorry, you just lost. ' + player2_name + ' is the winner!')
                    # call a function to end the game
                    break

            while first_player_move is False:
                added_letter = input('Which single letter would you like to add to the fragment? ')
                word_fragment += added_letter
                print('The current word fragment is: ' + word_fragment)
                print('It is now ' + player1_name + "'s turn.")
                if word_fragment in open('data.txt').read() and len(word_fragment) > 3 :
                    print('I am sorry, you just lost. ' + player1_name + ' is the winner!')
                    # call a function to end the game
                    break

我希望输出贯穿每个玩家的回合并最终打印“现在是'下一个玩家'的回合”,但它会继续为下一个玩家回合打印相同的名称,这告诉我代码卡在了两个 while 循环中的第一个。

标签: pythonpython-3.xwhile-loop

解决方案


由于first_player_move不改变为false,当内部循环结束时,外部开始一个新的循环并再次调用内部。

顺序流是:

  1. 进入第一个循环 => True#如此真实
  2. 进入内循环 => first_player_moveis True# so true
  3. 然后执行内部块breaks并进入第一个循环并重复上述步骤

  4. 进入第一个循环 => True#如此真实

  5. 进入内循环 => first_player_moveis True# so true

推荐阅读