Python循环多次检查

时间:2016-05-08 13:00:23

标签: python python-2.7

早上好,

只要其中一个row1check变量变为True,while循环就会停止?我希望循环保持循环,直到所有3个变量都为True。我正确使用循环吗?

def x_turn ():
global row1check
global row2check
global row3check
while (row1check == False) and (row2check == False) and (row3check == False):
    move = raw_input("Player X Enter coordinates 'row,col': ")

    row = move[0]
    column = move[2]

    if row == "1" and column == "1" and row1[0] == " ":
        row1[0] = "x"
        draw_matrix()
        check_game()
        end_game()
        o_turn()
    if row == "1" and column == "2" and row1[1] == " ":
        row1[1] = "x"
        draw_matrix()
        check_game()
        end_game()
        o_turn()
    if row == "1" and column == "3" and row1[2] == " ":
        row1[2] = "x"
        draw_matrix()
        check_game()
        end_game()
        o_turn()
    if row == "2" and column == "1" and row2[0] == " ":
        row2[0] = "x"
        draw_matrix()
        check_game()
        end_game()
        o_turn()
    if row == "2" and column == "2" and row2[1] == " ":
        row2[1] = "x"
        draw_matrix()
        check_game()
        end_game()
        o_turn()
    if row == "2" and column == "3" and row2[2] == " ":
        row2[2] = "x"
        draw_matrix()
        check_game()
        end_game()
        o_turn()

4 个答案:

答案 0 :(得分:1)

您可以使用all功能:

while not all([row1check, row2check, row3check]):

只有在所有这些都为真时才会停止。

答案 1 :(得分:0)

切换到or而不是and

while (row1check == False) or (row2check == False) or (row3check == False):

这种方式只有当所有3个条件都是True时才会停止循环。

P.S您还可以使用all

>>> data = [False, False, False]
>>> not all(data)
True

答案 2 :(得分:0)

你的while循环语法是对的。但根据您的要求,您应该使用:

while (row1check == False) or (row2check == False) or (row3check == False):

在此处使用or意味着只要满足上述任何条件,它就应该继续运行代码。也就是说,row1check,row2check或row3check中的任何一个都是false。

答案 3 :(得分:0)

你也可以像这样使用and运算符:

row1check = False
row2check = False
row3check = False

def x_turn():
    global row1check
    global row2check
    global row3check
    while not (row1check and row2check and row3check):
        print('Looping...')
        row1check = True
        row2check = True
        row3check = True

if __name__ == '__main__':
    x_turn()

当row1check,row2check,row3check都为True时停止while while循环。