• 4.4 条件循环

    4.4 条件循环

    现在,我们可以将if语句和for语句结合。循环链表中每一项,只输出结尾字母是 l 的词。我们将为变量挑选另一个名字以表明 Python 并不在意变量名的意义。

    1. >>> sent1 = ['Call', 'me', 'Ishmael', '.']
    2. >>> for xyzzy in sent1:
    3. ... if xyzzy.endswith('l'):
    4. ... print(xyzzy)
    5. ...
    6. Call
    7. Ishmael
    8. >>>

    你会发现在iffor语句所在行末尾——缩进开始之前——有一个冒号。事实上,所有的 Python 控制结构都以冒号结尾。冒号表示当前语句与后面的缩进块有关联。

    我们也可以指定当if语句的条件不满足时采取的行动。在这里,我们看到elif(else if)语句和else语句。请注意,这些在缩进代码前也有冒号。

    1. >>> for token in sent1:
    2. ... if token.islower():
    3. ... print(token, 'is a lowercase word')
    4. ... elif token.istitle():
    5. ... print(token, 'is a titlecase word')
    6. ... else:
    7. ... print(token, 'is punctuation')
    8. ...
    9. Call is a titlecase word
    10. me is a lowercase word
    11. Ishmael is a titlecase word
    12. . is punctuation
    13. >>>

    正如你看到的,即便只有这么一点儿 Python 知识,你就已经可以开始构建多行的 Python 程序。分块开发程序,在整合它们之前测试每一块代码是否达到你的预期是很重要的。这也是 Python 交互式解释器的价值所在,也是为什么你必须适应它的原因。

    最后,让我们把一直在探索的习惯用法组合起来。首先,我们创建一个包含 cie 或 cei 的词的列表,然后循环输出其中的每一项。请注意 print 语句中给出的额外信息︰<cite>end=’ ‘</cite>。它告诉 Python 在每个单词后面打印一个空格(而不是默认的换行)。

    1. >>> tricky = sorted(w for w in set(text2) if 'cie' in w or 'cei' in w)
    2. >>> for word in tricky:
    3. ... print(word, end=' ')
    4. ancient ceiling conceit conceited conceive conscience
    5. conscientious conscientiously deceitful deceive ...
    6. >>>