| 1 | \chapter{Compound statements\label{compound}}
|
|---|
| 2 | \indexii{compound}{statement}
|
|---|
| 3 |
|
|---|
| 4 | Compound statements contain (groups of) other statements; they affect
|
|---|
| 5 | or control the execution of those other statements in some way. In
|
|---|
| 6 | general, compound statements span multiple lines, although in simple
|
|---|
| 7 | incarnations a whole compound statement may be contained in one line.
|
|---|
| 8 |
|
|---|
| 9 | The \keyword{if}, \keyword{while} and \keyword{for} statements implement
|
|---|
| 10 | traditional control flow constructs. \keyword{try} specifies exception
|
|---|
| 11 | handlers and/or cleanup code for a group of statements. Function and
|
|---|
| 12 | class definitions are also syntactically compound statements.
|
|---|
| 13 |
|
|---|
| 14 | Compound statements consist of one or more `clauses.' A clause
|
|---|
| 15 | consists of a header and a `suite.' The clause headers of a
|
|---|
| 16 | particular compound statement are all at the same indentation level.
|
|---|
| 17 | Each clause header begins with a uniquely identifying keyword and ends
|
|---|
| 18 | with a colon. A suite is a group of statements controlled by a
|
|---|
| 19 | clause. A suite can be one or more semicolon-separated simple
|
|---|
| 20 | statements on the same line as the header, following the header's
|
|---|
| 21 | colon, or it can be one or more indented statements on subsequent
|
|---|
| 22 | lines. Only the latter form of suite can contain nested compound
|
|---|
| 23 | statements; the following is illegal, mostly because it wouldn't be
|
|---|
| 24 | clear to which \keyword{if} clause a following \keyword{else} clause would
|
|---|
| 25 | belong:
|
|---|
| 26 | \index{clause}
|
|---|
| 27 | \index{suite}
|
|---|
| 28 |
|
|---|
| 29 | \begin{verbatim}
|
|---|
| 30 | if test1: if test2: print x
|
|---|
| 31 | \end{verbatim}
|
|---|
| 32 |
|
|---|
| 33 | Also note that the semicolon binds tighter than the colon in this
|
|---|
| 34 | context, so that in the following example, either all or none of the
|
|---|
| 35 | \keyword{print} statements are executed:
|
|---|
| 36 |
|
|---|
| 37 | \begin{verbatim}
|
|---|
| 38 | if x < y < z: print x; print y; print z
|
|---|
| 39 | \end{verbatim}
|
|---|
| 40 |
|
|---|
| 41 | Summarizing:
|
|---|
| 42 |
|
|---|
| 43 | \begin{productionlist}
|
|---|
| 44 | \production{compound_stmt}
|
|---|
| 45 | {\token{if_stmt}}
|
|---|
| 46 | \productioncont{| \token{while_stmt}}
|
|---|
| 47 | \productioncont{| \token{for_stmt}}
|
|---|
| 48 | \productioncont{| \token{try_stmt}}
|
|---|
| 49 | \productioncont{| \token{with_stmt}}
|
|---|
| 50 | \productioncont{| \token{funcdef}}
|
|---|
| 51 | \productioncont{| \token{classdef}}
|
|---|
| 52 | \production{suite}
|
|---|
| 53 | {\token{stmt_list} NEWLINE
|
|---|
| 54 | | NEWLINE INDENT \token{statement}+ DEDENT}
|
|---|
| 55 | \production{statement}
|
|---|
| 56 | {\token{stmt_list} NEWLINE | \token{compound_stmt}}
|
|---|
| 57 | \production{stmt_list}
|
|---|
| 58 | {\token{simple_stmt} (";" \token{simple_stmt})* [";"]}
|
|---|
| 59 | \end{productionlist}
|
|---|
| 60 |
|
|---|
| 61 | Note that statements always end in a
|
|---|
| 62 | \code{NEWLINE}\index{NEWLINE token} possibly followed by a
|
|---|
| 63 | \code{DEDENT}.\index{DEDENT token} Also note that optional
|
|---|
| 64 | continuation clauses always begin with a keyword that cannot start a
|
|---|
| 65 | statement, thus there are no ambiguities (the `dangling
|
|---|
| 66 | \keyword{else}' problem is solved in Python by requiring nested
|
|---|
| 67 | \keyword{if} statements to be indented).
|
|---|
| 68 | \indexii{dangling}{else}
|
|---|
| 69 |
|
|---|
| 70 | The formatting of the grammar rules in the following sections places
|
|---|
| 71 | each clause on a separate line for clarity.
|
|---|
| 72 |
|
|---|
| 73 |
|
|---|
| 74 | \section{The \keyword{if} statement\label{if}}
|
|---|
| 75 | \stindex{if}
|
|---|
| 76 |
|
|---|
| 77 | The \keyword{if} statement is used for conditional execution:
|
|---|
| 78 |
|
|---|
| 79 | \begin{productionlist}
|
|---|
| 80 | \production{if_stmt}
|
|---|
| 81 | {"if" \token{expression} ":" \token{suite}}
|
|---|
| 82 | \productioncont{( "elif" \token{expression} ":" \token{suite} )*}
|
|---|
| 83 | \productioncont{["else" ":" \token{suite}]}
|
|---|
| 84 | \end{productionlist}
|
|---|
| 85 |
|
|---|
| 86 | It selects exactly one of the suites by evaluating the expressions one
|
|---|
| 87 | by one until one is found to be true (see section~\ref{Booleans} for
|
|---|
| 88 | the definition of true and false); then that suite is executed (and no
|
|---|
| 89 | other part of the \keyword{if} statement is executed or evaluated). If
|
|---|
| 90 | all expressions are false, the suite of the \keyword{else} clause, if
|
|---|
| 91 | present, is executed.
|
|---|
| 92 | \kwindex{elif}
|
|---|
| 93 | \kwindex{else}
|
|---|
| 94 |
|
|---|
| 95 |
|
|---|
| 96 | \section{The \keyword{while} statement\label{while}}
|
|---|
| 97 | \stindex{while}
|
|---|
| 98 | \indexii{loop}{statement}
|
|---|
| 99 |
|
|---|
| 100 | The \keyword{while} statement is used for repeated execution as long
|
|---|
| 101 | as an expression is true:
|
|---|
| 102 |
|
|---|
| 103 | \begin{productionlist}
|
|---|
| 104 | \production{while_stmt}
|
|---|
| 105 | {"while" \token{expression} ":" \token{suite}}
|
|---|
| 106 | \productioncont{["else" ":" \token{suite}]}
|
|---|
| 107 | \end{productionlist}
|
|---|
| 108 |
|
|---|
| 109 | This repeatedly tests the expression and, if it is true, executes the
|
|---|
| 110 | first suite; if the expression is false (which may be the first time it
|
|---|
| 111 | is tested) the suite of the \keyword{else} clause, if present, is
|
|---|
| 112 | executed and the loop terminates.
|
|---|
| 113 | \kwindex{else}
|
|---|
| 114 |
|
|---|
| 115 | A \keyword{break} statement executed in the first suite terminates the
|
|---|
| 116 | loop without executing the \keyword{else} clause's suite. A
|
|---|
| 117 | \keyword{continue} statement executed in the first suite skips the rest
|
|---|
| 118 | of the suite and goes back to testing the expression.
|
|---|
| 119 | \stindex{break}
|
|---|
| 120 | \stindex{continue}
|
|---|
| 121 |
|
|---|
| 122 |
|
|---|
| 123 | \section{The \keyword{for} statement\label{for}}
|
|---|
| 124 | \stindex{for}
|
|---|
| 125 | \indexii{loop}{statement}
|
|---|
| 126 |
|
|---|
| 127 | The \keyword{for} statement is used to iterate over the elements of a
|
|---|
| 128 | sequence (such as a string, tuple or list) or other iterable object:
|
|---|
| 129 | \obindex{sequence}
|
|---|
| 130 |
|
|---|
| 131 | \begin{productionlist}
|
|---|
| 132 | \production{for_stmt}
|
|---|
| 133 | {"for" \token{target_list} "in" \token{expression_list}
|
|---|
| 134 | ":" \token{suite}}
|
|---|
| 135 | \productioncont{["else" ":" \token{suite}]}
|
|---|
| 136 | \end{productionlist}
|
|---|
| 137 |
|
|---|
| 138 | The expression list is evaluated once; it should yield an iterable
|
|---|
| 139 | object. An iterator is created for the result of the
|
|---|
| 140 | {}\code{expression_list}. The suite is then executed once for each
|
|---|
| 141 | item provided by the iterator, in the
|
|---|
| 142 | order of ascending indices. Each item in turn is assigned to the
|
|---|
| 143 | target list using the standard rules for assignments, and then the
|
|---|
| 144 | suite is executed. When the items are exhausted (which is immediately
|
|---|
| 145 | when the sequence is empty), the suite in the \keyword{else} clause, if
|
|---|
| 146 | present, is executed, and the loop terminates.
|
|---|
| 147 | \kwindex{in}
|
|---|
| 148 | \kwindex{else}
|
|---|
| 149 | \indexii{target}{list}
|
|---|
| 150 |
|
|---|
| 151 | A \keyword{break} statement executed in the first suite terminates the
|
|---|
| 152 | loop without executing the \keyword{else} clause's suite. A
|
|---|
| 153 | \keyword{continue} statement executed in the first suite skips the rest
|
|---|
| 154 | of the suite and continues with the next item, or with the \keyword{else}
|
|---|
| 155 | clause if there was no next item.
|
|---|
| 156 | \stindex{break}
|
|---|
| 157 | \stindex{continue}
|
|---|
| 158 |
|
|---|
| 159 | The suite may assign to the variable(s) in the target list; this does
|
|---|
| 160 | not affect the next item assigned to it.
|
|---|
| 161 |
|
|---|
| 162 | The target list is not deleted when the loop is finished, but if the
|
|---|
| 163 | sequence is empty, it will not have been assigned to at all by the
|
|---|
| 164 | loop. Hint: the built-in function \function{range()} returns a
|
|---|
| 165 | sequence of integers suitable to emulate the effect of Pascal's
|
|---|
| 166 | \code{for i := a to b do};
|
|---|
| 167 | e.g., \code{range(3)} returns the list \code{[0, 1, 2]}.
|
|---|
| 168 | \bifuncindex{range}
|
|---|
| 169 | \indexii{Pascal}{language}
|
|---|
| 170 |
|
|---|
| 171 | \warning{There is a subtlety when the sequence is being modified
|
|---|
| 172 | by the loop (this can only occur for mutable sequences, i.e. lists).
|
|---|
| 173 | An internal counter is used to keep track of which item is used next,
|
|---|
| 174 | and this is incremented on each iteration. When this counter has
|
|---|
| 175 | reached the length of the sequence the loop terminates. This means that
|
|---|
| 176 | if the suite deletes the current (or a previous) item from the
|
|---|
| 177 | sequence, the next item will be skipped (since it gets the index of
|
|---|
| 178 | the current item which has already been treated). Likewise, if the
|
|---|
| 179 | suite inserts an item in the sequence before the current item, the
|
|---|
| 180 | current item will be treated again the next time through the loop.
|
|---|
| 181 | This can lead to nasty bugs that can be avoided by making a temporary
|
|---|
| 182 | copy using a slice of the whole sequence, e.g.,
|
|---|
| 183 | \index{loop!over mutable sequence}
|
|---|
| 184 | \index{mutable sequence!loop over}}
|
|---|
| 185 |
|
|---|
| 186 | \begin{verbatim}
|
|---|
| 187 | for x in a[:]:
|
|---|
| 188 | if x < 0: a.remove(x)
|
|---|
| 189 | \end{verbatim}
|
|---|
| 190 |
|
|---|
| 191 |
|
|---|
| 192 | \section{The \keyword{try} statement\label{try}}
|
|---|
| 193 | \stindex{try}
|
|---|
| 194 |
|
|---|
| 195 | The \keyword{try} statement specifies exception handlers and/or cleanup
|
|---|
| 196 | code for a group of statements:
|
|---|
| 197 |
|
|---|
| 198 | \begin{productionlist}
|
|---|
| 199 | \production{try_stmt} {try1_stmt | try2_stmt}
|
|---|
| 200 | \production{try1_stmt}
|
|---|
| 201 | {"try" ":" \token{suite}}
|
|---|
| 202 | \productioncont{("except" [\token{expression}
|
|---|
| 203 | ["," \token{target}]] ":" \token{suite})+}
|
|---|
| 204 | \productioncont{["else" ":" \token{suite}]}
|
|---|
| 205 | \productioncont{["finally" ":" \token{suite}]}
|
|---|
| 206 | \production{try2_stmt}
|
|---|
| 207 | {"try" ":" \token{suite}}
|
|---|
| 208 | \productioncont{"finally" ":" \token{suite}}
|
|---|
| 209 | \end{productionlist}
|
|---|
| 210 |
|
|---|
| 211 | \versionchanged[In previous versions of Python,
|
|---|
| 212 | \keyword{try}...\keyword{except}...\keyword{finally} did not work.
|
|---|
| 213 | \keyword{try}...\keyword{except} had to be nested in
|
|---|
| 214 | \keyword{try}...\keyword{finally}]{2.5}
|
|---|
| 215 |
|
|---|
| 216 | The \keyword{except} clause(s) specify one or more exception handlers.
|
|---|
| 217 | When no exception occurs in the
|
|---|
| 218 | \keyword{try} clause, no exception handler is executed. When an
|
|---|
| 219 | exception occurs in the \keyword{try} suite, a search for an exception
|
|---|
| 220 | handler is started. This search inspects the except clauses in turn until
|
|---|
| 221 | one is found that matches the exception. An expression-less except
|
|---|
| 222 | clause, if present, must be last; it matches any exception. For an
|
|---|
| 223 | except clause with an expression, that expression is evaluated, and the
|
|---|
| 224 | clause matches the exception if the resulting object is ``compatible''
|
|---|
| 225 | with the exception. An object is compatible with an exception if it
|
|---|
| 226 | is the class or a base class of the exception object, a tuple
|
|---|
| 227 | containing an item compatible with the exception, or, in the
|
|---|
| 228 | (deprecated) case of string exceptions, is the raised string itself
|
|---|
| 229 | (note that the object identities must match, i.e. it must be the same
|
|---|
| 230 | string object, not just a string with the same value).
|
|---|
| 231 | \kwindex{except}
|
|---|
| 232 |
|
|---|
| 233 | If no except clause matches the exception, the search for an exception
|
|---|
| 234 | handler continues in the surrounding code and on the invocation stack.
|
|---|
| 235 | \footnote{The exception is propogated to the invocation stack only if
|
|---|
| 236 | there is no \keyword{finally} clause that negates the exception.}
|
|---|
| 237 |
|
|---|
| 238 | If the evaluation of an expression in the header of an except clause
|
|---|
| 239 | raises an exception, the original search for a handler is canceled
|
|---|
| 240 | and a search starts for the new exception in the surrounding code and
|
|---|
| 241 | on the call stack (it is treated as if the entire \keyword{try} statement
|
|---|
| 242 | raised the exception).
|
|---|
| 243 |
|
|---|
| 244 | When a matching except clause is found, the exception is assigned to
|
|---|
| 245 | the target specified in that except clause, if present, and the except
|
|---|
| 246 | clause's suite is executed. All except clauses must have an
|
|---|
| 247 | executable block. When the end of this block is reached, execution
|
|---|
| 248 | continues normally after the entire try statement. (This means that
|
|---|
| 249 | if two nested handlers exist for the same exception, and the exception
|
|---|
| 250 | occurs in the try clause of the inner handler, the outer handler will
|
|---|
| 251 | not handle the exception.)
|
|---|
| 252 |
|
|---|
| 253 | Before an except clause's suite is executed, details about the
|
|---|
| 254 | exception are assigned to three variables in the
|
|---|
| 255 | \module{sys}\refbimodindex{sys} module: \code{sys.exc_type} receives
|
|---|
| 256 | the object identifying the exception; \code{sys.exc_value} receives
|
|---|
| 257 | the exception's parameter; \code{sys.exc_traceback} receives a
|
|---|
| 258 | traceback object\obindex{traceback} (see section~\ref{traceback})
|
|---|
| 259 | identifying the point in the program where the exception occurred.
|
|---|
| 260 | These details are also available through the \function{sys.exc_info()}
|
|---|
| 261 | function, which returns a tuple \code{(\var{exc_type}, \var{exc_value},
|
|---|
| 262 | \var{exc_traceback})}. Use of the corresponding variables is
|
|---|
| 263 | deprecated in favor of this function, since their use is unsafe in a
|
|---|
| 264 | threaded program. As of Python 1.5, the variables are restored to
|
|---|
| 265 | their previous values (before the call) when returning from a function
|
|---|
|
|---|