Python 3.x 即使满足第一个条件,如何使用if语句完成整个列表?
下面的代码是一个刽子手游戏。当Python 3.x 即使满足第一个条件,如何使用if语句完成整个列表?,python-3.x,list,for-loop,if-statement,Python 3.x,List,For Loop,If Statement,下面的代码是一个刽子手游戏。当if语句找到第一个字母时,它会停止,不会进一步遍历列表,因此不会添加重复的字母。例如,如果一个单词包含两个a字母,那么它将只添加第一个字母 words = ["harry potter", "i love you forever", "neverland", "pockahontas"] lives = 3 hangman = list(random.choice(words)) copy_of_hangman = hangman.copy() print(copy
if
语句找到第一个字母时,它会停止,不会进一步遍历列表,因此不会添加重复的字母。例如,如果一个单词包含两个a
字母,那么它将只添加第一个字母
words = ["harry potter", "i love you forever", "neverland", "pockahontas"]
lives = 3
hangman = list(random.choice(words))
copy_of_hangman = hangman.copy()
print(copy_of_hangman)
for i in range(-6, 6, 2):
copy_of_hangman[i] = "_"
print(copy_of_hangman)
while lives != 0:
guess = input("Make your guess: ")
for letter in hangman:
if letter == guess:
copy_of_hangman[hangman.index(letter)] = guess
print(" ".join(copy_of_hangman))
您需要使用while循环。
因此,与其复制hangman[hangman.index(字母)],不如猜测 您可以使用(未经测试的):
pos = hangman.index(letter)
while pos != None:
copy_of_hangman[pos] = guess
pos = hangman.index(letter)