blob: 196215accaa1ed52b746032db261504fb9232d0e [file] [log] [blame]
Guido van Rossumda43a4a1992-08-14 09:17:29 +00001\chapter{Compound statements}
2\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
Guido van Rossume9914961994-08-01 12:38:14 +00009The \verb@if@, \verb@while@ and \verb@for@ statements implement
10traditional control flow constructs. \verb@try@ specifies exception
Guido van Rossumda43a4a1992-08-14 09:17:29 +000011handlers and/or cleanup code for a group of statements. Function and
12class definitions are also syntactically compound statements.
13
14Compound statements consist of one or more `clauses'. A clause
15consists of a header and a `suite'. The clause headers of a
16particular 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
Guido van Rossume9914961994-08-01 12:38:14 +000024clear to which \verb@if@ clause a following \verb@else@ clause would
Guido van Rossumda43a4a1992-08-14 09:17:29 +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
Guido van Rossume9914961994-08-01 12:38:14 +000035\verb@print@ statements are executed:
Guido van Rossumda43a4a1992-08-14 09:17:29 +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 Rossume9914961994-08-01 12:38:14 +000051Note that statements always end in a \verb@NEWLINE@ possibly followed
52by a \verb@DEDENT@.
Guido van Rossumda43a4a1992-08-14 09:17:29 +000053\index{NEWLINE token}
54\index{DEDENT token}
55
56Also note that optional continuation clauses always begin with a
57keyword that cannot start a statement, thus there are no ambiguities
Guido van Rossume9914961994-08-01 12:38:14 +000058(the `dangling \verb@else@' problem is solved in Python by requiring
59nested \verb@if@ statements to be indented).
Guido van Rossumda43a4a1992-08-14 09:17:29 +000060\indexii{dangling}{else}
61
62The formatting of the grammar rules in the following sections places
63each clause on a separate line for clarity.
64
65\section{The {\tt if} statement}
66\stindex{if}
67
Guido van Rossume9914961994-08-01 12:38:14 +000068The \verb@if@ statement is used for conditional execution:
Guido van Rossumda43a4a1992-08-14 09:17:29 +000069
70\begin{verbatim}
71if_stmt: "if" condition ":" suite
72 ("elif" condition ":" suite)*
73 ["else" ":" suite]
74\end{verbatim}
75
76It selects exactly one of the suites by evaluating the conditions one
77by one until one is found to be true (see section \ref{Booleans} for
78the definition of true and false); then that suite is executed (and no
Guido van Rossume9914961994-08-01 12:38:14 +000079other part of the \verb@if@ statement is executed or evaluated). If
80all conditions are false, the suite of the \verb@else@ clause, if
Guido van Rossumda43a4a1992-08-14 09:17:29 +000081present, is executed.
82\kwindex{elif}
83\kwindex{else}
84
85\section{The {\tt while} statement}
86\stindex{while}
87\indexii{loop}{statement}
88
Guido van Rossume9914961994-08-01 12:38:14 +000089The \verb@while@ statement is used for repeated execution as long as a
Guido van Rossumda43a4a1992-08-14 09:17:29 +000090condition is true:
91
92\begin{verbatim}
93while_stmt: "while" condition ":" suite
94 ["else" ":" suite]
95\end{verbatim}
96
97This repeatedly tests the condition and, if it is true, executes the
98first suite; if the condition is false (which may be the first time it
Guido van Rossume9914961994-08-01 12:38:14 +000099is tested) the suite of the \verb@else@ clause, if present, is
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000100executed and the loop terminates.
101\kwindex{else}
102
Guido van Rossume9914961994-08-01 12:38:14 +0000103A \verb@break@ statement executed in the first suite terminates the
104loop without executing the \verb@else@ clause's suite. A
105\verb@continue@ statement executed in the first suite skips the rest
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000106of the suite and goes back to testing the condition.
107\stindex{break}
108\stindex{continue}
109
110\section{The {\tt for} statement}
111\stindex{for}
112\indexii{loop}{statement}
113
Guido van Rossume9914961994-08-01 12:38:14 +0000114The \verb@for@ statement is used to iterate over the elements of a
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000115sequence (string, tuple or list):
116\obindex{sequence}
117
118\begin{verbatim}
119for_stmt: "for" target_list "in" condition_list ":" suite
120 ["else" ":" suite]
121\end{verbatim}
122
123The condition list is evaluated once; it should yield a sequence. The
124suite is then executed once for each item in the sequence, in the
125order of ascending indices. Each item in turn is assigned to the
126target list using the standard rules for assignments, and then the
127suite is executed. When the items are exhausted (which is immediately
Guido van Rossume9914961994-08-01 12:38:14 +0000128when the sequence is empty), the suite in the \verb@else@ clause, if
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000129present, is executed, and the loop terminates.
130\kwindex{in}
131\kwindex{else}
132\indexii{target}{list}
133
Guido van Rossume9914961994-08-01 12:38:14 +0000134A \verb@break@ statement executed in the first suite terminates the
135loop without executing the \verb@else@ clause's suite. A
136\verb@continue@ statement executed in the first suite skips the rest
137of the suite and continues with the next item, or with the \verb@else@
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000138clause if there was no next item.
139\stindex{break}
140\stindex{continue}
141
142The suite may assign to the variable(s) in the target list; this does
143not affect the next item assigned to it.
144
145The target list is not deleted when the loop is finished, but if the
146sequence is empty, it will not have been assigned to at all by the
147loop.
148
Guido van Rossume9914961994-08-01 12:38:14 +0000149Hint: the built-in function \verb@range()@ returns a sequence of
150integers suitable to emulate the effect of Pascal's
151\verb@for i := a to b do@;
152e.g. \verb@range(3)@ returns the list \verb@[0, 1, 2]@.
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000153\bifuncindex{range}
154\index{Pascal}
155
156{\bf Warning:} There is a subtlety when the sequence is being modified
157by the loop (this can only occur for mutable sequences, i.e. lists).
158An internal counter is used to keep track of which item is used next,
159and this is incremented on each iteration. When this counter has
160reached the length of the sequence the loop terminates. This means that
161if the suite deletes the current (or a previous) item from the
162sequence, the next item will be skipped (since it gets the index of
163the current item which has already been treated). Likewise, if the
164suite inserts an item in the sequence before the current item, the
165current item will be treated again the next time through the loop.
166This can lead to nasty bugs that can be avoided by making a temporary
167copy using a slice of the whole sequence, e.g.
168\index{loop!over mutable sequence}
169\index{mutable sequence!loop over}
170
171\begin{verbatim}
172for x in a[:]:
173 if x < 0: a.remove(x)
174\end{verbatim}
175
Guido van Rossum7f8765d1993-10-11 12:54:58 +0000176\section{The {\tt try} statement} \label{try}
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000177\stindex{try}
178
Guido van Rossume9914961994-08-01 12:38:14 +0000179The \verb@try@ statement specifies exception handlers and/or cleanup
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000180code for a group of statements:
181
182\begin{verbatim}
183try_stmt: try_exc_stmt | try_fin_stmt
184try_exc_stmt: "try" ":" suite
185 ("except" [condition ["," target]] ":" suite)+
Guido van Rossume9914961994-08-01 12:38:14 +0000186 ["else" ":" suite]
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000187try_fin_stmt: "try" ":" suite
188 "finally" ":" suite
189\end{verbatim}
190
Guido van Rossume9914961994-08-01 12:38:14 +0000191There are two forms of \verb@try@ statement: \verb@try...except@ and
192\verb@try...finally@. These forms cannot be mixed.
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000193
Guido van Rossume9914961994-08-01 12:38:14 +0000194The \verb@try...except@ form specifies one or more exception handlers
195(the \verb@except@ clauses). When no exception occurs in the
196\verb@try@ clause, no exception handler is executed. When an
197exception occurs in the \verb@try@ suite, a search for an exception
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000198handler is started. This inspects the except clauses in turn until
199one is found that matches the exception. A condition-less except
200clause, if present, must be last; it matches any exception. For an
201except clause with a condition, that condition is evaluated, and the
202clause matches the exception if the resulting object is ``compatible''
203with the exception. An object is compatible with an exception if it
Guido van Rossumeb8b0d21995-02-07 14:37:17 +0000204is either the object that identifies the exception, or (for exceptions
205that are classes) it is a base class of the exception, or it is a
206tuple containing an item that is compatible with the exception. Note
207that the object identities must match, i.e. it must be the same
208object, not just an object with the same value.
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000209\kwindex{except}
210
211If no except clause matches the exception, the search for an exception
212handler continues in the surrounding code and on the invocation stack.
213
214If the evaluation of a condition in the header of an except clause
215raises an exception, the original search for a handler is cancelled
216and a search starts for the new exception in the surrounding code and
Guido van Rossume9914961994-08-01 12:38:14 +0000217on the call stack (it is treated as if the entire \verb@try@ statement
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000218raised the exception).
219
220When a matching except clause is found, the exception's parameter is
221assigned to the target specified in that except clause, if present,
222and the except clause's suite is executed. When the end of this suite
223is 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
Guido van Rossum7f8765d1993-10-11 12:54:58 +0000228Before an except clause's suite is executed, details about the
Guido van Rossume9914961994-08-01 12:38:14 +0000229exception are assigned to three variables in the \verb@sys@ module:
230\verb@sys.exc_type@ receives the object identifying the exception;
231\verb@sys.exc_value@ receives the exception's parameter;
232\verb@sys.exc_traceback@ receives a traceback object (see section
Guido van Rossum7f8765d1993-10-11 12:54:58 +0000233\ref{traceback}) identifying the point in the program where the
234exception occurred.
235\bimodindex{sys}
236\ttindex{exc_type}
237\ttindex{exc_value}
238\ttindex{exc_traceback}
239\obindex{traceback}
240
Guido van Rossume9914961994-08-01 12:38:14 +0000241The optional \verb@else@ clause is executed when no exception occurs
242in the \verb@try@ clause. Exceptions in the \verb@else@ clause are
243not handled by the preceding \verb@except@ clauses.
244\kwindex{else}
245
246The \verb@try...finally@ form specifies a `cleanup' handler. The
247\verb@try@ clause is executed. When no exception occurs, the
248\verb@finally@ clause is executed. When an exception occurs in the
249\verb@try@ clause, the exception is temporarily saved, the
250\verb@finally@ clause is executed, and then the saved exception is
251re-raised. If the \verb@finally@ clause raises another exception or
252executes a \verb@return@, \verb@break@ or \verb@continue@ statement,
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000253the saved exception is lost.
254\kwindex{finally}
255
Guido van Rossume9914961994-08-01 12:38:14 +0000256When a \verb@return@ or \verb@break@ statement is executed in the
257\verb@try@ suite of a \verb@try...finally@ statement, the
258\verb@finally@ clause is also executed `on the way out'. A
259\verb@continue@ statement is illegal in the \verb@try@ clause. (The
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000260reason is a problem with the current implementation --- this
261restriction may be lifted in the future).
262\stindex{return}
263\stindex{break}
264\stindex{continue}
265
266\section{Function definitions} \label{function}
267\indexii{function}{definition}
268
269A function definition defines a user-defined function object (see
270section \ref{types}):
271\obindex{user-defined function}
272\obindex{function}
273
274\begin{verbatim}
275funcdef: "def" funcname "(" [parameter_list] ")" ":" suite
Guido van Rossume9914961994-08-01 12:38:14 +0000276parameter_list: (defparameter ",")* ("*" identifier | defparameter [","])
277defparameter: parameter ["=" condition]
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000278sublist: parameter ("," parameter)* [","]
279parameter: identifier | "(" sublist ")"
280funcname: identifier
281\end{verbatim}
282
283A function definition is an executable statement. Its execution binds
284the function name in the current local name space to a function object
285(a wrapper around the executable code for the function). This
286function object contains a reference to the current global name space
287as the global name space to be used when the function is called.
288\indexii{function}{name}
289\indexii{name}{binding}
290
291The function definition does not execute the function body; this gets
292executed only when the function is called.
293
Guido van Rossume9914961994-08-01 12:38:14 +0000294When one or more top-level parameters have the form {\em parameter =
295condition}, the function is said to have ``default parameter values''.
296Default parameter values are evaluated when the function definition is
297executed. For a parameter with a default value, the correponding
298argument may be omitted from a call, in which case the parameter's
299default value is substituted. If a parameter has a default value, all
300following parameters must also have a default value --- this is a
301syntactic restriction that is not expressed by the grammar.%
302\footnote{Currently this is not checked; instead,
Guido van Rossum31cce971995-01-04 19:17:34 +0000303{\tt def f(a=1,b)} is interpreted as {\tt def f(a=1,b=None)}.}
Guido van Rossume9914961994-08-01 12:38:14 +0000304\indexiii{default}{parameter}{value}
305
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000306Function call semantics are described in section \ref{calls}. When a
Guido van Rossume9914961994-08-01 12:38:14 +0000307user-defined function is called, first missing arguments for which a
308default value exists are supplied; then the arguments (a.k.a. actual
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000309parameters) are bound to the (formal) parameters, as follows:
310\indexii{function}{call}
311\indexiii{user-defined}{function}{call}
312\index{parameter}
313\index{argument}
314\indexii{parameter}{formal}
315\indexii{parameter}{actual}
316
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000317\begin{itemize}
318
319\item
320If there are no formal parameters, there must be no arguments.
321
322\item
323If the formal parameter list does not end in a star followed by an
324identifier, there must be exactly as many arguments as there are
325parameters in the formal parameter list (at the top level); the
326arguments are assigned to the formal parameters one by one. Note that
327the presence or absence of a trailing comma at the top level in either
328the formal or the actual parameter list makes no difference. The
329assignment to a formal parameter is performed as if the parameter
330occurs on the left hand side of an assignment statement whose right
331hand side's value is that of the argument.
332
333\item
334If the formal parameter list ends in a star followed by an identifier,
335preceded by zero or more comma-followed parameters, there must be at
336least as many arguments as there are parameters preceding the star.
337Call this number {\em N}. The first {\em N} arguments are assigned to
338the corresponding formal parameters in the way descibed above. A
339tuple containing the remaining arguments, if any, is then assigned to
340the identifier following the star. This variable will always be a
Guido van Rossume9914961994-08-01 12:38:14 +0000341tuple: if there are no extra arguments, its value is \verb@()@, if
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000342there is just one extra argument, it is a singleton tuple.
343\indexii{variable length}{parameter list}
344
345\end{itemize}
346
347Note that the `variable length parameter list' feature only works at
348the top level of the parameter list; individual parameters use a model
349corresponding more closely to that of ordinary assignment. While the
350latter model is generally preferable, because of the greater type
351safety it offers (wrong-sized tuples aren't silently mistreated),
352variable length parameter lists are a sufficiently accepted practice
353in most programming languages that a compromise has been worked out.
354(And anyway, assignment has no equivalent for empty argument lists.)
355
Guido van Rossume9914961994-08-01 12:38:14 +0000356It is also possible to create anonymous functions (functions not bound
357to a name), for immediate use in expressions. This uses lambda forms,
358described in section \ref{lambda}.
359\indexii{lambda}{form}
360
Guido van Rossumda43a4a1992-08-14 09:17:29 +0000361\section{Class definitions} \label{class}
362\indexii{class}{definition}
363
364A class definition defines a class object (see section \ref{types}):
365\obindex{class}
366
367\begin{verbatim}
368classdef: "class" classname [inheritance] ":" suite
369inheritance: "(" [condition_list] ")"
370classname: identifier
371\end{verbatim}
372
373A class definition is an executable statement. It first evaluates the
374inheritance list, if present. Each item in the inheritance list
375should evaluate to a class object. The class's suite is then executed
376in a new execution frame (see section \ref{execframes}), using a newly
377created local name space and the original global name space.
378(Usually, the suite contains only function definitions.) When the
379class's suite finishes execution, its execution frame is discarded but
380its local name space is saved. A class object is then created using
381the inheritance list for the base classes and the saved local name
382space for the attribute dictionary. The class name is bound to this
383class object in the original local name space.
384\index{inheritance}
385\indexii{class}{name}
386\indexii{name}{binding}
387\indexii{execution}{frame}