0

I am just trying to code a very simple tictactoe. the variable titled ‘one’ in the function called updategrid is the one giving me trouble.


gamestate = "playing"
playerturn = "x"
one = "1"
two = "2"
three = "3"
four = "4"
five = "5"
six = "6"
seven = "7"
eight = "8"
nine = "9"

def showgrid():
    print(f'{one}|{two}|{three}')
    print("_____")
    print(f'{four}|{five}|{six}')
    print("_____")
    print(f'{seven}|{eight}|{nine}')
    
def updategrid():
    if playerinput == "1":
        one = playerturn
        
        
while gamestate == "playing":
    if playerturn == "x":
        showgrid()
        playerinput = input("which place would you like to go in")
        updategrid()

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Your updategrid function has a local variable assigned `one`. I think this is why. There's a keyword called `global` to let your function know about the global variables. – jkim Dec 21 '21 at 02:02
  • 3
    If you assign to a variable in a function, that variable is local by default, even if there is a global variable of the same name. If you want to use the global one, put `global myvarname` in the function. – John Gordon Dec 21 '21 at 02:11
  • 2
    Please clarify "giving me trouble". What exactly happens differently than what you expect? – OneCricketeer Dec 21 '21 at 02:18
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Dec 28 '21 at 13:13

1 Answers1

0

It looks like your issue is that you are expecting 1 to change to x in the grid after running the program and inputting 1 in the first round.

In order to change the value of a global variable from inside a function, you need to use the global keyword before assigning a new value to the variable.

def updategrid():
    global one
    if playerinput == "1":
        one = playerturn

After the above change, the program behaves as I think you are hoping it to:

enter image description here

You'll likely need a lot of global statements if you are going to continue in this way and it is not generally considered great practice so you might want to think about how you can rethink the task to limit those global statements.

ljdyer
  • 1,946
  • 1
  • 3
  • 11