python 输入在我输入正确的值后一直循环

ogsagwnx  于 2023-05-05  发布在  Python
关注(0)|答案(2)|浏览(218)
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
eoxn13cs

eoxn13cs1#

这是因为你在比较之前替换了“猜测”:

...
guess = input("Guess a letter: ").lower()
if random_word[i] == guess:
...

试试这个:

for i in range(len(random_word)):
    while guess in random_word[i]:
        if random_word[i] == guess:
            display[i] = random_word[i]
            print(" ".join(display))
        guess = input("Guess a letter: ").lower()

更好的版本:

display = ["_" for _ in random_word]
guess = ''
while "_" in display:
    guess = input("Guess a letter: ").lower()
    for i in range(len(random_word)):
        if random_word[i] == guess:
            display[i] = random_word[i]
    print(" ".join(display))
5m1hhzi4

5m1hhzi42#

如果您的目的是不断询问用户下一个字母,直到他们猜对为止,那么while循环的条件应该是guess != random_word[i],而不是guess in random_word[i]
“重复这个,只要猜测是 * 不等于 * 正确的字母。”

相关问题