gpt4 book ai didi

python - 我不明白这段教程代码?

转载 作者:行者123 更新时间:2023-11-28 21:49:48 24 4
gpt4 key购买 nike

我目前正在通过 Michael Dawson 的一本书学习 Python。一切都清晰简洁,除了我进行了一个名为“Word Jumble Game”的练习。这是令我困惑的代码。

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.

我尝试跟踪程序(可能代表我的明显疏忽)但我看不到“单词”最终是如何跳出循环的,因为只要其中包含字符,它肯定会评估为 True 并且是无限循环。

非常感谢任何帮助,因为我到处寻找答案,但没有结果。提前致谢。

最佳答案

这三句话是你苦苦理解的

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 字符串。

如果您还不相信,请在每次迭代结束时添加打印语句。这应该对您有所帮助。

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

关于python - 我不明白这段教程代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32919209/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com