0

我正在尝试用 Python 构建一个刽子手游戏,如果用户输入他们已经尝试过的字母,我已经将其设置为重复输入功能。但出于某种原因,“猜测”变量存储了我尝试的每一个值,我很困惑为什么会发生这种情况。我只希望它存储最新的输入。这是代码:

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

和输出(作为一个注释,第一个'a'被预加载以测试'if'语句):

>>> 
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']
>>> 

print 语句显示似乎涉及多个值。谁能解释为什么会这样?我觉得我一定遗漏了一些明显的东西。非常感谢!

4

1 回答 1

1

像这样递归地调用自己是一个坏主意。最终你会得到一个例外。处理这个问题的正确方法是while循环

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
于 2013-03-15T06:30:37.740 回答