-2

I'm writing a Tic Tac Toe AI and have a problem with a function that I want to define. It can be simplified to something like:

z = True
X = 1
y = 2

def place(X,y):
    if z = True:
        if X == 1:
            x = y

(please note, I made some of my x'es capital just to make it easier to differentiate them for this post). The problem here is that I need to assign the value of y to X, but in the "x=y" statement, I'm given an error that x is a local variable not used, like if the x in that IF statement is local only to that IF statement, and is not connected.

A test with it showed that after the function was run, the X was unchanged, and printed the old value. No error is given in the function before that, only the one marked as x is local. What can I do to fix this so that x and X actually share values?

I have tried making go through other variables, but that didn't work. I have tried to use the global function on a value to lead it through, but that didn't work either.

hjundaj
  • 9
  • 1
  • 2
  • 1
    If you mean "How do I assign to a global variable inside a function?", then the answer is to use a `global` statement. See http://stackoverflow.com/questions/4693120/use-of-global-keyword-in-python – khelwood Mar 29 '17 at 08:23
  • Also `if z = True:` is invalid syntax. – khelwood Mar 29 '17 at 08:25

3 Answers3

1

Your 'x' is local since it is first defined locally. Define it globally and mark it global. That is,

z = True
X = 1
x = None
y = 2

def place(X,y):
    global x
    if z = True:
        if X == 1:
            x = y
Frank-Rene Schäfer
  • 3,182
  • 27
  • 51
1

If you want to access global variables from inside a function you should use the keyword global so the function knows where to find this variables.

z = True
X = 1
y = 2

def place(X,y):
    global z, X, y
    if z = True:
        if X == 1:
            x = y
Carles Mitjans
  • 4,786
  • 3
  • 19
  • 38
0

You have a typo here:

if z = True:

It should be

if z == True: