1
x = 0
y = 0
tx = 0
ty = 0

def setup():
    size(600, 600)
    noStroke()

def draw():
    background(0)
    textAlign(LEFT,TOP)
    # text("Hello World",x,y)
    tx=mouseX
    ty=mouseY
    f=0.01
    #The error: "UnboundLocalError: local variable 'x' referenced before assignment"
    x=lerp(x,tx,f)
    y=lerp(y,ty,f)

This is the processing python code. I am on Mac OSX High Sierra 10.13.1, using Processing 3.3.6 with Python Mode 3037.

This code gives "UnboundLocalError: local variable 'x' referenced before assignment" at the line immediately after the commented line in the code.

I am new to python and this seems to be what google says to do.

EDIT: Also, how would I reference global and instance variables in a class method?

martineau
  • 119,623
  • 25
  • 170
  • 301
mackycheese21
  • 884
  • 1
  • 9
  • 24

2 Answers2

2

To modify global variables from within a function, you need to use the global statement, like so:

def draw():
    global x, y, tx, ty
    background(0)
    ...

If you were using a class, your code would look like this:

class Drawer(object):
    def __init__(self):
        self.x = 0
        self.y = 0
        self.tx = 0
        self.ty = 0

    def setup(self):
        size(600, 600)
        noStroke()

    def draw(self):
        background(0)
        textAlign(LEFT, TOP)
        # text("Hello World",x,y)
        self.tx = mouseX
        self.ty = mouseY
        f = 0.01
        self.x = lerp(self.x, self.tx, f)
        self.y = lerp(self.y, self.ty, f)

d = Drawer()
d.setup()
d.draw()
Alex Hall
  • 34,833
  • 5
  • 57
  • 89
  • That seems kind of ackward to always have to use the global statement. Then how does this work for classes? – mackycheese21 Apr 19 '18 at 20:19
  • @mackycheese21 you can [use singleton](https://stackoverflow.com/questions/42237752/single-instance-of-class-in-python) – Sphinx Apr 19 '18 at 20:21
0

Should work ? I'm not into python, this is from someone else

x = 0
y = 0
tx = 0
ty = 0

def setup():
    size(600, 600)
    noStroke()

def draw():
    global x, y, tx, ty
    background(0)
    textAlign(LEFT,TOP)
    # text("Hello World",x,y)
    tx=mouseX
    ty=mouseY
    f=0.01
    x=lerp(x,tx,f)
    y=lerp(y,ty,f)