我正在从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.
我试着追踪这个程序(也许这是我的一个明显疏忽),但我看不出“单词”最终是如何跳出循环的,因为只要它有字符在里面,它肯定会评估为真,并且是一个无限循环。你知道吗
任何帮助都是非常感谢的家伙,因为我已经到处寻找答案,它是徒劳的。提前谢谢。你知道吗
while word:
将执行循环块,直到字长为零。 注意:此代码的作用类似于随机。随机.from random import shuffle; shuffle(word)
这三种说法正是你所难以理解的
因此,在每次迭代之后,从原始字符串
word
中正好减少一项。(word[position]
)因此,最终您将得到一个空的
word
字符串。你知道吗如果您还不确定,请在每次迭代结束时添加print语句。这应该对你有帮助。你知道吗
相关问题 更多 >
编程相关推荐