blob: b8fac0b81cfd08f6432bb0500ebdb54a1cb3c731 [file] [log] [blame]
Fred Drake61c77281998-07-28 19:34:22 +00001\chapter{Compound statements\label{compound}}
Fred Drakef6669171998-05-06 19:52:49 +00002\indexii{compound}{statement}
3
4Compound statements contain (groups of) other statements; they affect
5or control the execution of those other statements in some way. In
6general, compound statements span multiple lines, although in simple
7incarnations a whole compound statement may be contained in one line.
8
Fred Drake5c07d9b1998-05-14 19:37:06 +00009The \keyword{if}, \keyword{while} and \keyword{for} statements implement
10traditional control flow constructs. \keyword{try} specifies exception
Fred Drakef6669171998-05-06 19:52:49 +000011handlers and/or cleanup code for a group of statements. Function and
12class definitions are also syntactically compound statements.
13
Guido van Rossum5399d681998-07-24 18:51:11 +000014Compound statements consist of one or more `clauses.' A clause
15consists of a header and a `suite.' The clause headers of a
Fred Drakef6669171998-05-06 19:52:49 +000016particular compound statement are all at the same indentation level.
17Each clause header begins with a uniquely identifying keyword and ends
18with a colon. A suite is a group of statements controlled by a
19clause. A suite can be one or more semicolon-separated simple
20statements on the same line as the header, following the header's
21colon, or it can be one or more indented statements on subsequent
22lines. Only the latter form of suite can contain nested compound
23statements; the following is illegal, mostly because it wouldn't be
Fred Drake5c07d9b1998-05-14 19:37:06 +000024clear to which \keyword{if} clause a following \keyword{else} clause would
Fred Drakef6669171998-05-06 19:52:49 +000025belong:
26\index{clause}
27\index{suite}
28
29\begin{verbatim}
30if test1: if test2: print x
31\end{verbatim}
32
33Also note that the semicolon binds tighter than the colon in this
34context, so that in the following example, either all or none of the
Fred Drake5c07d9b1998-05-14 19:37:06 +000035\keyword{print} statements are executed:
Fred Drakef6669171998-05-06 19:52:49 +000036
37\begin{verbatim}
38if x < y < z: print x; print y; print z
39\end{verbatim}
40
41Summarizing:
42
43\begin{verbatim}
44compound_stmt: if_stmt | while_stmt | for_stmt
45 | try_stmt | funcdef | classdef
46suite: stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT
47statement: stmt_list NEWLINE | compound_stmt
48stmt_list: simple_stmt (";" simple_stmt)* [";"]
49\end{verbatim}
50
Guido van Rossum5399d681998-07-24 18:51:11 +000051Note that statements always end in a
52\code{NEWLINE}\index{NEWLINE token} possibly followed by a
53\code{DEDENT}.\index{DEDENT token} Also note that optional
54continuation clauses always begin with a keyword that cannot start a
55statement, thus there are no ambiguities (the `dangling
56\keyword{else}' problem is solved in Python by requiring nested
57\keyword{if} statements to be indented).
Fred Drakef6669171998-05-06 19:52:49 +000058\indexii{dangling}{else}
59
60The formatting of the grammar rules in the following sections places
61each clause on a separate line for clarity.
62
Fred Drake61c77281998-07-28 19:34:22 +000063\section{The \keyword{if} statement\label{if}}
Fred Drakef6669171998-05-06 19:52:49 +000064\stindex{if}
65
Fred Drake5c07d9b1998-05-14 19:37:06 +000066The \keyword{if} statement is used for conditional execution:
Fred Drakef6669171998-05-06 19:52:49 +000067
68\begin{verbatim}
Guido van Rossum5399d681998-07-24 18:51:11 +000069if_stmt: "if" expression ":" suite
70 ("elif" expression ":" suite)*
Fred Drakef6669171998-05-06 19:52:49 +000071 ["else" ":" suite]
72\end{verbatim}
73
Guido van Rossum5399d681998-07-24 18:51:11 +000074It selects exactly one of the suites by evaluating the expressions one
Fred Drakef6669171998-05-06 19:52:49 +000075by one until one is found to be true (see section \ref{Booleans} for
76the definition of true and false); then that suite is executed (and no
Fred Drake5c07d9b1998-05-14 19:37:06 +000077other part of the \keyword{if} statement is executed or evaluated). If
Guido van Rossum5399d681998-07-24 18:51:11 +000078all expressions are false, the suite of the \keyword{else} clause, if
Fred Drakef6669171998-05-06 19:52:49 +000079present, is executed.
80\kwindex{elif}
81\kwindex{else}
82
Fred Drake61c77281998-07-28 19:34:22 +000083\section{The \keyword{while} statement\label{while}}
Fred Drakef6669171998-05-06 19:52:49 +000084\stindex{while}
85\indexii{loop}{statement}
86
Guido van Rossum5399d681998-07-24 18:51:11 +000087The \keyword{while} statement is used for repeated execution as long
88as an expression is true:
Fred Drakef6669171998-05-06 19:52:49 +000089
90\begin{verbatim}
Guido van Rossum5399d681998-07-24 18:51:11 +000091while_stmt: "while" expression ":" suite
Fred Drakef6669171998-05-06 19:52:49 +000092 ["else" ":" suite]
93\end{verbatim}
94
Guido van Rossum5399d681998-07-24 18:51:11 +000095This repeatedly tests the expression and, if it is true, executes the
96first suite; if the expression is false (which may be the first time it
Fred Drake5c07d9b1998-05-14 19:37:06 +000097is tested) the suite of the \keyword{else} clause, if present, is
Fred Drakef6669171998-05-06 19:52:49 +000098executed and the loop terminates.
99\kwindex{else}
100
Fred Drake5c07d9b1998-05-14 19:37:06 +0000101A \keyword{break} statement executed in the first suite terminates the
102loop without executing the \keyword{else} clause's suite. A
103\keyword{continue} statement executed in the first suite skips the rest
Guido van Rossum5399d681998-07-24 18:51:11 +0000104of the suite and goes back to testing the expression.
Fred Drakef6669171998-05-06 19:52:49 +0000105\stindex{break}
106\stindex{continue}
107
Fred Drake61c77281998-07-28 19:34:22 +0000108\section{The \keyword{for} statement\label{for}}
Fred Drakef6669171998-05-06 19:52:49 +0000109\stindex{for}
110\indexii{loop}{statement}
111
Fred Drake5c07d9b1998-05-14 19:37:06 +0000112The \keyword{for} statement is used to iterate over the elements of a
Fred Drakef6669171998-05-06 19:52:49 +0000113sequence (string, tuple or list):
114\obindex{sequence}
115
116\begin{verbatim}
Guido van Rossum5399d681998-07-24 18:51:11 +0000117for_stmt: "for" target_list "in" expression_list ":" suite
Fred Drakef6669171998-05-06 19:52:49 +0000118 ["else" ":" suite]
119\end{verbatim}
120
Guido van Rossum5399d681998-07-24 18:51:11 +0000121The expression list is evaluated once; it should yield a sequence. The
Fred Drakef6669171998-05-06 19:52:49 +0000122suite is then executed once for each item in the sequence, in the
123order of ascending indices. Each item in turn is assigned to the
124target list using the standard rules for assignments, and then the
125suite is executed. When the items are exhausted (which is immediately
Fred Drake5c07d9b1998-05-14 19:37:06 +0000126when the sequence is empty), the suite in the \keyword{else} clause, if
Fred Drakef6669171998-05-06 19:52:49 +0000127present, is executed, and the loop terminates.
128\kwindex{in}
129\kwindex{else}
130\indexii{target}{list}
131
Fred Drake5c07d9b1998-05-14 19:37:06 +0000132A \keyword{break} statement executed in the first suite terminates the
133loop without executing the \keyword{else} clause's suite. A
134\keyword{continue} statement executed in the first suite skips the rest
135of the suite and continues with the next item, or with the \keyword{else}
Fred Drakef6669171998-05-06 19:52:49 +0000136clause if there was no next item.
137\stindex{break}
138\stindex{continue}
139
140The suite may assign to the variable(s) in the target list; this does
141not affect the next item assigned to it.
142
143The target list is not deleted when the loop is finished, but if the
144sequence is empty, it will not have been assigned to at all by the
Guido van Rossum5399d681998-07-24 18:51:11 +0000145loop. Hint: the built-in function \function{range()} returns a
146sequence of integers suitable to emulate the effect of Pascal's
Fred Drake5c07d9b1998-05-14 19:37:06 +0000147\code{for i := a to b do};
Guido van Rossum5399d681998-07-24 18:51:11 +0000148e.g., \code{range(3)} returns the list \code{[0, 1, 2]}.
Fred Drakef6669171998-05-06 19:52:49 +0000149\bifuncindex{range}
Fred Drake5c07d9b1998-05-14 19:37:06 +0000150\indexii{Pascal}{language}
Fred Drakef6669171998-05-06 19:52:49 +0000151
Fred Drake5c07d9b1998-05-14 19:37:06 +0000152\strong{Warning:} There is a subtlety when the sequence is being modified
Fred Drakef6669171998-05-06 19:52:49 +0000153by the loop (this can only occur for mutable sequences, i.e. lists).
154An internal counter is used to keep track of which item is used next,
155and this is incremented on each iteration. When this counter has
156reached the length of the sequence the loop terminates. This means that
157if the suite deletes the current (or a previous) item from the
158sequence, the next item will be skipped (since it gets the index of
159the current item which has already been treated). Likewise, if the
160suite inserts an item in the sequence before the current item, the
161current item will be treated again the next time through the loop.
162This can lead to nasty bugs that can be avoided by making a temporary
Guido van Rossum5399d681998-07-24 18:51:11 +0000163copy using a slice of the whole sequence, e.g.,
Fred Drakef6669171998-05-06 19:52:49 +0000164\index{loop!over mutable sequence}
165\index{mutable sequence!loop over}
166
167\begin{verbatim}
168for x in a[:]:
169 if x < 0: a.remove(x)
170\end{verbatim}
171
Fred Drake61c77281998-07-28 19:34:22 +0000172\section{The \keyword{try} statement\label{try}}
Fred Drakef6669171998-05-06 19:52:49 +0000173\stindex{try}
174
Fred Drake5c07d9b1998-05-14 19:37:06 +0000175The \keyword{try} statement specifies exception handlers and/or cleanup
Fred Drakef6669171998-05-06 19:52:49 +0000176code for a group of statements:
177
178\begin{verbatim}
179try_stmt: try_exc_stmt | try_fin_stmt
180try_exc_stmt: "try" ":" suite
Guido van Rossum5399d681998-07-24 18:51:11 +0000181 ("except" [expression ["," target]] ":" suite)+
Fred Drakef6669171998-05-06 19:52:49 +0000182 ["else" ":" suite]
183try_fin_stmt: "try" ":" suite
Fred Drake2cba0f62001-01-02 19:22:48 +0000184 "finally" ":" suite
Fred Drakef6669171998-05-06 19:52:49 +0000185\end{verbatim}
186
Fred Drake5c07d9b1998-05-14 19:37:06 +0000187There are two forms of \keyword{try} statement:
188\keyword{try}...\keyword{except} and
Guido van Rossum5399d681998-07-24 18:51:11 +0000189\keyword{try}...\keyword{finally}. These forms cannot be mixed (but
190they can be nested in each other).
Fred Drakef6669171998-05-06 19:52:49 +0000191
Fred Drake5c07d9b1998-05-14 19:37:06 +0000192The \keyword{try}...\keyword{except} form specifies one or more
193exception handlers
194(the \keyword{except} clauses). When no exception occurs in the
195\keyword{try} clause, no exception handler is executed. When an
196exception occurs in the \keyword{try} suite, a search for an exception
Guido van Rossum5399d681998-07-24 18:51:11 +0000197handler is started. This search inspects the except clauses in turn until
198one is found that matches the exception. An expression-less except
Fred Drakef6669171998-05-06 19:52:49 +0000199clause, if present, must be last; it matches any exception. For an
Guido van Rossum5399d681998-07-24 18:51:11 +0000200except clause with an expression, that expression is evaluated, and the
Fred Drakef6669171998-05-06 19:52:49 +0000201clause matches the exception if the resulting object is ``compatible''
202with the exception. An object is compatible with an exception if it
203is either the object that identifies the exception, or (for exceptions
204that are classes) it is a base class of the exception, or it is a
205tuple containing an item that is compatible with the exception. Note
206that the object identities must match, i.e. it must be the same
207object, not just an object with the same value.
208\kwindex{except}
209
210If no except clause matches the exception, the search for an exception
211handler continues in the surrounding code and on the invocation stack.
212
Guido van Rossum5399d681998-07-24 18:51:11 +0000213If the evaluation of an expression in the header of an except clause
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000214raises an exception, the original search for a handler is canceled
Fred Drakef6669171998-05-06 19:52:49 +0000215and a search starts for the new exception in the surrounding code and
Fred Drake5c07d9b1998-05-14 19:37:06 +0000216on the call stack (it is treated as if the entire \keyword{try} statement
Fred Drakef6669171998-05-06 19:52:49 +0000217raised the exception).
218
219When a matching except clause is found, the exception's parameter is
220assigned to the target specified in that except clause, if present,
Fred Drake4c2533f1999-08-24 22:14:01 +0000221and the except clause's suite is executed. All except clauses must
222have an executable block. When the end of this block
Fred Drakef6669171998-05-06 19:52:49 +0000223is reached, execution continues normally after the entire try
224statement. (This means that if two nested handlers exist for the same
225exception, and the exception occurs in the try clause of the inner
226handler, the outer handler will not handle the exception.)
227
228Before an except clause's suite is executed, details about the
Fred Drake99cd5731999-02-12 20:40:09 +0000229exception are assigned to three variables in the
230\module{sys}\refbimodindex{sys} module: \code{sys.exc_type} receives
231the object identifying the exception; \code{sys.exc_value} receives
232the exception's parameter; \code{sys.exc_traceback} receives a
233traceback object\obindex{traceback} (see section \ref{traceback})
234identifying the point in the program where the exception occurred.
Guido van Rossum5399d681998-07-24 18:51:11 +0000235These details are also available through the \function{sys.exc_info()}
Fred Drake99cd5731999-02-12 20:40:09 +0000236function, which returns a tuple \code{(\var{exc_type}, \var{exc_value},
237\var{exc_traceback})}. Use of the corresponding variables is
Guido van Rossum5399d681998-07-24 18:51:11 +0000238deprecated in favor of this function, since their use is unsafe in a
239threaded program. As of Python 1.5, the variables are restored to
240their previous values (before the call) when returning from a function
241that handled an exception.
Fred Drake99cd5731999-02-12 20:40:09 +0000242\withsubitem{(in module sys)}{\ttindex{exc_type}
243 \ttindex{exc_value}\ttindex{exc_traceback}}
Fred Drakef6669171998-05-06 19:52:49 +0000244
Fred Drake2cba0f62001-01-02 19:22:48 +0000245The optional \keyword{else} clause is executed if and when control
246flows off the end of the \keyword{try} clause.\footnote{
247 Currently, control ``flows off the end'' except in the case of an
248 exception or the execution of a \keyword{return},
249 \keyword{continue}, or \keyword{break} statement.
250} Exceptions in the \keyword{else} clause are not handled by the
251preceding \keyword{except} clauses.
Fred Drakef6669171998-05-06 19:52:49 +0000252\kwindex{else}
Fred Drake2cba0f62001-01-02 19:22:48 +0000253\stindex{return}
254\stindex{break}
255\stindex{continue}
Fred Drakef6669171998-05-06 19:52:49 +0000256
Fred Drake5c07d9b1998-05-14 19:37:06 +0000257The \keyword{try}...\keyword{finally} form specifies a `cleanup' handler. The
258\keyword{try} clause is executed. When no exception occurs, the
259\keyword{finally} clause is executed. When an exception occurs in the
260\keyword{try} clause, the exception is temporarily saved, the
261\keyword{finally} clause is executed, and then the saved exception is
262re-raised. If the \keyword{finally} clause raises another exception or
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000263executes a \keyword{return} or \keyword{break} statement, the saved
264exception is lost. A \keyword{continue} statement is illegal in the
265\keyword{finally} clause. (The reason is a problem with the current
266implementation -- thsi restriction may be lifted in the future). The
267exception information is not available to the program during execution of
268the \keyword{finally} clause.
Fred Drakef6669171998-05-06 19:52:49 +0000269\kwindex{finally}
270
Jeremy Hylton3faa52e2001-02-01 22:48:12 +0000271When a \keyword{return}, \keyword{break} or \keyword{continue} statement is
272executed in the \keyword{try} suite of a \keyword{try}...\keyword{finally}
273statement, the \keyword{finally} clause is also executed `on the way out.' A
274\keyword{continue} statement is illegal in the \keyword{finally} clause.
275(The reason is a problem with the current implementation --- this
Fred Drakef6669171998-05-06 19:52:49 +0000276restriction may be lifted in the future).
277\stindex{return}
278\stindex{break}
279\stindex{continue}
280
Fred Drake61c77281998-07-28 19:34:22 +0000281\section{Function definitions\label{function}}
Fred Drakef6669171998-05-06 19:52:49 +0000282\indexii{function}{definition}
283
284A function definition defines a user-defined function object (see
Guido van Rossum5399d681998-07-24 18:51:11 +0000285section \ref{types}):
Fred Drakef6669171998-05-06 19:52:49 +0000286\obindex{user-defined function}
287\obindex{function}
288
289\begin{verbatim}
290funcdef: "def" funcname "(" [parameter_list] ")" ":" suite
291parameter_list: (defparameter ",")* ("*" identifier [, "**" identifier]
292 | "**" identifier
293 | defparameter [","])
Guido van Rossum5399d681998-07-24 18:51:11 +0000294defparameter: parameter ["=" expression]
Fred Drakef6669171998-05-06 19:52:49 +0000295sublist: parameter ("," parameter)* [","]
296parameter: identifier | "(" sublist ")"
297funcname: identifier
298\end{verbatim}
299
300A function definition is an executable statement. Its execution binds
Guido van Rossum5399d681998-07-24 18:51:11 +0000301the function name in the current local namespace to a function object
Fred Drakef6669171998-05-06 19:52:49 +0000302(a wrapper around the executable code for the function). This
Guido van Rossum5399d681998-07-24 18:51:11 +0000303function object contains a reference to the current global namespace
304as the global namespace to be used when the function is called.
Fred Drakef6669171998-05-06 19:52:49 +0000305\indexii{function}{name}
306\indexii{name}{binding}
307
308The function definition does not execute the function body; this gets
309executed only when the function is called.
310
Guido van Rossum5399d681998-07-24 18:51:11 +0000311When one or more top-level parameters have the form \var{parameter}
312\code{=} \var{expression}, the function is said to have ``default
Guido van Rossume0394391998-12-04 19:37:10 +0000313parameter values.'' For a parameter with a
Guido van Rossum5399d681998-07-24 18:51:11 +0000314default value, the corresponding argument may be omitted from a call,
315in which case the parameter's default value is substituted. If a
316parameter has a default value, all following parameters must also have
317a default value --- this is a syntactic restriction that is not
Fred Drakee15956b2000-04-03 04:51:13 +0000318expressed by the grammar.
Fred Drakef6669171998-05-06 19:52:49 +0000319\indexiii{default}{parameter}{value}
320
Guido van Rossume0394391998-12-04 19:37:10 +0000321\strong{Default parameter values are evaluated when the function
322definition is executed.} This means that the expression is evaluated
323once, when the function is defined, and that that same
324``pre-computed'' value is used for each call. This is especially
325important to understand when a default parameter is a mutable object,
326such as a list or a dictionary: if the function modifies the object
327(e.g. by appending an item to a list), the default value is in effect
328modified. This is generally not what was intended. A way around this
329is to use \code{None} as the default, and explicitly test for it in
330the body of the function, e.g.:
331
332\begin{verbatim}
333def whats_on_the_telly(penguin=None):
334 if penguin is None:
335 penguin = []
336 penguin.append("property of the zoo")
337 return penguin
338\end{verbatim}
339
Guido van Rossum5399d681998-07-24 18:51:11 +0000340Function call semantics are described in more detail in section
341\ref{calls}.
342A function call always assigns values to all parameters mentioned in
343the parameter list, either from position arguments, from keyword
344arguments, or from default values. If the form ``\code{*identifier}''
345is present, it is initialized to a tuple receiving any excess
346positional parameters, defaulting to the empty tuple. If the form
347``\code{**identifier}'' is present, it is initialized to a new
348dictionary receiving any excess keyword arguments, defaulting to a
349new empty dictionary.
Fred Drakef6669171998-05-06 19:52:49 +0000350
Fred Drakef6669171998-05-06 19:52:49 +0000351
Fred Drakef6669171998-05-06 19:52:49 +0000352
Fred Drakef6669171998-05-06 19:52:49 +0000353
Fred Drakef6669171998-05-06 19:52:49 +0000354
355It is also possible to create anonymous functions (functions not bound
356to a name), for immediate use in expressions. This uses lambda forms,
Guido van Rossum5399d681998-07-24 18:51:11 +0000357described in section \ref{lambda}. Note that the lambda form is
358merely a shorthand for a simplified function definition; a function
359defined in a ``\keyword{def}'' statement can be passed around or
360assigned to another name just like a function defined by a lambda
361form. The ``\keyword{def}'' form is actually more powerful since it
362allows the execution of multiple statements.
Fred Drakef6669171998-05-06 19:52:49 +0000363\indexii{lambda}{form}
364
Guido van Rossum5399d681998-07-24 18:51:11 +0000365\strong{Programmer's note:} a ``\code{def}'' form executed inside a
366function definition defines a local function that can be returned or
367passed around. Because of Python's two-scope philosophy, a local
368function defined in this way does not have access to the local
369variables of the function that contains its definition; the same rule
370applies to functions defined by a lambda form. A standard trick to
371pass selected local variables into a locally defined function is to
372use default argument values, like this:
373
374\begin{verbatim}
375# Return a function that returns its argument incremented by 'n'
376def make_incrementer(n):
377 def increment(x, n=n):
378 return x+n
379 return increment
380
381add1 = make_incrementer(1)
382print add1(3) # This prints '4'
383\end{verbatim}
384
Fred Drake61c77281998-07-28 19:34:22 +0000385\section{Class definitions\label{class}}
Fred Drakef6669171998-05-06 19:52:49 +0000386\indexii{class}{definition}
387
388A class definition defines a class object (see section \ref{types}):
389\obindex{class}
390
391\begin{verbatim}
392classdef: "class" classname [inheritance] ":" suite
Guido van Rossum5399d681998-07-24 18:51:11 +0000393inheritance: "(" [expression_list] ")"
Fred Drakef6669171998-05-06 19:52:49 +0000394classname: identifier
395\end{verbatim}
396
397A class definition is an executable statement. It first evaluates the
398inheritance list, if present. Each item in the inheritance list
399should evaluate to a class object. The class's suite is then executed
400in a new execution frame (see section \ref{execframes}), using a newly
Guido van Rossum5399d681998-07-24 18:51:11 +0000401created local namespace and the original global namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000402(Usually, the suite contains only function definitions.) When the
403class's suite finishes execution, its execution frame is discarded but
Guido van Rossum5399d681998-07-24 18:51:11 +0000404its local namespace is saved. A class object is then created using
405the inheritance list for the base classes and the saved local
406namespace for the attribute dictionary. The class name is bound to this
407class object in the original local namespace.
Fred Drakef6669171998-05-06 19:52:49 +0000408\index{inheritance}
409\indexii{class}{name}
410\indexii{name}{binding}
411\indexii{execution}{frame}
Guido van Rossum5399d681998-07-24 18:51:11 +0000412
413\strong{Programmer's note:} variables defined in the class definition
414are class variables; they are shared by all instances. To define
415instance variables, they must be given a value in the the
416\method{__init__()} method or in another method. Both class and
417instance variables are accessible through the notation
418```code{self.name}'', and an instance variable hides a class variable
419with the same name when accessed in this way. Class variables with
420immutable values can be used as defaults for instance variables.