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! While you're at it, check out some resources Treehouse students have shared here.

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

Python

Igor Bochenek
Igor Bochenek
3,960 Points

Starting roguelike game

Hello i've got problem my code is working but now i wnt to add main function and when I run it after input terminal says File "warm_up.py", line 15, in print_board board = create_board(width, height) NameError: name 'width' is not defined i know that somewhere is problem but I cant figure it out.

def create_board(width, height):

board = []
counter = width - 2
for row in range(height):
    board.append([])
    for column in range(width):
        board[row].append("X")
for line in range(1, height - 1):
    board[line][1:-1] = ' ' * counter
return board

def print_board():

board = create_board(width, height)
for row in board:
    print("".join(row))

def main():

width = int(input("width: "))
height = int(input("height:"))

create_board(width, height)

print_board()

if name == "main": main()

1 Answer

Steven Parker
Steven Parker
231,269 Points

The print_board function has no access to the width and height.

In the main function you define width and height variables, which you pass to create_board. So far so good, but then you call print_board with no arguments but it then tries to call create_board and pass it those arguments again. But this time, it doesn't have those arguments and they are not globally available so you get the error.

Now you could make them global, or pass them to print_board. But it might be even better if you capture the board in main when you first create it, and then pass that to print_board. Then print_board could just print the board it was handed and not create a new one. I'd bet that's going to be more useful to you later when you start filling in the board and working with it.

Also please see the Markdown Cheatsheet link at the bottom of the "Add an Answer" section for instructions on how to format posted code. :arrow_heading_down: