Hangman程序:在循环

时间:2018-05-15 02:19:04

标签: python-3.x while-loop global-variables

我正在编写一个程序来玩游戏刽子手,我认为我没有正确使用我的全局变量。

一旦程序的第一次迭代在正确猜测之后结束,任何具有正确猜测的连续迭代都会打印word及其所有过去的值。

如何才能打印word的最新值?这段代码在while循环中,每次迭代都得到用户输入。谢谢!

代码:

word=''

#lettersGuessed is a list of string values of letters guessed

def getGuessedWord(secretWord, lettersGuessed):
    global word
    for letter in secretWord:
        if letter not in lettersGuessed:
            word=word+' _'
        elif letter in lettersGuessed:
            word=word+' '+letter
    return print(word)

输出:

#first iteration if 'a' was guessed:
a _ _ _ _

#second iteration if 'l' was guessed:
a _ _ _ _ a _ _ l _

#third iteration if 'e' was guessed:
a _ _ _ _ a _ _ l _ a _ _ l e

#Assuming the above, for the third iteration I want:
a _ _ l e

注意:这只是我的代码的一小部分,但我不认为其他块是相关的。

2 个答案:

答案 0 :(得分:1)

您面临的主要问题是每次调用函数时都要附加全局变量。但是,我认为你不需要使用全局变量,一般来说这是一个非常糟糕的做法,你可以简单地使用下面的代码来考虑你在问题中解释的内容:

def getGuessedWord(secretWord, lettersGuessed):
    return ' '.join(letter if letter in lettersGuessed else '_'
                    for letter in secretWord)

我还认为如果你使用python理解来提高代码速度会更好。

答案 1 :(得分:0)

每次调用函数getGuessedWord时,你都要添加`word,你不能使用全局:

secretWord = "myword"


def getGuessedWord(secretWord, lettersGuessed):
    word = ""
    for letter in secretWord:
        if letter not in lettersGuessed:
            word=word+' _'
        elif letter in lettersGuessed:
            word=word+' '+letter
    return print(word)


getGuessedWord(secretWord,"")
getGuessedWord(secretWord,"m")
getGuessedWord(secretWord,"mwd")

或者你可以通过设置一个恒定长度的单词来解决这个问题,(不那么好,更难以遵循)例如:word='_ '*len(secretWord),然后代替添加它,替换字母word=word[:2*i]+letter +word[2*i+1:]

此处示例:

secretWord = "myword"
word='_ '*len(secretWord)

def getGuessedWord(secretWord, lettersGuessed):
    global word
    for i, letter in enumerate(secretWord):
        if letter in lettersGuessed:
            word=word[:2*i]+letter +word[2*i+1:]
    return print(word)

getGuessedWord(secretWord,"")
getGuessedWord(secretWord,"m")
getGuessedWord(secretWord,"w")
getGuessedWord(secretWord,"d")