Search code examples
pythonvariablespython-idlelocal-variablesraw-input

In Python IDLE 2.7, why is raw_input storing multiple values?


I'm trying to build a hangman game in Python, and I've set it repeat the input function if the user inputs a letter they've already tried. For some reason though, the "guess" variable stores every single value that I try, and I'm confused why this is happening. I only want it to store the most recent input. Here's the code:

def inputGuess(lettersGuessed):

    guess = raw_input("What is your guess? ")
    guess = guess.lower()
    if guess in lettersGuessed:
        print "You've already guessed that. Try again!"
        inputGuess(lettersGuessed)
    print guess
    return guess

And the output (as a note, the first 'a' was pre-loaded to test the 'if' statement):

>>> 
Loading word list from file...
55900 words loaded.
The secret word has 8 letters!
Available letters: bcdefghijklmnopqrstuvwxyz
What is your guess? a
You've already guessed that. Try again!
What is your guess? a
You've already guessed that. Try again!
What is your guess? a
You've already guessed that. Try again!
What is your guess? f
f
a
a
a
['a', 'a']
>>> 

The print statement shows that multiple values seem to be involved. Can anyone explain why this is happening? I feel like I must be missing something obvious. Thanks so much!


Solution

  • Calling yourself recursively like that is a bad idea. Eventually you'll get an exception. The proper way to handle this is a while loop

    def inputGuess(lettersGuessed):
        while True:
            guess = raw_input("What is your guess? ")
            guess = guess.lower()
            if guess in lettersGuessed:
                print "You've already guessed that. Try again!"
            else:
                break
        print guess
        return guess