1

I've been trying to do an assignment for my python exam and I got stuck on this problem. I've listed the full code bellow. I set the variable A1 to " " and later down the line I want to use the function player1_move to change the variables accordingly to the user's input. However I get errors saying that A1 is mentioned before being set. I think that python recognizes A1 as a local variable within the definition (sorry if I'm saying gibberish but I can't describe it more accurately). How can I fix this error? Code:

A1 = ""
A2 = " "
A3 = " "
B1 = " "
B2 = " "
B3 = " "
C1 = " "
C2 = " "
C3 = " "

def board():
    print(f"""  1   2   3 
    A {A1}---{A2}---{A3}
      |\  |  /|
      | \ | / |
      |  \|/  |
     B {B1}---{B2}---{B3}
      |  /|\  |
      | / | \ |
      |/  |  \|
     G {C1}---{C2}---{C3}""")

board()
def player1_move(x):

    if x.title() == "A1":
        if A1 == " ":
            A1 = "x"
            board()
        else:
            print("This place is taken!" + "\nEnter another one!")

player1move1 = input("Player 1 moves first!" + "\nEnter your first move! :")
player1_move(player1move1)

Error:

Traceback (most recent call last):
  File "/home/noname/Documents/PythonProjects/Assignment/dummy_file1.py", line 34, in <module>
    player1_move(player1move1)
  File "/home/noname/Documents/PythonProjects/Assignment/dummy_file1.py", line 27, in player1_move
    if A1 == " ":
UnboundLocalError: local variable 'A1' referenced before assignment
hxrohxto
  • 13
  • 3
  • 2
    Yes; locality is determined when the function is defined, not as it is executed, so that the proper code can be generated. (Global names are accessed by name; local names are accessed by a precomputed index for speed.) – chepner Dec 14 '22 at 17:35
  • 1
    You shouldn't be using global variables in the first place. Represent a board using a list or some other data structure, and pass such a value to `board()` as an argument to format it. `player1_move`, likewise, should take a board and either update it in place or return a new updated board. – chepner Dec 14 '22 at 17:37
  • 1
    Assigning to a variable inside a function *always* makes a new variable. If you want to assign to a variable outside it use the `global` or `nonlocal` keywords. Note: Good python code simply avoids the need. – mousetail Dec 14 '22 at 17:37

1 Answers1

1

Add "global A1" to the top of your player1_move function.

Of course, the better way to do this would be to not use global variables at all. Make board a class.

Malcolm
  • 461
  • 2
  • 10