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

Audrey Watson
Audrey Watson
3,790 Points

If I wanted to add an exit option, would I create a new method or add an elif in the check_location or start_game method

If I wanted to add an option for the user to exit the memory game, would I create a new method called exit_game or could I put it in the start_game or check_location method?

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

Hey Audrey Watson, there are multiple ways to implement an exit option.

The key point is to exit gracefully. This might be done by setting game_running to False. Since game_running is local to the start_game method, putting in the option to exit in that method seems most logical. The “enter to continue” input could be checked for alternative (non-enter) values and set game_running to False.

An exit_game method would not be strictly needed. However, if you wished to place addition clean up code in such a method, then the exit could be called from multiple locations. If this method forced the program to end, it would not matter if game_running was changed since the program execution would not be returning to the while loop.

Using sys.exit() is a standard way to exit.

import sys


sys.exit()

If an exit_game is created to “clean up” and exit, one idiom I like to add is catching keyboard interrupts (Cntr-c in Linux). This would allow calling the exit method if the user hits Cntr-c anytime during execution.

If __name__ == "__main__”:
    game = Game()
    try:
        game.start_game()
    except KeyboardInterrupt:
        # call clean up
        game.exit_game()

Exiting from the check_location could work as well. If an invalid or empty guess is received then the user could be asked if they wish to quit, which could then call the exit_game method.

Alternatively, the check_location return value could be set to None to indicate an exit is requested. Then not guess1 or not guess2 could be used to call exit_game.

Any or all of the above would work. There isn’t a perfect correct answer. Perhaps play around with various combinations to see which you like best.

Please post back what on what you decide! I’m curious what you go with. Good Luck!!