麻烦理解列表

Trouble understanding list

几周前我才开始学习 python,目前我正在尝试根据 python 一本书编写一个刽子手游戏。我无法理解以下代码:

MAX_WRONG = len(HANGMAN)-1
WORDS = ("book","toy","paper","school","house","computer","television")
word=random.choice(WORDS)
so_far = "-"*len(word)
wrong = 0
used = []
while wrong < MAX_WRONG and so_far!=word:
    print HANGMAN[wrong]
    print "\nYou've used the following letters:\n",used
    print "\nSo far, the word is:\n", so_far
    guess = raw_input("\n\nEnter your guess:")
    guess = guess.lower()

if guess in word:
    print"\nYes!",guess,"is in the word!"
    new=""
    for i in range(len(word)):
        if guess == word[i]:
            new+=guess
        else:
            new+=so_far[i]
    so_far=new

我的问题是代码块以 if guess in word: 开头并以 so_far=new 结尾。整段代码是什么意思?

谢谢!

让我们分解一下

if guess in word:

-> 如果输入的字母是所选单词的一部分(但这里的代码使用 raw_input 所以它实际上是一个字符串,但我们现在将其视为字符。

print"\nYes!",guess,"is in the word!"
new=""

->new 为空字符串。

for i in range(len(word)):

->从索引零开始迭代单词中的每个字符。

    if guess == word[i]:
        new+=guess

->在迭代过程中,如果输入的字母与 i 位置的单词匹配,则将其附加到 new 字符串,因为我们想向玩家显示字符所在的位置he/she猜对了。

    else:
        new+=so_far[i]

->否则,将 - 附加到 new 字符串而不是

so_far=new

->最后,重新分配新字符串。

本质上,if 语句构造 "correctly guessed" 字母,else 构造隐藏字母 -.