Chapter Topics

• if Statement
• else Statement
• elif Statement
• Conditional Expressions

• while Statement
• for Statement
• break Statement
• continue Statement
• pass Statement
• else Statement . . . Take Two
• Iterators

• List Comprehensions

• Generator Expressions

本章主题

• if 声明
• else声明
• elif声明
• 条件表达式

• while声明
• for声明t
• break声明
• continue声明
• pass声明
• else 声明 . . . Take Two
• Iterators

• List Comprehensions

• Generator Expressions

8
he primary focus of this chapter are Python’s conditional and looping
statements, and all their related components. We will take a close look
at if, while, for, and their friends else, elif, break, continue, and pass.

本章的主要内容是Python的条件和循环声明以及与它们相关的部分。我们会深入探讨if、while、for和他们的搭配else、elif、break、continue和pass。

8.1 if Statement
if声明

The if statement for Python will seem amazingly familiar. It is made up of three main components: the keyword itself, an expression that is tested for its truth value, and a code suite to execute if the expression evaluates to non- zero or true. The syntax for an if statement is:

if expression:
expr_true_suite

The suite of the if clause, expr_true_suite, will be executed only if the above conditional expression results in a Boolean true value. Otherwise, execution resumes at the next statement following the suite.
Python的if声明看上去十分的熟悉,它由三部分组成:关键字本身、用来判断真假的条件表达式和当表达式的值非零或为真时要执行的代码段。if声明的语法如下:

if expression:
expr_true_suite

if语句的代码段expr_true_suite只有在条件表达式的结果为布尔真时才执行,
否则会继续执行紧跟在该代码段后面的声明。

8.1.1 Multiple Conditional Expressions
多重条件表达式

The Boolean operators and, or, and not can be used to provide multiple condi- tional expressions or perform negation of expressions in the same if statement.

if not warn and (system_load >= 10): print "WARNING: losing resources" warn += 1


布尔操作符and、or和not可以用来提供多出那个条件表达式或者在相同的if声明中
否定表达式。
if not warn and (system_load >= 10): print "WARNING: losing resources" warn += 1

8.1.2 Single Statement Suites
单一声明代码段


If the suite of a compound statement, i.e., if clause, while or for loop, consists only of a single line, it may go on the same line as the header statement:

if make_hard_copy: send_data_to_printer()
Single line statements such as the above are valid syntax-wise; however, although it may be convenient, it may make your code more difficult to read,
so we recommend you indent the suite on the next line. Another good reason
is that if you must add another line to the suite, you have to move that line down anyway.
如果一个组合声明的代码段,例如if语句、while或for循环,仅仅包含一行代码,那么它可以和前面的声明在同一行上:
if make_hard_copy: send_data_to_printer()
如上的单行生命是合法的语法,然而尽管它可能方便,但是会使得代码更加难读,所以我们推荐把这行代码在下一行缩进。另外一个很好的理由就是如果你必须添加另外一行代码,你无论如何得把它移到下一行。