Robin Andrews
Robin Andrews

Reputation: 3794

Python UnboundLocalError: local variable referenced before assignment

I'm confused. What is different about player1_head compared to the other variables I am printing in the code below? As far as I can tell it should behave the same as the others - it's declared in the global scope, no? I don't think it's a typo.

UnboundLocalError: local variable 'player1_head' referenced before assignment

from turtle import *
from random import randint
from utils import square, vector

player1_xy = vector(-100, 0)
player1_aim = vector(4, 0)
player1_body = []
player1_head = "It looks like I'm assigning here."

def draw():
    "Advance player and draw game."
    print("xy: ", player1_xy)
    print("head: ", player1_head)
    print("body: ", player1_body)
    player1_xy.move(player1_aim)
    player1_head = player1_xy.copy()
    player1_body.append(player1_head)
    square(player1_xy.x, player1_xy.y, 3, 'red')
    update()
    ontimer(draw, 200)

setup(420, 420, 370, 0)
hideturtle()
tracer(False)

draw()
done()

Upvotes: 0

Views: 8947

Answers (2)

cdlane
cdlane

Reputation: 41872

Because you failed to declare player1_head as a global, in the draw() function it appears to that function that you're printing out local variable player1_head before it has a value:

print("head: ", player1_head)
# ...
player1_head = player1_xy.copy()

Instead do:

def draw():
    """ Advance player and draw game. """

    global player1_head

    print("xy: ", player1_xy)
    print("head: ", player1_head)
    print("body: ", player1_body)
    player1_xy.move(player1_aim)
    player1_head = player1_xy.copy()
    player1_body.append(player1_head)

    square(player1_xy.x, player1_xy.y, 3, 'red')

    update()
    ontimer(draw, 200)

Upvotes: 2

Djaouad
Djaouad

Reputation: 22776

The assignment player1_head = player1_xy.copy() in the draw() function is saying to Python that the variable player1_head is a local variable to the function draw(), and since print("head: ", player1_head) is referencing a local variable before its assignment, the error is shown. You can fix this by using player1_head as a global variable (since you're modifying it, same goes for the variable player1_body, since you're doing player1_body.append(player1_head)), like so:

def draw():
    "Advance player and draw game."
    global player1_head
    #...rest of the code

Note however that you should avoid using global variables when possible, this is one the problems that arises from using them (they can be modified by any function, which can sometimes lead to errors and confusions).

Upvotes: 0

Related Questions