【问题标题】:My while loop is repeating over and over again我的while循环一遍又一遍地重复
【发布时间】:2012-11-29 09:45:16
【问题描述】:

它引用一个有 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

【问题讨论】:

    标签: python while-loop


    【解决方案1】:

    您的while 语句始终返回真值,因为or 'X' 始终计算为True。首先,评估board[computer] == '0',如果False,则继续到or 的右侧,即字符串X。您的代码中其他地方的这种模式确实是正确的,所以我怀疑这只是一个疏忽。

    相反,您必须包括布尔比较的两边:

    while board[computer] == 'O' or board[computer] == 'X':
    

    或者更好,你可以使用in

    while board[computer] in ['O','X']:
    

    或者,由 cmets 中的 @icktoofay 提供,惯用语:

    while board[computer] in 'OX':
    

    您的counter 必须在循环外初始化为0,而不是在循环内重新初始化。

     # initialize outside the loop
     counter = 0
     while board[computer] == 'O' or 'X':
        # Don't re-initialize to 0 in the loop
    

    【讨论】:

    • 甚至是'OX',而不是['O','X']。
    • @icktoofay 是的 - 我的 Python 生锈了,我总是忘记这一点。
    • 感谢您这么快回复迈克尔!但是在做出改变之后(你发布的第一个)它没有修复它,它仍然在寻找一个开放的地方:(
    • 还有一个问题是在检查它是否大于15之前立即将计数器设置为零。当然,它永远不会大于15。
    • @user1861771 这是因为您的计数器设置在循环内。把它移到外面。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-16
    • 1970-01-01
    相关资源
    最近更新 更多