Search code examples
pythonfunctionglobal-variables

Why does the code only works when it's not in a function in Python?


I think its a global or local error but I dont get it.

def who_wins_when_player_3(player):
    if player == 3:
        amount_triangles = np.count_nonzero(board == 3)
        if amount_triangles == 3 or 5 or 7:
            player = 2
        else:
            player = 1

here it doesn't work:

    # vertical win check
    for col in range(BOARD_COLS):
        if board[0][col] == player and board[1][col] == player and board[2][col] == player or board[3][col] == player and board[1][col] == player and board[2][col] == player:
            who_wins_when_player_3()
            print(f"Player {player} wins")
            return True

here it works:

    # vertical win check
    for col in range(BOARD_COLS):
        if board[0][col] == player and board[1][col] == player and board[2][col] == player or board[3][col] == player and board[1][col] == player and board[2][col] == player:
            if player == 3:
                amount_triangles = np.count_nonzero(board == 3)
                if amount_triangles == 3 or 5 or 7:
                    player = 2
                else:
                    player = 1
            print(f"Player {player} wins")
            return True


where is the error?

Best regards


Solution

  • Assigning a value inside the function doesn't do anything unless you return the value. Try this version of the function where the winning value of player is returned:

    def who_wins_when_player_3(player):
        if player == 3:
            amount_triangles = np.count_nonzero(board == 3)
            if amount_triangles == 3 or 5 or 7:
                return 2
            else:
                return 1
        return player  # if we don't do this, the function will return None if player != 3
    

    and then have the caller assign it to player within its own scope:

        # vertical win check
        for col in range(BOARD_COLS):
            if board[0][col] == player and board[1][col] == player and board[2][col] == player or board[3][col] == player and board[1][col] == player and board[2][col] == player:
                player = who_wins_when_player_3(player)  # pass player in and reassign it
                print(f"Player {player} wins")
                return True
    

    There may be other problems with this code, but this hopefully at least clarifies how returning a value from a function works.