Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Collections (2016, retired 2019) Dungeon Game Win or Lose

Jacob Keeley
Jacob Keeley
2,033 Points

How to handle input error?

I recreated the Dungeon Game, following from the videos but implemented a way for the player to choose the size of the square board.

def board(): 
    cells = []
    while True:
        try:
            n = int(input('Specify board size with a single integer:')) 
        except ValueError:
            print("That's not an integer!")
            continue
        else:
            for y in range(1, n+1):
                for x in range(1, n+1):
                    cells.append((x,y))
            break 
    return n, cells

board_size, board_cells = board()

It works well and using the try and except function I've managed to avoid issue with non-integer inputs.

However, this does not handle the error thrown when the player inputs "1", specifying the 1x1 board that would force the monster, player, and door to be on the same square. How can I fix that?

1 Answer

Ken Alger
STAFF
Ken Alger
Treehouse Teacher

Jacob;

Nice feature. You could certainly use an if statement to check input to force a minimum board size.

Ken

Jacob Keeley
Jacob Keeley
2,033 Points

Thanks, Ken. I thought that'd be the way to go and had been trying to implement it in the try block to no avail. I've since modified the else block, instead.

else:
        if n == 1:
            n = int(input('Please pick a number greater than 1: '))
        for y in range(1, n+1):
            for x in range(1, n+1):
                cells.append((x,y))