1 \chapter{Compound statements
\label{compound
}}
2 \indexii{compound
}{statement
}
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.
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.
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
30 if test1: if test2: print x
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:
38 if x < y < z: print x; print y; print z
43 \begin{productionlist
}
44 \production{compound_stmt
}
46 \productioncont{|
\token{while_stmt
}}
47 \productioncont{|
\token{for_stmt
}}
48 \productioncont{|
\token{try_stmt
}}
49 \productioncont{|
\token{funcdef
}}
50 \productioncont{|
\token{classdef
}}
52 {\token{stmt_list
} NEWLINE
53 | NEWLINE INDENT
\token{statement
}+ DEDENT
}
54 \production{statement
}
55 {\token{stmt_list
} NEWLINE |
\token{compound_stmt
}}
56 \production{stmt_list
}
57 {\token{simple_stmt
} (";"
\token{simple_stmt
})*
[";"
]}
60 Note that statements always end in a
61 \code{NEWLINE
}\index{NEWLINE token
} possibly followed by a
62 \code{DEDENT
}.
\index{DEDENT token
} Also note that optional
63 continuation clauses always begin with a keyword that cannot start a
64 statement, thus there are no ambiguities (the `dangling
65 \keyword{else
}' problem is solved in Python by requiring nested
66 \keyword{if
} statements to be indented).
67 \indexii{dangling
}{else
}
69 The formatting of the grammar rules in the following sections places
70 each clause on a separate line for clarity.
73 \section{The
\keyword{if
} statement
\label{if
}}
76 The
\keyword{if
} statement is used for conditional execution:
78 \begin{productionlist
}
80 {"if"
\token{expression
} ":"
\token{suite
}}
81 \productioncont{( "elif"
\token{expression
} ":"
\token{suite
} )*
}
82 \productioncont{["else" ":"
\token{suite
}]}
85 It selects exactly one of the suites by evaluating the expressions one
86 by one until one is found to be true (see section~
\ref{Booleans
} for
87 the definition of true and false); then that suite is executed (and no
88 other part of the
\keyword{if
} statement is executed or evaluated). If
89 all expressions are false, the suite of the
\keyword{else
} clause, if
95 \section{The
\keyword{while
} statement
\label{while
}}
97 \indexii{loop
}{statement
}
99 The
\keyword{while
} statement is used for repeated execution as long
100 as an expression is true:
102 \begin{productionlist
}
103 \production{while_stmt
}
104 {"while"
\token{expression
} ":"
\token{suite
}}
105 \productioncont{["else" ":"
\token{suite
}]}
108 This repeatedly tests the expression and, if it is true, executes the
109 first suite; if the expression is false (which may be the first time it
110 is tested) the suite of the
\keyword{else
} clause, if present, is
111 executed and the loop terminates.
114 A
\keyword{break
} statement executed in the first suite terminates the
115 loop without executing the
\keyword{else
} clause's suite. A
116 \keyword{continue
} statement executed in the first suite skips the rest
117 of the suite and goes back to testing the expression.
122 \section{The
\keyword{for
} statement
\label{for
}}
124 \indexii{loop
}{statement
}
126 The
\keyword{for
} statement is used to iterate over the elements of a
127 sequence (such as a string, tuple or list) or other iterable object:
130 \begin{productionlist
}
131 \production{for_stmt
}
132 {"for"
\token{target_list
} "in"
\token{expression_list
}
134 \productioncont{["else" ":"
\token{suite
}]}
137 The expression list is evaluated once; it should yield a sequence. The
138 suite is then executed once for each item in the sequence, in the
139 order of ascending indices. Each item in turn is assigned to the
140 target list using the standard rules for assignments, and then the
141 suite is executed. When the items are exhausted (which is immediately
142 when the sequence is empty), the suite in the
\keyword{else
} clause, if
143 present, is executed, and the loop terminates.
146 \indexii{target
}{list
}
148 A
\keyword{break
} statement executed in the first suite terminates the
149 loop without executing the
\keyword{else
} clause's suite. A
150 \keyword{continue
} statement executed in the first suite skips the rest
151 of the suite and continues with the next item, or with the
\keyword{else
}
152 clause if there was no next item.
156 The suite may assign to the variable(s) in the target list; this does
157 not affect the next item assigned to it.
159 The target list is not deleted when the loop is finished, but if the
160 sequence is empty, it will not have been assigned to at all by the
161 loop. Hint: the built-in function
\function{range()
} returns a
162 sequence of integers suitable to emulate the effect of Pascal's
163 \code{for i := a to b do
};
164 e.g.,
\code{range(
3)
} returns the list
\code{[0,
1,
2]}.
166 \indexii{Pascal
}{language
}
168 \warning{There is a subtlety when the sequence is being modified
169 by the loop (this can only occur for mutable sequences, i.e. lists).
170 An internal counter is used to keep track of which item is used next,
171 and this is incremented on each iteration. When this counter has
172 reached the length of the sequence the loop terminates. This means that
173 if the suite deletes the current (or a previous) item from the
174 sequence, the next item will be skipped (since it gets the index of
175 the current item which has already been treated). Likewise, if the
176 suite inserts an item in the sequence before the current item, the
177 current item will be treated again the next time through the loop.
178 This can lead to nasty bugs that can be avoided by making a temporary
179 copy using a slice of the whole sequence, e.g.,
180 \index{loop!over mutable sequence
}
181 \index{mutable sequence!loop over
}}
185 if x <
0: a.remove(x)
189 \section{The
\keyword{try
} statement
\label{try
}}
192 The
\keyword{try
} statement specifies exception handlers and/or cleanup
193 code for a group of statements:
195 \begin{productionlist
}
196 \production{try_stmt
}
197 {\token{try_exc_stmt
} |
\token{try_fin_stmt
}}
198 \production{try_exc_stmt
}
199 {"try" ":"
\token{suite
}}
200 \productioncont{("except"
[\token{expression
}
201 [","
\token{target
}]] ":"
\token{suite
})+
}
202 \productioncont{["else" ":"
\token{suite
}]}
203 \production{try_fin_stmt
}
204 {"try" ":"
\token{suite
}
205 "finally" ":"
\token{suite
}}
208 There are two forms of
\keyword{try
} statement:
209 \keyword{try
}...
\keyword{except
} and
210 \keyword{try
}...
\keyword{finally
}. These forms cannot be mixed (but
211 they can be nested in each other).
213 The
\keyword{try
}...
\keyword{except
} form specifies one or more
215 (the
\keyword{except
} clauses). When no exception occurs in the
216 \keyword{try
} clause, no exception handler is executed. When an
217 exception occurs in the
\keyword{try
} suite, a search for an exception
218 handler is started. This search inspects the except clauses in turn until
219 one is found that matches the exception. An expression-less except
220 clause, if present, must be last; it matches any exception. For an
221 except clause with an expression, that expression is evaluated, and the
222 clause matches the exception if the resulting object is ``compatible''
223 with the exception. An object is compatible with an exception if it
224 is either the object that identifies the exception, or (for exceptions
225 that are classes) it is a base class of the exception, or it is a
226 tuple containing an item that is compatible with the exception. Note
227 that the object identities must match, i.e. it must be the same
228 object, not just an object with the same value.
231 If no except clause matches the exception, the search for an exception
232 handler continues in the surrounding code and on the invocation stack.
234 If the evaluation of an expression in the header of an except clause
235 raises an exception, the original search for a handler is canceled
236 and a search starts for the new exception in the surrounding code and
237 on the call stack (it is treated as if the entire
\keyword{try
} statement
238 raised the exception).
240 When a matching except clause is found, the exception's parameter is
241 assigned to the target specified in that except clause, if present,
242 and the except clause's suite is executed. All except clauses must
243 have an executable block. When the end of this block
244 is reached, execution continues normally after the entire try
245 statement. (This means that if two nested handlers exist for the same
246 exception, and the exception occurs in the try clause of the inner
247 handler, the outer handler will not handle the exception.)
249 Before an except clause's suite is executed, details about the
250 exception are assigned to three variables in the
251 \module{sys
}\refbimodindex{sys
} module:
\code{sys.exc_type
} receives
252 the object identifying the exception;
\code{sys.exc_value
} receives
253 the exception's parameter;
\code{sys.exc_traceback
} receives a
254 traceback object
\obindex{traceback
} (see section~
\ref{traceback
})
255 identifying the point in the program where the exception occurred.
256 These details are also available through the
\function{sys.exc_info()
}
257 function, which returns a tuple
\code{(
\var{exc_type
},
\var{exc_value
},
258 \var{exc_traceback
})
}. Use of the corresponding variables is
259 deprecated in favor of this function, since their use is unsafe in a
260 threaded program. As of Python
1.5, the variables are restored to
261 their previous values (before the call) when returning from a function
262 that handled an exception.
263 \withsubitem{(in module sys)
}{\ttindex{exc_type
}
264 \ttindex{exc_value
}\ttindex{exc_traceback
}}
266 The optional
\keyword{else
} clause is executed if and when control
267 flows off the end of the
\keyword{try
} clause.
\footnote{
268 Currently, control ``flows off the end'' except in the case of an
269 exception or the execution of a
\keyword{return
},
270 \keyword{continue
}, or
\keyword{break
} statement.
271 } Exceptions in the
\keyword{else
} clause are not handled by the
272 preceding
\keyword{except
} clauses.
278 The
\keyword{try
}...
\keyword{finally
} form specifies a `cleanup' handler. The
279 \keyword{try
} clause is executed. When no exception occurs, the
280 \keyword{finally
} clause is executed. When an exception occurs in the
281 \keyword{try
} clause, the exception is temporarily saved, the
282 \keyword{finally
} clause is executed, and then the saved exception is
283 re-raised. If the
\keyword{finally
} clause raises another exception or
284 executes a
\keyword{return
} or
\keyword{break
} statement, the saved
285 exception is lost. A
\keyword{continue
} statement is illegal in the
286 \keyword{finally
} clause. (The reason is a problem with the current
287 implementation -- this restriction may be lifted in the future). The
288 exception information is not available to the program during execution of
289 the
\keyword{finally
} clause.
292 When a
\keyword{return
},
\keyword{break
} or
\keyword{continue
} statement is
293 executed in the
\keyword{try
} suite of a
\keyword{try
}...
\keyword{finally
}
294 statement, the
\keyword{finally
} clause is also executed `on the way out.' A
295 \keyword{continue
} statement is illegal in the
\keyword{finally
} clause.
296 (The reason is a problem with the current implementation --- this
297 restriction may be lifted in the future).
302 Additional information on exceptions can be found in
303 section~
\ref{exceptions
}, and information on using the
\keyword{raise
}
304 statement to generate exceptions may be found in section~
\ref{raise
}.
307 \section{Function definitions
\label{function
}}
308 \indexii{function
}{definition
}
311 A function definition defines a user-defined function object (see
312 section~
\ref{types
}):
313 \obindex{user-defined function
}
316 \begin{productionlist
}
318 {"def"
\token{funcname
} "("
[\token{parameter_list
}] ")"
320 \production{parameter_list
}
321 {(
\token{defparameter
} ",")*
}
322 \productioncont{("*"
\token{identifier
} [, "**"
\token{identifier
}]}
323 \productioncont{| "**"
\token{identifier
}
324 |
\token{defparameter
} [","
])
}
325 \production{defparameter
}
326 {\token{parameter
} ["="
\token{expression
}]}
328 {\token{parameter
} (","
\token{parameter
})*
[","
]}
329 \production{parameter
}
330 {\token{identifier
} | "("
\token{sublist
} ")"
}
331 \production{funcname
}
335 A function definition is an executable statement. Its execution binds
336 the function name in the current local namespace to a function object
337 (a wrapper around the executable code for the function). This
338 function object contains a reference to the current global namespace
339 as the global namespace to be used when the function is called.
340 \indexii{function
}{name
}
341 \indexii{name
}{binding
}
343 The function definition does not execute the function body; this gets
344 executed only when the function is called.
346 When one or more top-level parameters have the form
\var{parameter
}
347 \code{=
} \var{expression
}, the function is said to have ``default
348 parameter values.'' For a parameter with a
349 default value, the corresponding argument may be omitted from a call,
350 in which case the parameter's default value is substituted. If a
351 parameter has a default value, all following parameters must also have
352 a default value --- this is a syntactic restriction that is not
353 expressed by the grammar.
354 \indexiii{default
}{parameter
}{value
}
356 \strong{Default parameter values are evaluated when the function
357 definition is executed.
} This means that the expression is evaluated
358 once, when the function is defined, and that that same
359 ``pre-computed'' value is used for each call. This is especially
360 important to understand when a default parameter is a mutable object,
361 such as a list or a dictionary: if the function modifies the object
362 (e.g. by appending an item to a list), the default value is in effect
363 modified. This is generally not what was intended. A way around this
364 is to use
\code{None
} as the default, and explicitly test for it in
365 the body of the function, e.g.:
368 def whats_on_the_telly(penguin=None):
371 penguin.append("property of the zoo")
375 Function call semantics are described in more detail in
377 A function call always assigns values to all parameters mentioned in
378 the parameter list, either from position arguments, from keyword
379 arguments, or from default values. If the form ``
\code{*identifier
}''
380 is present, it is initialized to a tuple receiving any excess
381 positional parameters, defaulting to the empty tuple. If the form
382 ``
\code{**identifier
}'' is present, it is initialized to a new
383 dictionary receiving any excess keyword arguments, defaulting to a
384 new empty dictionary.
386 It is also possible to create anonymous functions (functions not bound
387 to a name), for immediate use in expressions. This uses lambda forms,
388 described in section~
\ref{lambda
}. Note that the lambda form is
389 merely a shorthand for a simplified function definition; a function
390 defined in a ``
\keyword{def
}'' statement can be passed around or
391 assigned to another name just like a function defined by a lambda
392 form. The ``
\keyword{def
}'' form is actually more powerful since it
393 allows the execution of multiple statements.
394 \indexii{lambda
}{form
}
396 \strong{Programmer's note:
} Functions are first-class objects. A
397 ``
\code{def
}'' form executed inside a function definition defines a
398 local function that can be returned or passed around. Free variables
399 used in the nested function can access the local variables of the
400 function containing the def. See section~
\ref{naming
} for details.
403 \section{Class definitions
\label{class
}}
404 \indexii{class
}{definition
}
407 A class definition defines a class object (see section~
\ref{types
}):
410 \begin{productionlist
}
411 \production{classdef
}
412 {"class"
\token{classname
} [\token{inheritance
}] ":"
414 \production{inheritance
}
415 {"("
[\token{expression_list
}] ")"
}
416 \production{classname
}
420 A class definition is an executable statement. It first evaluates the
421 inheritance list, if present. Each item in the inheritance list
422 should evaluate to a class object. The class's suite is then executed
423 in a new execution frame (see section~
\ref{naming
}), using a newly
424 created local namespace and the original global namespace.
425 (Usually, the suite contains only function definitions.) When the
426 class's suite finishes execution, its execution frame is discarded but
427 its local namespace is saved. A class object is then created using
428 the inheritance list for the base classes and the saved local
429 namespace for the attribute dictionary. The class name is bound to this
430 class object in the original local namespace.
432 \indexii{class
}{name
}
433 \indexii{name
}{binding
}
434 \indexii{execution
}{frame
}
436 \strong{Programmer's note:
} variables defined in the class definition
437 are class variables; they are shared by all instances. To define
438 instance variables, they must be given a value in the the
439 \method{__init__()
} method or in another method. Both class and
440 instance variables are accessible through the notation
441 ``
\code{self.name
}'', and an instance variable hides a class variable
442 with the same name when accessed in this way. Class variables with
443 immutable values can be used as defaults for instance variables.