import random
word_list = ["ardvark", "baboon", "camel"]
random_word = random.choice(word_list)
print(random_word)
display = ["_" for _ in random_word]
guess = ''
for i in range(len(random_word)):
while guess in random_word[i]:
guess = input("Guess a letter: ").lower()
if random_word[i] == guess:
display[i] = random_word[i]
print(" ".join(display))
我希望它不会在空白处打印出值后问同样的问题2次。
这是代码的输出:
camel
Guess a letter: c
c _ _ _ _
Guess a letter: a
Guess a letter: a
c a _ _ _
Guess a letter: m
Guess a letter: m
c a m _ _
Guess a letter: e
Guess a letter: e
c a m e _
Guess a letter: l
Guess a letter: l
c a m e l
2条答案
按热度按时间eoxn13cs1#
这是因为你在比较之前替换了“猜测”:
试试这个:
更好的版本:
5m1hhzi42#
如果您的目的是不断询问用户下一个字母,直到他们猜对为止,那么
while
循环的条件应该是guess != random_word[i]
,而不是guess in random_word[i]
。“重复这个,只要猜测是 * 不等于 * 正确的字母。”