为什么代码只在Python中不在函数中时才起作用?

2024-05-14 16:10:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我认为这是一个全局或局部错误,但我不明白

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

在这里它不起作用:

    # 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

它在这里工作:

    # 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


错误在哪里

致意


Tags: orandboardifcount错误npcol
1条回答
网友
1楼 · 发布于 2024-05-14 16:10:14

除非return指定值,否则在函数内赋值不会起任何作用。尝试此版本的函数,其中返回player的中奖值:

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

然后让调用者将其分配给其自身范围内的player

    # 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

这段代码可能还有其他问题,但希望至少能澄清函数返回值的工作原理

相关问题 更多 >

    热门问题