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

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.


8.1 if Statement

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:

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.

if expression:


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

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 make_hard_copy: send_data_to_printer()