我不明白这段教程的代码?

2024-09-29 23:17:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从michaeldawson的一本书中学习Python。所有的东西都很清楚和简洁,除了我做了一个叫做“单词混乱游戏”的练习。 这就是让我困惑的代码。你知道吗

import random

    # create a sequence of words to choose from
    WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")

    # pick one word randomly from the sequence
    word = random.choice(WORDS)

    # create a variable to use later to see if the guess is correct
    correct = word

    # create a jumbled version of the word
    jumble =""
    while word:
        position = random.randrange(len(word))
        jumble += word[position]
        word = word[:position] + word[(position + 1):]

我不明白的是while:word有效。解释如下:

I set the loop up this way so that it will continue until word is equal to the empty string. This is perfect, because each time the loop executes, the computer creates a new version of word with one letter “extracted” and assigns it back to word. Eventually, word will become the empty string and the jumbling will be done.

我试着追踪这个程序(也许这是我的一个明显疏忽),但我看不出“单词”最终是如何跳出循环的,因为只要它有字符在里面,它肯定会评估为真,并且是一个无限循环。你知道吗

任何帮助都是非常感谢的家伙,因为我已经到处寻找答案,它是徒劳的。提前谢谢。你知道吗


Tags: ofthetofromiscreatepositionrandom
2条回答

while word:将执行循环块,直到字长为零。 注意:此代码的作用类似于随机。随机. from random import shuffle; shuffle(word)

这三种说法正是你所难以理解的

jumble += word[position] # adding value of the index `position` to jumble
word[:position] # items from the beginning through position-1
word[(position + 1):]   # items position+1 through the rest of the array

因此,在每次迭代之后,从原始字符串word中正好减少一项。(word[position]

因此,最终您将得到一个空的word字符串。你知道吗

如果您还不确定,请在每次迭代结束时添加print语句。这应该对你有帮助。你知道吗

while word:
    position = random.randrange(len(word))
    jumble += word[position]
    word = word[:position] + word[(position + 1):]
    print word

相关问题 更多 >

    热门问题