Search code examples
pythontic-tac-toe

Tic Tac Toe function not defining variable correctly


I'm building a Tic Tac Toe game as practice for an intro-to-Python course I'm taking on Udemy. I have a series of functions built right now but I can't get two of them to work together. When I run these two functions I get an error saying the first_player is undefined. However, first_player is defined in the first function. Does anyone know why Python won't recognize what first_player is in the second function?

If these functions work correctly I'd expect it to as the first player if he/she wants to be X's or O's and then have Python assign X's or O's to player 1 and player 1.

In the choose_first player() I've tried printing out the first_player variable and it prints correctly.

The code I'm using is below:

#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()

Solution

  • You can't access the variable of another function. (or you have to define it as a global variable)

    choose_first_player can return the value of first_player and then you can pass it to the other function.

    And do something like this :

    def choose_first_player():
        ...
        return first_player
    
    first_player = choose_first_player()
    
    ... 
    
    def player_input(first_player):
      ...
    
    player_input(first_player)
    

    Here you can read more on python scopes