-1

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()
Barmar
  • 741,623
  • 53
  • 500
  • 612
Hiebs915
  • 666
  • 1
  • 7
  • 22
  • You should read that link and some more about the [scope of variables in Python](https://www.google.com/search?q=python+variable+scope). Your problem is that the `first_player` is defined inside `choose_first_player()` and therefore isn't accessible elsewhere. – Pranav Hosangadi Oct 20 '20 at 16:07
  • Yes, it does answer my question, thanks! I guess when I was trying to google an answer I didn't know I was looking for "Scope". That explains everything. Thank you again. – Hiebs915 Oct 20 '20 at 18:29

1 Answers1

1

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

AlexisG
  • 2,476
  • 3
  • 11
  • 25