我的while循环重复一遍又一遍

use*_*771 3 python while-loop

它正在引用一个具有9个插槽的游戏板,一旦插槽被填满## while循环在没有任何空位且我不知道如何修复它时继续搜索新的位置,请帮助!:(

        computer = random.randint(0, 8)
        if board[computer] != 'X' and board[computer] != 'O':
            print computer
            board[computer] = 'O'
        else:
            while board[computer] == 'O' or 'X':
                counter = 0
                if counter > 15:
                    break
                computer = random.randint(0, 8)
                print computer
                if board[computer] != 'X' and board[computer] != 'O':
                    board[computer] = 'O'
                counter += 1
Run Code Online (Sandbox Code Playgroud)

Mic*_*ski 6

您的while语句始终返回true值,因为or 'X'始终求值为True.首先,board[computer] == '0'评估,如果False,它进入右侧or,这只是字符串X.你的代码中的其他地方确实有这种模式,所以我怀疑这只是一种疏忽.

相反,您必须包含布尔比较的两侧:

while board[computer] == 'O' or board[computer] == 'X':
Run Code Online (Sandbox Code Playgroud)

或者更好,你可以使用 in

while board[computer] in ['O','X']:
Run Code Online (Sandbox Code Playgroud)

或者,@icktoofay在评论中的礼貌,惯用语:

while board[computer] in 'OX':
Run Code Online (Sandbox Code Playgroud)

counter必须初始化到循环0 外部,而不是在内部重新初始化.

 # initialize outside the loop
 counter = 0
 while board[computer] == 'O' or 'X':
    # Don't re-initialize to 0 in the loop
Run Code Online (Sandbox Code Playgroud)

  • 还有一个问题是,在检查它是否大于15之前立即将计数器设置为零.当然,它绝不会大于15. (4认同)