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

Lauren Gainsbrook
Lauren Gainsbrook
12,539 Points

Number game - calling a function from within itself

I'm working on creating this number game (guess the computer's number) with my own little touches. I've created a function that prompts the user to enter 'y' or 'n' based on whether they want to play again. Since I've added a few extra things (like a "give up" option), I want to call this function in a few different places. Within the function, I want to have an option to start the function again if the user doesn't enter 'y' or 'n' (for example, if they enter 'yes' or something totally wrong). This is the "else:" at the bottom... but I get an error when I run it (it appears to be going back into the game() function). Is there a way I can call the function from within itself?

def play_again():
    play_again = raw_input("Would you like to play again? Enter 'y' for yes, 'n' for no.")
    if play_again.lower() == 'y':
        print "Alright! Let's get started!"
        game()
    elif play_again.lower() == 'n': 
        print "Thanks for playing. Have a nice day!"
    else: 
        print "Error: please enter 'y' to play again or 'n' to quit."
        play_again()

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

Choose variable names carefully. This line

    play_again = raw_input("Would you like to play again? Enter 'y' for yes, 'n' for no.")

overwrites the function play_again with a string assigned to the variable play_again

Change the variable name to something like

    response = raw_input("Would you like to play again? Enter 'y' for yes, 'n' for no.")
Lauren Gainsbrook
Lauren Gainsbrook
12,539 Points

Haha, wow so simple!!! Thanks!