>我正在编写一个程序来玩刽子手游戏,但我认为我没有正确使用我的全局变量。
一旦程序的第一次迭代在正确猜测后结束,任何具有正确猜测的连续迭代都会打印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
注意:这只是我代码的一小段,但我觉得其他块不相关。
您面临的主要问题是每次调用函数时都会附加全局变量。但是,我认为您不需要使用全局变量,通常这是一种非常糟糕的做法,考虑到您在问题中解释的内容,您可以简单地使用以下代码:
def getGuessedWord(secretWord, lettersGuessed):
return ' '.join(letter if letter in lettersGuessed else '_'
for letter in secretWord)
我还认为,如果你使用 python 理解来让你的代码更快,那就更好了。
每次调用函数getGuessedWord
添加到单词时,您不能使用全局:
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")