Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Ian McGlory
Ian McGlory
1,997 Points


I've been scratching my head trying to get draw map to work. All I get back is an error:

UnboundLocalError: local variable 'output' referenced before assignment.

Below is some of my code which for the sake of the question I've only replicated the necessary bits.

import random

CELLS = [(0,0), (1,0), (2,0), (3,0), (4,0),
         (0,1), (1,1), (2,1), (3,1), (4,1),
         (0,2), (1,2), (2,2), (3,2), (4,2),
         (0,3), (1,3), (2,3), (3,3), (4,3),
         (0,4), (1,4), (2,4), (3,4), (4,4),

def get_locations():
    return random.sample(CELLS, 3)

monster,door,player = get_locations()
def draw_map(player):
    print(" _"*5)
    tile = "|{}"
    for cell in CELLS:
        x, y = cell
        if x<4:
            line_end = ""
            if cell == player:
                output = tile.format("X")
            line_end = "\n"
            if cell == player:
                output = tile.format("X|")
                output = tile.format("_|")
        print(output, end = line_end)        


From what I know, the code is telling me that output is being referenced before it's being assigned to a value. However, this is just about verbatim from what I saw in the video. What am I doing wrong?

1 Answer

You need to assign output before using it in your for loop.

def draw_map(player):
    output = ""

Assign it within the function, before the for-loop.