麻烦理解清单

时间:2015-03-20 03:30:45

标签: python variables

几周前我刚刚开始学习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结尾的代码块。这整段代码意味着什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

让我们分解

if guess in word:

- &GT;如果输入字母是所选单词的一部分(但这里的代码使用的是raw_input,所以它实际上是一个字符串,但我们暂时把它当作char。

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

- &gt; new为空字符串。

for i in range(len(word)):

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

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

- &gt;在迭代过程中,如果输入字母与i位置的单词匹配,则将其附加到new字符串,因为我们要向玩家显示该字符的位置/她猜错了。

    else:
        new+=so_far[i]

- &gt;否则,将-添加到new字符串

so_far=new

- &gt;最后,重新分配新字符串。

基本上,if语句正在构建“正确猜测”字母,而else正在构建隐藏字母为-