This is probably an easy problem to solve but I'm having a bit of difficulty. The error is UnboundLocalError: local: "switch" and that's all the error says. The line refers to the line switch = - switch in the following code:

boundary = game.getBoundary()

level = 1
maxX = -1
maxItem = 0
minX = boundary.getWidth()+1
minItem = 0
change = 0
switch = 1

class shootCollisionListener (events.CollisionListener):
    global switch
    def __init__ (self, item):
        self._item = item
    def collisionDetected(self, event):
            switch = -switch

I used global so I don't know why I'm getting this error.

When variables are assigned inside a function, they are always bound to the function's local namespace. The global namespace is never checked for name switch, therefore the error.

>>> switch = -1
>>> def test():
... 	return -switch
>>> switch = test()
>>> switch
>>> def test1():
... 	switch = -switch
... 	return switch
>>> test1()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "<interactive input>", line 2, in test1
UnboundLocalError: local variable 'switch' referenced before assignment
>>> def test2():
... 	global switch
... 	switch = -switch
... 	return switch
>>> test2()
>>> test2()

The local namespace of a method doesnt see the namespace of the class. Inside a method, you can only access the variables from the local namespace and the variables defined at module level. So your global switch is misplaced.

This article has been dead for over six months. Start a new discussion instead.