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

random.choice(MAP) sometimes returns NoneType

There seems to be a problem while trying to take a random value from MAP. http://pastebin.com/5W6vjawH

Chris Freeman
Chris Freeman
Treehouse Moderator 68,468 Points

Can you explain why you assert this? Is an error raised? or is it perhaps the value of player, monster, or door happen to be NoneType? Which is not the same thing as random.choice() being the cause.

It doesn't always happen but sometimes randomly when i start the game it does and that's why i assume it has something to do with random.choice(). An exception is raised and only the player is NoneType, but both the door and the monster variable's values are assigned properly.

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

I was able to reproduce the error. In the function start_position at ①, if player, monster, or door have the same value, start_position() is called but the return values are not captured at ②. The function then ends and a None is returned. Fix by returning the values at ②.

def start_position():
    player = random.choice(MAP)
    monster = random.choice(MAP)
    door = random.choice(MAP)

    # check to see if they occupy the same space
    if player == monster or door == monster or door == player:  # ①
        start_position()  # ②
    else:
        return player, monster, door

Thank you sir!