Noughts And Crosses game loop iterating too many times

Question:

This is my noughts and crosses code i am still early on in making it and I am trying to do it as independently as possible without too much help from google- this is a simple question but why is it that when you get 3 in a row within the 2d list that the loop I have made continues to iterate one last time before ending? thanks a lot

    won = False

    sum = 0
    for i in range (3):
        if grid[i][i] == "X":
            sum +=1
        elif grid[i][i] == "O":
            sum -=1
    if sum == 3 or sum == -3:
        won = True

    sum = 0
    for i in range (3):
        if grid[row][i] == "X":
            sum +=1
        elif grid[row][i] == "O":
            sum -=1
    if sum == 3 or sum == -3:
        won = True

    sum = 0
    for i in range (3):
        if grid[i][column] == "X":
            sum +=1
        elif grid[i][column] == "O":
            sum -=1
    if sum == 3 or sum == -3:
        won = True    

    return won



#############################main program#############################  
grid = [["-","-","-"],
        ["-","-","-"],
        ["-","-","-"]]
for x in grid:
    print (x)

win = False

while win == False:
    print("nCrossesn")
    column = int(input("Enter a Columnn"))
    row = int(input("Enter a Rown"))
    grid[row][column] = ("X")
    for x in grid: print (x)
    win = checkwin(grid, row, column)
    print("nNoughtsn")
    column = int(input("Enter a Columnn"))
    row = int(input("Enter a Rown"))
    grid[row][column] = ("O")
    for x in grid: print (x)  
    win = checkwin(grid, row, column)```


Asked By: Jojo

||

Answers:

After your check whether last placed X made the player win, you don’t exit the loop in any case (the while loop condition is only checked when an iteration starts, not all the time) – the program always continues and allows O player to move, even if win is already true. To change that behaviour, you need to break from the loop if the X player won, using break keyword. Your loop would look like this:

while win == False:
    print("nCrossesn")
    column = int(input("Enter a Columnn"))
    row = int(input("Enter a Rown"))
    grid[row][column] = ("X")
    for x in grid: print (x)
    win = checkwin(grid, row, column)
    if win:
        break
    print("nNoughtsn")
    column = int(input("Enter a Columnn"))
    row = int(input("Enter a Rown"))
    grid[row][column] = ("O")
    for x in grid: print (x)  
    win = checkwin(grid, row, column)
Answered By: BlackAnubis7
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.