Tic Tac Toe 函数未正确定义变量

Tic Tac Toe function not defining variable correctly

我正在构建一个 Tic Tac Toe 游戏作为 Python 介绍课程的练习,我正在参加 Udemy。我现在构建了一系列功能,但我无法让其中两个一起工作。当我 运行 这两个函数时,我收到一条错误消息,指出 first_player 未定义。但是,first_player 是在第一个函数中定义的。有谁知道为什么 Python 无法识别第二个函数中的 first_player 是什么?

如果这些功能正常工作,如果 he/she 想成为 X 或 O,然后让 Python 将 X 或 O 分配给玩家 1 和玩家 1,我希望它作为第一个玩家.

choose_first player() 中,我尝试打印出 first_player 变量并且打印正确。

我使用的代码如下:

#Randomly chooses which player goes first.
def choose_first_player():
    import random
    first_player = (str(random.randint(1,2)))

    if first_player == '1':
        print("\nPlayer " +first_player+ " goes first.")
    if first_player == '2':
        print("\nPlayer " +first_player+ " goes first.")

choose_first_player()

#Asks first_player if they want to be X's or O's.
def player_input():

    marker = ''

    while marker != 'X' and marker != 'O':
        marker = input("\nPlayer" +first_player+ " , do you want to be X's or O's?  Please enter X or O: ").upper()

    player1 = marker

    if player1 == 'X':
        player2 = 'O'
    else:
        player2 = 'X'
        player1 = 'O'

    print("\nPlayer 1 is: " + player1)
    print("Player 2 is: " + player2)
    return(player1,player2)

player_input()

您不能访问另一个函数的变量。 (或者你必须将其定义为全局变量)

choose_first_player 可以 return first_player 的值,然后你可以将它传递给其他函数。

然后做这样的事情:

def choose_first_player():
    ...
    return first_player

first_player = choose_first_player()

... 

def player_input(first_player):
  ...

player_input(first_player)

在这里你可以阅读更多关于python scopes