我在 Python 学习书中编写代码的程序如下:
VOWELS = ('a', 'e', 'i', 'o', 'u', 'y')
pigLatin = [] # A list of the words in Pig Latin.
for word in message.split():
# Separate the non-letters at the start of this word:
prefixNonLetters = ''
while len(word) > 0 and not word[0].isalpha():
prefixNonLetters += word[0]
word = word[1:]
if len(word) == 0:
pigLatin.append(prefixNonLetters)
continue
# Separate the non-letters at the end of this word:
suffixNonLetters = ''
while not word[-1].isalpha():
suffixNonLetters += word[-1]
word = word[:-1]
# Remember if the word was in uppercase or title case.
wasUpper = word.isupper()
wasTitle = word.istitle()
word = word.lower() # Make the word lowercase for translation.
# Separate the consonants at the start of this word:
prefixConsonants = ''
while len(word) > 0 and not word[0] in VOWELS:
prefixConsonants += word[0]
word = word[1:]
# Add the Pig Latin ending to the word:
if prefixConsonants != '':
word += prefixConsonants + 'ay'
else:
word += 'yay'
# Set the word back to uppercase or title case:
if wasUpper:
word = word.upper()
if wasTitle:
word = word.title()
# Add the non-letters back to the start or end of the word.
pigLatin.append(prefixNonLetters + word + suffixNonLetters)
# Join all the words back together into a single string:
print(' '.join(pigLatin))
所以基本上,在每次迭代结束时,我都会在 pigLatin 列表中添加一个完整的单词,包括转换后的单词本身以及非字母后缀和前缀(如果存在)。
然而,这让我有点困惑,因为它挑战了我之前对 for 循环的看法。我认为在这种情况下,prefixNonLetters 或 prefixConsonants 等变量的内容应该保留在每次迭代中。但如果是这样,它会弄乱第一个单词之后的所有单词(它们与前面单词的部分内容会太长)。
所以,我的问题如下: for 循环中的每次迭代是否都会清空其中的变量?这对我来说似乎很奇怪,并且绝对与我事先查看 for 循环的方式不一致,但这似乎是因为这样编写的程序确实可以正常工作......
提前谢谢你,如果我问的问题对你们中的一些人来说太基本了,我很抱歉;毕竟我只是个新手。