Guido van Rossum | da43a4a | 1992-08-14 09:17:29 +0000 | [diff] [blame] | 1 | \chapter{Compound statements} |
| 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 \verb\if\, \verb\while\ and \verb\for\ statements implement |
| 10 | traditional control flow constructs. \verb\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 \verb\if\ clause a following \verb\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 | \verb\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{verbatim} |
| 44 | compound_stmt: if_stmt | while_stmt | for_stmt |
| 45 | | try_stmt | funcdef | classdef |
| 46 | suite: stmt_list NEWLINE | NEWLINE INDENT statement+ DEDENT |
| 47 | statement: stmt_list NEWLINE | compound_stmt |
| 48 | stmt_list: simple_stmt (";" simple_stmt)* [";"] |
| 49 | \end{verbatim} |
| 50 | |
| 51 | Note that statements always end in a \verb\NEWLINE\ possibly followed |
| 52 | by a \verb\DEDENT\. |
| 53 | \index{NEWLINE token} |
| 54 | \index{DEDENT token} |
| 55 | |
| 56 | Also note that optional continuation clauses always begin with a |
| 57 | keyword that cannot start a statement, thus there are no ambiguities |
| 58 | (the `dangling \verb\else\' problem is solved in Python by requiring |
| 59 | nested \verb\if\ statements to be indented). |
| 60 | \indexii{dangling}{else} |
| 61 | |
| 62 | The formatting of the grammar rules in the following sections places |
| 63 | each clause on a separate line for clarity. |
| 64 | |
| 65 | \section{The {\tt if} statement} |
| 66 | \stindex{if} |
| 67 | |
| 68 | The \verb\if\ statement is used for conditional execution: |
| 69 | |
| 70 | \begin{verbatim} |
| 71 | if_stmt: "if" condition ":" suite |
| 72 | ("elif" condition ":" suite)* |
| 73 | ["else" ":" suite] |
| 74 | \end{verbatim} |
| 75 | |
| 76 | It selects exactly one of the suites by evaluating the conditions one |
| 77 | by one until one is found to be true (see section \ref{Booleans} for |
| 78 | the definition of true and false); then that suite is executed (and no |
| 79 | other part of the \verb\if\ statement is executed or evaluated). If |
| 80 | all conditions are false, the suite of the \verb\else\ clause, if |
| 81 | present, is executed. |
| 82 | \kwindex{elif} |
| 83 | \kwindex{else} |
| 84 | |
| 85 | \section{The {\tt while} statement} |
| 86 | \stindex{while} |
| 87 | \indexii{loop}{statement} |
| 88 | |
| 89 | The \verb\while\ statement is used for repeated execution as long as a |
| 90 | condition is true: |
| 91 | |
| 92 | \begin{verbatim} |
| 93 | while_stmt: "while" condition ":" suite |
| 94 | ["else" ":" suite] |
| 95 | \end{verbatim} |
| 96 | |
| 97 | This repeatedly tests the condition and, if it is true, executes the |
| 98 | first suite; if the condition is false (which may be the first time it |
| 99 | is tested) the suite of the \verb\else\ clause, if present, is |
| 100 | executed and the loop terminates. |
| 101 | \kwindex{else} |
| 102 | |
| 103 | A \verb\break\ statement executed in the first suite terminates the |
| 104 | loop without executing the \verb\else\ clause's suite. A |
| 105 | \verb\continue\ statement executed in the first suite skips the rest |
| 106 | of 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 | |
| 114 | The \verb\for\ statement is used to iterate over the elements of a |
| 115 | sequence (string, tuple or list): |
| 116 | \obindex{sequence} |
| 117 | |
| 118 | \begin{verbatim} |
| 119 | for_stmt: "for" target_list "in" condition_list ":" suite |
| 120 | ["else" ":" suite] |
| 121 | \end{verbatim} |
| 122 | |
| 123 | The condition list is evaluated once; it should yield a sequence. The |
| 124 | suite is then executed once for each item in the sequence, in the |
| 125 | order of ascending indices. Each item in turn is assigned to the |
| 126 | target list using the standard rules for assignments, and then the |
| 127 | suite is executed. When the items are exhausted (which is immediately |
| 128 | when the sequence is empty), the suite in the \verb\else\ clause, if |
| 129 | present, is executed, and the loop terminates. |
| 130 | \kwindex{in} |
| 131 | \kwindex{else} |
| 132 | \indexii{target}{list} |
| 133 | |
| 134 | A \verb\break\ statement executed in the first suite terminates the |
| 135 | loop without executing the \verb\else\ clause's suite. A |
| 136 | \verb\continue\ statement executed in the first suite skips the rest |
| 137 | of the suite and continues with the next item, or with the \verb\else\ |
| 138 | clause if there was no next item. |
| 139 | \stindex{break} |
| 140 | \stindex{continue} |
| 141 | |
| 142 | The suite may assign to the variable(s) in the target list; this does |
| 143 | not affect the next item assigned to it. |
| 144 | |
| 145 | The target list is not deleted when the loop is finished, but if the |
| 146 | sequence is empty, it will not have been assigned to at all by the |
| 147 | loop. |
| 148 | |
| 149 | Hint: the built-in function \verb\range()\ returns a sequence of |
| 150 | integers suitable to emulate the effect of Pascal's \verb\for i := a |
| 151 | to b do\; e.g. \verb\range(3)\ returns the list \verb\[0, 1, 2]\. |
| 152 | \bifuncindex{range} |
| 153 | \index{Pascal} |
| 154 | |
| 155 | {\bf Warning:} There is a subtlety when the sequence is being modified |
| 156 | by the loop (this can only occur for mutable sequences, i.e. lists). |
| 157 | An internal counter is used to keep track of which item is used next, |
| 158 | and this is incremented on each iteration. When this counter has |
| 159 | reached the length of the sequence the loop terminates. This means that |
| 160 | if the suite deletes the current (or a previous) item from the |
| 161 | sequence, the next item will be skipped (since it gets the index of |
| 162 | the current item which has already been treated). Likewise, if the |
| 163 | suite inserts an item in the sequence before the current item, the |
| 164 | current item will be treated again the next time through the loop. |
| 165 | This can lead to nasty bugs that can be avoided by making a temporary |
| 166 | copy using a slice of the whole sequence, e.g. |
| 167 | \index{loop!over mutable sequence} |
| 168 | \index{mutable sequence!loop over} |
| 169 | |
| 170 | \begin{verbatim} |
| 171 | for x in a[:]: |
| 172 | if x < 0: a.remove(x) |
| 173 | \end{verbatim} |
| 174 | |
Guido van Rossum | 7f8765d | 1993-10-11 12:54:58 +0000 | [diff] [blame^] | 175 | \section{The {\tt try} statement} \label{try} |
Guido van Rossum | da43a4a | 1992-08-14 09:17:29 +0000 | [diff] [blame] | 176 | \stindex{try} |
| 177 | |
| 178 | The \verb\try\ statement specifies exception handlers and/or cleanup |
| 179 | code for a group of statements: |
| 180 | |
| 181 | \begin{verbatim} |
| 182 | try_stmt: try_exc_stmt | try_fin_stmt |
| 183 | try_exc_stmt: "try" ":" suite |
| 184 | ("except" [condition ["," target]] ":" suite)+ |
| 185 | try_fin_stmt: "try" ":" suite |
| 186 | "finally" ":" suite |
| 187 | \end{verbatim} |
| 188 | |
| 189 | There are two forms of \verb\try\ statement: \verb\try...except\ and |
| 190 | \verb\try...finally\. These forms cannot be mixed. |
| 191 | |
| 192 | The \verb\try...except\ form specifies one or more exception handlers |
| 193 | (the \verb\except\ clauses). When no exception occurs in the |
| 194 | \verb\try\ clause, no exception handler is executed. When an |
| 195 | exception occurs in the \verb\try\ suite, a search for an exception |
| 196 | handler is started. This inspects the except clauses in turn until |
| 197 | one is found that matches the exception. A condition-less except |
| 198 | clause, if present, must be last; it matches any exception. For an |
| 199 | except clause with a condition, that condition is evaluated, and the |
| 200 | clause matches the exception if the resulting object is ``compatible'' |
| 201 | with the exception. An object is compatible with an exception if it |
| 202 | is either the object that identifies the exception or it is a tuple |
| 203 | containing an item that is compatible with the exception. Note that |
| 204 | the object identities must match, i.e. it must be the same object, not |
| 205 | just an object with the same value. |
| 206 | \kwindex{except} |
| 207 | |
| 208 | If no except clause matches the exception, the search for an exception |
| 209 | handler continues in the surrounding code and on the invocation stack. |
| 210 | |
| 211 | If the evaluation of a condition in the header of an except clause |
| 212 | raises an exception, the original search for a handler is cancelled |
| 213 | and a search starts for the new exception in the surrounding code and |
| 214 | on the call stack (it is treated as if the entire \verb\try\ statement |
| 215 | raised the exception). |
| 216 | |
| 217 | When a matching except clause is found, the exception's parameter is |
| 218 | assigned to the target specified in that except clause, if present, |
| 219 | and the except clause's suite is executed. When the end of this suite |
| 220 | is reached, execution continues normally after the entire try |
| 221 | statement. (This means that if two nested handlers exist for the same |
| 222 | exception, and the exception occurs in the try clause of the inner |
| 223 | handler, the outer handler will not handle the exception.) |
| 224 | |
Guido van Rossum | 7f8765d | 1993-10-11 12:54:58 +0000 | [diff] [blame^] | 225 | Before an except clause's suite is executed, details about the |
| 226 | exception are assigned to three variables in the \verb\sys\ module: |
| 227 | \verb\sys.exc_type\ receives the object identifying the exception; |
| 228 | \verb\sys.exc_value\ receives the exception's parameter; |
| 229 | \verb\sys.exc_traceback\ receives a traceback object (see section |
| 230 | \ref{traceback}) identifying the point in the program where the |
| 231 | exception occurred. |
| 232 | \bimodindex{sys} |
| 233 | \ttindex{exc_type} |
| 234 | \ttindex{exc_value} |
| 235 | \ttindex{exc_traceback} |
| 236 | \obindex{traceback} |
| 237 | |
Guido van Rossum | da43a4a | 1992-08-14 09:17:29 +0000 | [diff] [blame] | 238 | The \verb\try...finally\ form specifies a `cleanup' handler. The |
| 239 | \verb\try\ clause is executed. When no exception occurs, the |
| 240 | \verb\finally\ clause is executed. When an exception occurs in the |
| 241 | \verb\try\ clause, the exception is temporarily saved, the |
| 242 | \verb\finally\ clause is executed, and then the saved exception is |
| 243 | re-raised. If the \verb\finally\ clause raises another exception or |
| 244 | executes a \verb\return\, \verb\break\ or \verb\continue\ statement, |
| 245 | the saved exception is lost. |
| 246 | \kwindex{finally} |
| 247 | |
| 248 | When a \verb\return\ or \verb\break\ statement is executed in the |
| 249 | \verb\try\ suite of a \verb\try...finally\ statement, the |
| 250 | \verb\finally\ clause is also executed `on the way out'. A |
| 251 | \verb\continue\ statement is illegal in the \verb\try\ clause. (The |
| 252 | reason is a problem with the current implementation --- this |
| 253 | restriction may be lifted in the future). |
| 254 | \stindex{return} |
| 255 | \stindex{break} |
| 256 | \stindex{continue} |
| 257 | |
| 258 | \section{Function definitions} \label{function} |
| 259 | \indexii{function}{definition} |
| 260 | |
| 261 | A function definition defines a user-defined function object (see |
| 262 | section \ref{types}): |
| 263 | \obindex{user-defined function} |
| 264 | \obindex{function} |
| 265 | |
| 266 | \begin{verbatim} |
| 267 | funcdef: "def" funcname "(" [parameter_list] ")" ":" suite |
| 268 | parameter_list: (parameter ",")* ("*" identifier | parameter [","]) |
| 269 | sublist: parameter ("," parameter)* [","] |
| 270 | parameter: identifier | "(" sublist ")" |
| 271 | funcname: identifier |
| 272 | \end{verbatim} |
| 273 | |
| 274 | A function definition is an executable statement. Its execution binds |
| 275 | the function name in the current local name space to a function object |
| 276 | (a wrapper around the executable code for the function). This |
| 277 | function object contains a reference to the current global name space |
| 278 | as the global name space to be used when the function is called. |
| 279 | \indexii{function}{name} |
| 280 | \indexii{name}{binding} |
| 281 | |
| 282 | The function definition does not execute the function body; this gets |
| 283 | executed only when the function is called. |
| 284 | |
| 285 | Function call semantics are described in section \ref{calls}. When a |
| 286 | user-defined function is called, the arguments (a.k.a. actual |
| 287 | parameters) are bound to the (formal) parameters, as follows: |
| 288 | \indexii{function}{call} |
| 289 | \indexiii{user-defined}{function}{call} |
| 290 | \index{parameter} |
| 291 | \index{argument} |
| 292 | \indexii{parameter}{formal} |
| 293 | \indexii{parameter}{actual} |
| 294 | |
| 295 | \begin{itemize} |
| 296 | |
| 297 | \item |
| 298 | If there are no formal parameters, there must be no arguments. |
| 299 | |
| 300 | \item |
| 301 | If the formal parameter list does not end in a star followed by an |
| 302 | identifier, there must be exactly as many arguments as there are |
| 303 | parameters in the formal parameter list (at the top level); the |
| 304 | arguments are assigned to the formal parameters one by one. Note that |
| 305 | the presence or absence of a trailing comma at the top level in either |
| 306 | the formal or the actual parameter list makes no difference. The |
| 307 | assignment to a formal parameter is performed as if the parameter |
| 308 | occurs on the left hand side of an assignment statement whose right |
| 309 | hand side's value is that of the argument. |
| 310 | |
| 311 | \item |
| 312 | If the formal parameter list ends in a star followed by an identifier, |
| 313 | preceded by zero or more comma-followed parameters, there must be at |
| 314 | least as many arguments as there are parameters preceding the star. |
| 315 | Call this number {\em N}. The first {\em N} arguments are assigned to |
| 316 | the corresponding formal parameters in the way descibed above. A |
| 317 | tuple containing the remaining arguments, if any, is then assigned to |
| 318 | the identifier following the star. This variable will always be a |
| 319 | tuple: if there are no extra arguments, its value is \verb\()\, if |
| 320 | there is just one extra argument, it is a singleton tuple. |
| 321 | \indexii{variable length}{parameter list} |
| 322 | |
| 323 | \end{itemize} |
| 324 | |
| 325 | Note that the `variable length parameter list' feature only works at |
| 326 | the top level of the parameter list; individual parameters use a model |
| 327 | corresponding more closely to that of ordinary assignment. While the |
| 328 | latter model is generally preferable, because of the greater type |
| 329 | safety it offers (wrong-sized tuples aren't silently mistreated), |
| 330 | variable length parameter lists are a sufficiently accepted practice |
| 331 | in most programming languages that a compromise has been worked out. |
| 332 | (And anyway, assignment has no equivalent for empty argument lists.) |
| 333 | |
| 334 | \section{Class definitions} \label{class} |
| 335 | \indexii{class}{definition} |
| 336 | |
| 337 | A class definition defines a class object (see section \ref{types}): |
| 338 | \obindex{class} |
| 339 | |
| 340 | \begin{verbatim} |
| 341 | classdef: "class" classname [inheritance] ":" suite |
| 342 | inheritance: "(" [condition_list] ")" |
| 343 | classname: identifier |
| 344 | \end{verbatim} |
| 345 | |
| 346 | A class definition is an executable statement. It first evaluates the |
| 347 | inheritance list, if present. Each item in the inheritance list |
| 348 | should evaluate to a class object. The class's suite is then executed |
| 349 | in a new execution frame (see section \ref{execframes}), using a newly |
| 350 | created local name space and the original global name space. |
| 351 | (Usually, the suite contains only function definitions.) When the |
| 352 | class's suite finishes execution, its execution frame is discarded but |
| 353 | its local name space is saved. A class object is then created using |
| 354 | the inheritance list for the base classes and the saved local name |
| 355 | space for the attribute dictionary. The class name is bound to this |
| 356 | class object in the original local name space. |
| 357 | \index{inheritance} |
| 358 | \indexii{class}{name} |
| 359 | \indexii{name}{binding} |
| 360 | \indexii{execution}{frame} |