繁体   English   中英

如何在循环中的if语句中保存变量

[英]how to save a variable in a if statement in a loop

我正在尝试对刽子手进行编程,但遇到了问题。 在第 48 行中,您看到我正在尝试复制到目前为止已经猜到的单词。 但问题是程序何时要求输入下一个字母。 例如,如果用户猜到了字母“h”,它会说h____ ,下一轮我猜字母 e 它会说_e___但我希望它在这个例子中说he___

word = 'hello'
guessed = False
guess_word = secret_word(word)
a = '____'

while guessed == False:
    letter = ask_letter_from_user()

    if is_the_letter_in_the_word(word, letter):
        locatie_letter_in_woord = location_of_letter_in_word(word, letter)
        a = replace(guess_word, locatie_letter_in_woord, letter)
        print(a)

似乎aguess_word实际上应该是一个变量。

您在每个猜测的字母之后将guess_word传递给replace function,但您永远不会更新它的值。 相反,您a更新 .

摆脱a . 下一次,给你所有的变量起有意义的名字,然后你可能会意识到你有两个变量用于一个目的:-)

而不是调用replace(guess_word, locatie_letter_in_woord, letter) ,只需执行a = a[:locatie_letter_in_woord] + letter + a[locatie_letter_in_woord+1:] 这将防止前一个字母被覆盖。

Output:

wich letter do you want to try?: h
well done! you guessed the letter
youre guessed letters are: h
a: h___
wich letter do you want to try?: e
well done! you guessed the letter
youre guessed letters are: h,e
a: he__

尝试这个:

您可以将单词变成一个列表,并逐个检查每个字母

word = 'hello'
guessed = False
found = []
guess_word = secret_word(word)

while guessed == False:
    guess= ask_letter_from_user()

    if is_the_letter_in_the_word(word, letter):
        print('well done! you guessed the letter')
        word_as_list = list(guess_word)
        indices = [i for i, letter in enumerate(word) if letter == guess]
        for index in indices:
            word_as_list[index] = letter
            found.append(letter)
        print('youre guessed letters are: ' + list_joining(found))

        guess_word = "".join(word_as_list)
        print(guess_word)
    

在第 47 行代替a = replace(guess_word, locatie_letter_in_woord, letter)a = replace(a, locatie_letter_in_woord, letter)

wich letter do you want to try?: h
well done! you guessed the letter
youre guessed letters are: h
h___
wich letter do you want to try?: e
well done! you guessed the letter
youre guessed letters are: h,e
he__
wich letter do you want to try?: 

不过,这个程序还是有问题的。 当您调用 function 时:

def location_of_letter_in_word(word, letter):
    return word.find(letter)

仔细查看hello中的第二个l ,它将返回第一个l的位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM