Python 我能';我无法使代码正确循环

Python 我能';我无法使代码正确循环,python,while-loop,raw-input,Python,While Loop,Raw Input,我如何才能让这段代码工作,这样用户就可以在函数中输入他们的猜测,直到他们正确地猜出整个单词,或者不再有生命了?现在,用户只能输入一个字符串,然后循环突然结束 secret_words_list = ['voldemort', 'hogwarts'] def hangman(): lives = 5 while lives >= 0: answer = random.choice(secret_words_list) guess = raw

我如何才能让这段代码工作,这样用户就可以在函数中输入他们的猜测,直到他们正确地猜出整个单词,或者不再有生命了?现在,用户只能输入一个字符串,然后循环突然结束

secret_words_list = ['voldemort', 'hogwarts']  
def hangman():
    lives = 5
    while lives >= 0:
        answer = random.choice(secret_words_list)
        guess = raw_input('Write your answer here: ')
        hangman_display = ''
        for char in answer:
            if char in guess:
                hangman_display += char
                lives -= 1
            elif char == ' ':
                hangman_display += char
            else:
                hangman_display += "-"
                lives -= 1
        if hangman_display == answer:
            print("You win")
    print(hangman_display) 
我不明白你的确切要求,但这就是你要找的吗

节目的互动是这样的

Write your answer here: vol
-o------
Write your answer here: hog
hog-----
Write your answer here: hogwart
hogwart-
Write your answer here: hogwarts
You win
hogwarts

它之所以突然结束,是因为它是在逐个字符的基础上进行检查,而不是检查整个单词,然后判断猜测是否错误

基本上,有一个变量作为开关,当你有一个正确的猜测开关时,然后在“for”循环后进行检查,看看是否需要取消一个生命

您可以看到,这就是我在循环之前创建的“正确”变量所做的,并检查以下内容

希望这有帮助^ 康纳

编辑:

我将把它分解一下,这样它就不会是一个巨大的垃圾场:P 如果你不能理解这一点,请检查代码

您接收输入,测试它是否为一个字母,然后在显示器上进行涂鸦

检查每个字符是

#we need to check if we need to take a life away
correct = False
这就是我提到的“开关”创建的地方,只是一个布尔变量

#loop through the word to guess, character by character.
for char in word:
    #if the character is in the old display, add it to the new on.
    if char in lastdisplay:
        display += char
在这里,如果预先显示了角色,我们将在新的显示器上显示它

    #if the character is in the guess, add it to the display.
    elif char in guess:   
        display += char
        #we made a correct guess!
        correct = True
如果猜测的字符是我们当前正在检查的字符,请将其添加到显示中,然后将开关翻转到“True”

    #otherwise we need to add a blank space in our display.
    else:               
        if char == ' ':
            display += ' '  #space
        else:
            display += '_'  #empty character
否则,什么也没有发生,请添加空格/空白,然后继续循环

#if we didn't get a correct letter, take a life.
if not correct:
    lives -= 1
这里是我们检查“开关”的地方,如果它是“真的”,我们不需要牺牲生命


否则“开关”为“False”,我们将失去一个生命。

可能是因为除了“”,每个字符都会失去一个生命?也许您可以看到:对于每个字符检查,您都减少了一个生命,而不是在for循环后包含它(每隔一次迭代)?
#if we didn't get a correct letter, take a life.
if not correct:
    lives -= 1