0

我在 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 循环的方式不一致,但这似乎是因为这样编写的程序确实可以正常工作......

提前谢谢你,如果我问的问题对你们中的一些人来说太基本了,我很抱歉;毕竟我只是个新手。

4

1 回答 1

0

不,变量不会在每次迭代中“清除”,除非您手动更改它们。我将尝试解释您的代码片段:

# Separate the consonants at the start of this word:
prefixConsonants = ''

该变量prefixConsonants现在包含一个空字符串。如果它是第一次迭代,它只是在这个范围内创建的。如果是后续迭代,则它被“清除”,即它之前持有的字符串被替换为空字符串。

while len(word) > 0 and not word[0] in VOWELS:
    prefixConsonants += word[0]
    word = word[1:]

在这个循环结束时,变量prefixConsonants被填充字符 from或者如果条件从一开始就为假,word它仍然是空的。len(word) > 0 and not word[0] in VOWELS在解释器再次执行该行之前,所持有的任何字符串都prefixConsonants将一直存在prefixConsonants = ''

于 2020-06-16T08:56:05.527 回答