Search code examples
pythonsyntax-errorglobal-variables

Why is this a syntax error? Is there a way of returning both the variables when using onscreen click?


This is a python program in 3.10 and I need a separate x and y variable to use for my function which so I can place the noughts /crosses where they need to go. I have tried returning it as one two then split later but it doesn't actually store anything. my plan was then to set them a s global variables but it says it is a syntax error. I am still learning to code and don't understand why. also if there is a way of returning them what is it.

def which(hx,hy):
    if (hx > -54 and hx < -21) and (hy >43 and hy < 75):
        place=0
    elif (hx > -22 and hx < 19) and (hy >43 and hy < 75):
        place=1
    elif (hx > 20 and hx < -54) and (hy >43 and hy < 75):
        place=2
    elif (hx > -54 and hx < -21) and (hy > 3 and hy < 41):
        place=3
    elif (hx > -22 and hx < 19) and (hy >3 and hy < 41):
        place=4
    elif (hx > 20 and hx < -54) and (hy >3 and hy < 41):
        place=5
    elif (hx > -54 and hx < -21) and (hy > -37 and hy < 1):
        place=6
    elif (hx > -22 and hx < 19) and (hy > -37 and hy < 1):
        place=7
    elif (hx > 20 and hx < -54) and (hy > -37 and hy < 1):
        place=8
    return place

def seperate(x,y):
    global cx = x # this is the problem(it highlights the = red)
    global cy = y

onscreenclick(seperate)
print(cx)
print(cy)
h=which(cx,cy)
n(h)

Solution

  • def seperate(x,y):
        global cx = x # this is the problem(it highlights the = red)
        global cy = y
    

    Change to

    def seperate(x,y):
        global cx 
        cx= x # this is the problem(it highlights the = red)
        global cy
        cy = y
    

    You are declaring a variable as global and assigning it a value at the Same time. Python wants you to declare variables global, then you can assign values to it.

    W3school-Python global variables