Commit | Line | Data |
---|---|---|
920dae64 AT |
1 | <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> |
2 | <html> | |
3 | <head> | |
4 | <link rel="STYLESHEET" href="tut.css" type='text/css' /> | |
5 | <link rel="SHORTCUT ICON" href="../icons/pyfav.png" type="image/png" /> | |
6 | <link rel='start' href='../index.html' title='Python Documentation Index' /> | |
7 | <link rel="first" href="tut.html" title='Python Tutorial' /> | |
8 | <link rel='contents' href='node2.html' title="Contents" /> | |
9 | <link rel='index' href='node19.html' title='Index' /> | |
10 | <link rel='last' href='about.html' title='About this document...' /> | |
11 | <link rel='help' href='about.html' title='About this document...' /> | |
12 | <link rel="next" href="node7.html" /> | |
13 | <link rel="prev" href="node5.html" /> | |
14 | <link rel="parent" href="tut.html" /> | |
15 | <link rel="next" href="node7.html" /> | |
16 | <meta name='aesop' content='information' /> | |
17 | <title>4. More Control Flow Tools </title> | |
18 | </head> | |
19 | <body> | |
20 | <DIV CLASS="navigation"> | |
21 | <div id='top-navigation-panel' xml:id='top-navigation-panel'> | |
22 | <table align="center" width="100%" cellpadding="0" cellspacing="2"> | |
23 | <tr> | |
24 | <td class='online-navigation'><a rel="prev" title="3. An Informal Introduction" | |
25 | href="node5.html"><img src='../icons/previous.png' | |
26 | border='0' height='32' alt='Previous Page' width='32' /></A></td> | |
27 | <td class='online-navigation'><a rel="parent" title="Python Tutorial" | |
28 | href="tut.html"><img src='../icons/up.png' | |
29 | border='0' height='32' alt='Up One Level' width='32' /></A></td> | |
30 | <td class='online-navigation'><a rel="next" title="5. Data Structures" | |
31 | href="node7.html"><img src='../icons/next.png' | |
32 | border='0' height='32' alt='Next Page' width='32' /></A></td> | |
33 | <td align="center" width="100%">Python Tutorial</td> | |
34 | <td class='online-navigation'><a rel="contents" title="Table of Contents" | |
35 | href="node2.html"><img src='../icons/contents.png' | |
36 | border='0' height='32' alt='Contents' width='32' /></A></td> | |
37 | <td class='online-navigation'><img src='../icons/blank.png' | |
38 | border='0' height='32' alt='' width='32' /></td> | |
39 | <td class='online-navigation'><a rel="index" title="Index" | |
40 | href="node19.html"><img src='../icons/index.png' | |
41 | border='0' height='32' alt='Index' width='32' /></A></td> | |
42 | </tr></table> | |
43 | <div class='online-navigation'> | |
44 | <b class="navlabel">Previous:</b> | |
45 | <a class="sectref" rel="prev" href="node5.html">3. An Informal Introduction</A> | |
46 | <b class="navlabel">Up:</b> | |
47 | <a class="sectref" rel="parent" href="tut.html">Python Tutorial</A> | |
48 | <b class="navlabel">Next:</b> | |
49 | <a class="sectref" rel="next" href="node7.html">5. Data Structures</A> | |
50 | </div> | |
51 | <hr /></div> | |
52 | </DIV> | |
53 | <!--End of Navigation Panel--> | |
54 | <div class='online-navigation'> | |
55 | <!--Table of Child-Links--> | |
56 | <A NAME="CHILD_LINKS"><STRONG>Subsections</STRONG></a> | |
57 | ||
58 | <UL CLASS="ChildLinks"> | |
59 | <LI><A href="node6.html#SECTION006100000000000000000">4.1 <tt class="keyword">if</tt> Statements</a> | |
60 | <LI><A href="node6.html#SECTION006200000000000000000">4.2 <tt class="keyword">for</tt> Statements</a> | |
61 | <LI><A href="node6.html#SECTION006300000000000000000">4.3 The <tt class="function">range()</tt> Function</a> | |
62 | <LI><A href="node6.html#SECTION006400000000000000000">4.4 <tt class="keyword">break</tt> and <tt class="keyword">continue</tt> Statements, and | |
63 | <tt class="keyword">else</tt> Clauses on Loops</a> | |
64 | <LI><A href="node6.html#SECTION006500000000000000000">4.5 <tt class="keyword">pass</tt> Statements</a> | |
65 | <LI><A href="node6.html#SECTION006600000000000000000">4.6 Defining Functions</a> | |
66 | <LI><A href="node6.html#SECTION006700000000000000000">4.7 More on Defining Functions</a> | |
67 | <UL> | |
68 | <LI><A href="node6.html#SECTION006710000000000000000">4.7.1 Default Argument Values</a> | |
69 | <LI><A href="node6.html#SECTION006720000000000000000">4.7.2 Keyword Arguments</a> | |
70 | <LI><A href="node6.html#SECTION006730000000000000000">4.7.3 Arbitrary Argument Lists</a> | |
71 | <LI><A href="node6.html#SECTION006740000000000000000">4.7.4 Unpacking Argument Lists</a> | |
72 | <LI><A href="node6.html#SECTION006750000000000000000">4.7.5 Lambda Forms</a> | |
73 | <LI><A href="node6.html#SECTION006760000000000000000">4.7.6 Documentation Strings</a> | |
74 | </ul></ul> | |
75 | <!--End of Table of Child-Links--> | |
76 | </div> | |
77 | <HR> | |
78 | ||
79 | <H1><A NAME="SECTION006000000000000000000"></A><A NAME="moreControl"></A> | |
80 | <BR> | |
81 | 4. More Control Flow Tools | |
82 | </H1> | |
83 | ||
84 | <P> | |
85 | Besides the <tt class="keyword">while</tt> statement just introduced, Python knows | |
86 | the usual control flow statements known from other languages, with | |
87 | some twists. | |
88 | ||
89 | <P> | |
90 | ||
91 | <H1><A NAME="SECTION006100000000000000000"></A><A NAME="if"></A> | |
92 | <BR> | |
93 | 4.1 <tt class="keyword">if</tt> Statements | |
94 | </H1> | |
95 | ||
96 | <P> | |
97 | Perhaps the most well-known statement type is the | |
98 | <tt class="keyword">if</tt> statement. For example: | |
99 | ||
100 | <P> | |
101 | <div class="verbatim"><pre> | |
102 | >>> x = int(raw_input("Please enter an integer: ")) | |
103 | >>> if x < 0: | |
104 | ... x = 0 | |
105 | ... print 'Negative changed to zero' | |
106 | ... elif x == 0: | |
107 | ... print 'Zero' | |
108 | ... elif x == 1: | |
109 | ... print 'Single' | |
110 | ... else: | |
111 | ... print 'More' | |
112 | ... | |
113 | </pre></div> | |
114 | ||
115 | <P> | |
116 | There can be zero or more <tt class="keyword">elif</tt> parts, and the | |
117 | <tt class="keyword">else</tt> part is optional. The keyword `<tt class="keyword">elif</tt>' is | |
118 | short for `else if', and is useful to avoid excessive indentation. An | |
119 | <tt class="keyword">if</tt> ... <tt class="keyword">elif</tt> ... <tt class="keyword">elif</tt> ... sequence | |
120 | is a substitute for the <tt class="keyword">switch</tt> or | |
121 | <tt class="keyword">case</tt> statements found in other languages. | |
122 | ||
123 | <P> | |
124 | ||
125 | <H1><A NAME="SECTION006200000000000000000"></A><A NAME="for"></A> | |
126 | <BR> | |
127 | 4.2 <tt class="keyword">for</tt> Statements | |
128 | </H1> | |
129 | ||
130 | <P> | |
131 | The <tt class="keyword">for</tt><a id='l2h-4' xml:id='l2h-4'></a> statement in Python differs a bit from | |
132 | what you may be used to in C or Pascal. Rather than always | |
133 | iterating over an arithmetic progression of numbers (like in Pascal), | |
134 | or giving the user the ability to define both the iteration step and | |
135 | halting condition (as C), Python's | |
136 | <tt class="keyword">for</tt><a id='l2h-5' xml:id='l2h-5'></a> statement iterates over the items of any | |
137 | sequence (a list or a string), in the order that they appear in | |
138 | the sequence. For example (no pun intended): | |
139 | ||
140 | <P> | |
141 | <div class="verbatim"><pre> | |
142 | >>> # Measure some strings: | |
143 | ... a = ['cat', 'window', 'defenestrate'] | |
144 | >>> for x in a: | |
145 | ... print x, len(x) | |
146 | ... | |
147 | cat 3 | |
148 | window 6 | |
149 | defenestrate 12 | |
150 | </pre></div> | |
151 | ||
152 | <P> | |
153 | It is not safe to modify the sequence being iterated over in the loop | |
154 | (this can only happen for mutable sequence types, such as lists). If | |
155 | you need to modify the list you are iterating over (for example, to | |
156 | duplicate selected items) you must iterate over a copy. The slice | |
157 | notation makes this particularly convenient: | |
158 | ||
159 | <P> | |
160 | <div class="verbatim"><pre> | |
161 | >>> for x in a[:]: # make a slice copy of the entire list | |
162 | ... if len(x) > 6: a.insert(0, x) | |
163 | ... | |
164 | >>> a | |
165 | ['defenestrate', 'cat', 'window', 'defenestrate'] | |
166 | </pre></div> | |
167 | ||
168 | <P> | |
169 | ||
170 | <H1><A NAME="SECTION006300000000000000000"></A><A NAME="range"></A> | |
171 | <BR> | |
172 | 4.3 The <tt class="function">range()</tt> Function | |
173 | </H1> | |
174 | ||
175 | <P> | |
176 | If you do need to iterate over a sequence of numbers, the built-in | |
177 | function <tt class="function">range()</tt> comes in handy. It generates lists | |
178 | containing arithmetic progressions: | |
179 | ||
180 | <P> | |
181 | <div class="verbatim"><pre> | |
182 | >>> range(10) | |
183 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] | |
184 | </pre></div> | |
185 | ||
186 | <P> | |
187 | The given end point is never part of the generated list; | |
188 | <code>range(10)</code> generates a list of 10 values, the legal | |
189 | indices for items of a sequence of length 10. It is possible to let | |
190 | the range start at another number, or to specify a different increment | |
191 | (even negative; sometimes this is called the `step'): | |
192 | ||
193 | <P> | |
194 | <div class="verbatim"><pre> | |
195 | >>> range(5, 10) | |
196 | [5, 6, 7, 8, 9] | |
197 | >>> range(0, 10, 3) | |
198 | [0, 3, 6, 9] | |
199 | >>> range(-10, -100, -30) | |
200 | [-10, -40, -70] | |
201 | </pre></div> | |
202 | ||
203 | <P> | |
204 | To iterate over the indices of a sequence, combine | |
205 | <tt class="function">range()</tt> and <tt class="function">len()</tt> as follows: | |
206 | ||
207 | <P> | |
208 | <div class="verbatim"><pre> | |
209 | >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] | |
210 | >>> for i in range(len(a)): | |
211 | ... print i, a[i] | |
212 | ... | |
213 | 0 Mary | |
214 | 1 had | |
215 | 2 a | |
216 | 3 little | |
217 | 4 lamb | |
218 | </pre></div> | |
219 | ||
220 | <P> | |
221 | ||
222 | <H1><A NAME="SECTION006400000000000000000"></A><A NAME="break"></A> | |
223 | <BR> | |
224 | 4.4 <tt class="keyword">break</tt> and <tt class="keyword">continue</tt> Statements, and | |
225 | <tt class="keyword">else</tt> Clauses on Loops | |
226 | ||
227 | </H1> | |
228 | ||
229 | <P> | |
230 | The <tt class="keyword">break</tt> statement, like in C, breaks out of the smallest | |
231 | enclosing <tt class="keyword">for</tt> or <tt class="keyword">while</tt> loop. | |
232 | ||
233 | <P> | |
234 | The <tt class="keyword">continue</tt> statement, also borrowed from C, continues | |
235 | with the next iteration of the loop. | |
236 | ||
237 | <P> | |
238 | Loop statements may have an <code>else</code> clause; it is executed when | |
239 | the loop terminates through exhaustion of the list (with | |
240 | <tt class="keyword">for</tt>) or when the condition becomes false (with | |
241 | <tt class="keyword">while</tt>), but not when the loop is terminated by a | |
242 | <tt class="keyword">break</tt> statement. This is exemplified by the following loop, | |
243 | which searches for prime numbers: | |
244 | ||
245 | <P> | |
246 | <div class="verbatim"><pre> | |
247 | >>> for n in range(2, 10): | |
248 | ... for x in range(2, n): | |
249 | ... if n % x == 0: | |
250 | ... print n, 'equals', x, '*', n/x | |
251 | ... break | |
252 | ... else: | |
253 | ... # loop fell through without finding a factor | |
254 | ... print n, 'is a prime number' | |
255 | ... | |
256 | 2 is a prime number | |
257 | 3 is a prime number | |
258 | 4 equals 2 * 2 | |
259 | 5 is a prime number | |
260 | 6 equals 2 * 3 | |
261 | 7 is a prime number | |
262 | 8 equals 2 * 4 | |
263 | 9 equals 3 * 3 | |
264 | </pre></div> | |
265 | ||
266 | <P> | |
267 | ||
268 | <H1><A NAME="SECTION006500000000000000000"></A><A NAME="pass"></A> | |
269 | <BR> | |
270 | 4.5 <tt class="keyword">pass</tt> Statements | |
271 | </H1> | |
272 | ||
273 | <P> | |
274 | The <tt class="keyword">pass</tt> statement does nothing. | |
275 | It can be used when a statement is required syntactically but the | |
276 | program requires no action. | |
277 | For example: | |
278 | ||
279 | <P> | |
280 | <div class="verbatim"><pre> | |
281 | >>> while True: | |
282 | ... pass # Busy-wait for keyboard interrupt | |
283 | ... | |
284 | </pre></div> | |
285 | ||
286 | <P> | |
287 | ||
288 | <H1><A NAME="SECTION006600000000000000000"></A><A NAME="functions"></A> | |
289 | <BR> | |
290 | 4.6 Defining Functions | |
291 | </H1> | |
292 | ||
293 | <P> | |
294 | We can create a function that writes the Fibonacci series to an | |
295 | arbitrary boundary: | |
296 | ||
297 | <P> | |
298 | <div class="verbatim"><pre> | |
299 | >>> def fib(n): # write Fibonacci series up to n | |
300 | ... """Print a Fibonacci series up to n.""" | |
301 | ... a, b = 0, 1 | |
302 | ... while b < n: | |
303 | ... print b, | |
304 | ... a, b = b, a+b | |
305 | ... | |
306 | >>> # Now call the function we just defined: | |
307 | ... fib(2000) | |
308 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 | |
309 | </pre></div> | |
310 | ||
311 | <P> | |
312 | The keyword <tt class="keyword">def</tt> introduces a function <em>definition</em>. It | |
313 | must be followed by the function name and the parenthesized list of | |
314 | formal parameters. The statements that form the body of the function | |
315 | start at the next line, and must be indented. The first statement of | |
316 | the function body can optionally be a string literal; this string | |
317 | literal is the function's <a id='l2h-6' xml:id='l2h-6'></a>documentation | |
318 | string, or <i class="dfn">docstring</i>.<a id='l2h-7' xml:id='l2h-7'></a> | |
319 | ||
320 | <P> | |
321 | There are tools which use docstrings to automatically produce online | |
322 | or printed documentation, or to let the user interactively browse | |
323 | through code; it's good practice to include docstrings in code that | |
324 | you write, so try to make a habit of it. | |
325 | ||
326 | <P> | |
327 | The <em>execution</em> of a function introduces a new symbol table used | |
328 | for the local variables of the function. More precisely, all variable | |
329 | assignments in a function store the value in the local symbol table; | |
330 | whereas variable references first look in the local symbol table, then | |
331 | in the global symbol table, and then in the table of built-in names. | |
332 | Thus, global variables cannot be directly assigned a value within a | |
333 | function (unless named in a <tt class="keyword">global</tt> statement), although | |
334 | they may be referenced. | |
335 | ||
336 | <P> | |
337 | The actual parameters (arguments) to a function call are introduced in | |
338 | the local symbol table of the called function when it is called; thus, | |
339 | arguments are passed using <em>call by value</em> (where the | |
340 | <em>value</em> is always an object <em>reference</em>, not the value of | |
341 | the object).<A NAME="tex2html2" | |
342 | HREF="#foot1775"><SUP>4.1</SUP></A> When a function calls another function, a new local symbol table is | |
343 | created for that call. | |
344 | ||
345 | <P> | |
346 | A function definition introduces the function name in the current | |
347 | symbol table. The value of the function name | |
348 | has a type that is recognized by the interpreter as a user-defined | |
349 | function. This value can be assigned to another name which can then | |
350 | also be used as a function. This serves as a general renaming | |
351 | mechanism: | |
352 | ||
353 | <P> | |
354 | <div class="verbatim"><pre> | |
355 | >>> fib | |
356 | <function fib at 10042ed0> | |
357 | >>> f = fib | |
358 | >>> f(100) | |
359 | 1 1 2 3 5 8 13 21 34 55 89 | |
360 | </pre></div> | |
361 | ||
362 | <P> | |
363 | You might object that <code>fib</code> is not a function but a procedure. In | |
364 | Python, like in C, procedures are just functions that don't return a | |
365 | value. In fact, technically speaking, procedures do return a value, | |
366 | albeit a rather boring one. This value is called <code>None</code> (it's a | |
367 | built-in name). Writing the value <code>None</code> is normally suppressed by | |
368 | the interpreter if it would be the only value written. You can see it | |
369 | if you really want to: | |
370 | ||
371 | <P> | |
372 | <div class="verbatim"><pre> | |
373 | >>> print fib(0) | |
374 | None | |
375 | </pre></div> | |
376 | ||
377 | <P> | |
378 | It is simple to write a function that returns a list of the numbers of | |
379 | the Fibonacci series, instead of printing it: | |
380 | ||
381 | <P> | |
382 | <div class="verbatim"><pre> | |
383 | >>> def fib2(n): # return Fibonacci series up to n | |
384 | ... """Return a list containing the Fibonacci series up to n.""" | |
385 | ... result = [] | |
386 | ... a, b = 0, 1 | |
387 | ... while b < n: | |
388 | ... result.append(b) # see below | |
389 | ... a, b = b, a+b | |
390 | ... return result | |
391 | ... | |
392 | >>> f100 = fib2(100) # call it | |
393 | >>> f100 # write the result | |
394 | [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] | |
395 | </pre></div> | |
396 | ||
397 | <P> | |
398 | This example, as usual, demonstrates some new Python features: | |
399 | ||
400 | <P> | |
401 | ||
402 | <UL> | |
403 | <LI>The <tt class="keyword">return</tt> statement returns with a value from a function. | |
404 | <tt class="keyword">return</tt> without an expression argument returns <code>None</code>. | |
405 | Falling off the end of a procedure also returns <code>None</code>. | |
406 | ||
407 | <P> | |
408 | </LI> | |
409 | <LI>The statement <code>result.append(b)</code> calls a <em>method</em> of the list | |
410 | object <code>result</code>. A method is a function that `belongs' to an | |
411 | object and is named <code>obj.methodname</code>, where <code>obj</code> is some | |
412 | object (this may be an expression), and <code>methodname</code> is the name | |
413 | of a method that is defined by the object's type. Different types | |
414 | define different methods. Methods of different types may have the | |
415 | same name without causing ambiguity. (It is possible to define your | |
416 | own object types and methods, using <em>classes</em>, as discussed later | |
417 | in this tutorial.) | |
418 | The method <tt class="method">append()</tt> shown in the example is defined for | |
419 | list objects; it adds a new element at the end of the list. In this | |
420 | example it is equivalent to "<tt class="samp">result = result + [b]</tt>", but more | |
421 | efficient. | |
422 | ||
423 | <P> | |
424 | </LI> | |
425 | </UL> | |
426 | ||
427 | <P> | |
428 | ||
429 | <H1><A NAME="SECTION006700000000000000000"></A><A NAME="defining"></A> | |
430 | <BR> | |
431 | 4.7 More on Defining Functions | |
432 | </H1> | |
433 | ||
434 | <P> | |
435 | It is also possible to define functions with a variable number of | |
436 | arguments. There are three forms, which can be combined. | |
437 | ||
438 | <P> | |
439 | ||
440 | <H2><A NAME="SECTION006710000000000000000"></A><A NAME="defaultArgs"></A> | |
441 | <BR> | |
442 | 4.7.1 Default Argument Values | |
443 | </H2> | |
444 | ||
445 | <P> | |
446 | The most useful form is to specify a default value for one or more | |
447 | arguments. This creates a function that can be called with fewer | |
448 | arguments than it is defined to allow. For example: | |
449 | ||
450 | <P> | |
451 | <div class="verbatim"><pre> | |
452 | def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): | |
453 | while True: | |
454 | ok = raw_input(prompt) | |
455 | if ok in ('y', 'ye', 'yes'): return True | |
456 | if ok in ('n', 'no', 'nop', 'nope'): return False | |
457 | retries = retries - 1 | |
458 | if retries < 0: raise IOError, 'refusenik user' | |
459 | print complaint | |
460 | </pre></div> | |
461 | ||
462 | <P> | |
463 | This function can be called either like this: | |
464 | <code>ask_ok('Do you really want to quit?')</code> or like this: | |
465 | <code>ask_ok('OK to overwrite the file?', 2)</code>. | |
466 | ||
467 | <P> | |
468 | This example also introduces the <tt class="keyword">in</tt> keyword. This tests | |
469 | whether or not a sequence contains a certain value. | |
470 | ||
471 | <P> | |
472 | The default values are evaluated at the point of function definition | |
473 | in the <em>defining</em> scope, so that | |
474 | ||
475 | <P> | |
476 | <div class="verbatim"><pre> | |
477 | i = 5 | |
478 | ||
479 | def f(arg=i): | |
480 | print arg | |
481 | ||
482 | i = 6 | |
483 | f() | |
484 | </pre></div> | |
485 | ||
486 | <P> | |
487 | will print <code>5</code>. | |
488 | ||
489 | <P> | |
490 | <strong>Important warning:</strong> The default value is evaluated only once. | |
491 | This makes a difference when the default is a mutable object such as a | |
492 | list, dictionary, or instances of most classes. For example, the | |
493 | following function accumulates the arguments passed to it on | |
494 | subsequent calls: | |
495 | ||
496 | <P> | |
497 | <div class="verbatim"><pre> | |
498 | def f(a, L=[]): | |
499 | L.append(a) | |
500 | return L | |
501 | ||
502 | print f(1) | |
503 | print f(2) | |
504 | print f(3) | |
505 | </pre></div> | |
506 | ||
507 | <P> | |
508 | This will print | |
509 | ||
510 | <P> | |
511 | <div class="verbatim"><pre> | |
512 | [1] | |
513 | [1, 2] | |
514 | [1, 2, 3] | |
515 | </pre></div> | |
516 | ||
517 | <P> | |
518 | If you don't want the default to be shared between subsequent calls, | |
519 | you can write the function like this instead: | |
520 | ||
521 | <P> | |
522 | <div class="verbatim"><pre> | |
523 | def f(a, L=None): | |
524 | if L is None: | |
525 | L = [] | |
526 | L.append(a) | |
527 | return L | |
528 | </pre></div> | |
529 | ||
530 | <P> | |
531 | ||
532 | <H2><A NAME="SECTION006720000000000000000"></A><A NAME="keywordArgs"></A> | |
533 | <BR> | |
534 | 4.7.2 Keyword Arguments | |
535 | </H2> | |
536 | ||
537 | <P> | |
538 | Functions can also be called using | |
539 | keyword arguments of the form "<tt class="samp"><var>keyword</var> = <var>value</var></tt>". For | |
540 | instance, the following function: | |
541 | ||
542 | <P> | |
543 | <div class="verbatim"><pre> | |
544 | def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): | |
545 | print "-- This parrot wouldn't", action, | |
546 | print "if you put", voltage, "volts through it." | |
547 | print "-- Lovely plumage, the", type | |
548 | print "-- It's", state, "!" | |
549 | </pre></div> | |
550 | ||
551 | <P> | |
552 | could be called in any of the following ways: | |
553 | ||
554 | <P> | |
555 | <div class="verbatim"><pre> | |
556 | parrot(1000) | |
557 | parrot(action = 'VOOOOOM', voltage = 1000000) | |
558 | parrot('a thousand', state = 'pushing up the daisies') | |
559 | parrot('a million', 'bereft of life', 'jump') | |
560 | </pre></div> | |
561 | ||
562 | <P> | |
563 | but the following calls would all be invalid: | |
564 | ||
565 | <P> | |
566 | <div class="verbatim"><pre> | |
567 | parrot() # required argument missing | |
568 | parrot(voltage=5.0, 'dead') # non-keyword argument following keyword | |
569 | parrot(110, voltage=220) # duplicate value for argument | |
570 | parrot(actor='John Cleese') # unknown keyword | |
571 | </pre></div> | |
572 | ||
573 | <P> | |
574 | In general, an argument list must have any positional arguments | |
575 | followed by any keyword arguments, where the keywords must be chosen | |
576 | from the formal parameter names. It's not important whether a formal | |
577 | parameter has a default value or not. No argument may receive a | |
578 | value more than once -- formal parameter names corresponding to | |
579 | positional arguments cannot be used as keywords in the same calls. | |
580 | Here's an example that fails due to this restriction: | |
581 | ||
582 | <P> | |
583 | <div class="verbatim"><pre> | |
584 | >>> def function(a): | |
585 | ... pass | |
586 | ... | |
587 | >>> function(0, a=0) | |
588 | Traceback (most recent call last): | |
589 | File "<stdin>", line 1, in ? | |
590 | TypeError: function() got multiple values for keyword argument 'a' | |
591 | </pre></div> | |
592 | ||
593 | <P> | |
594 | When a final formal parameter of the form <code>**<var>name</var></code> is | |
595 | present, it receives a <a class="ulink" href="../lib/typesmapping.html" | |
596 | >dictionary</a> | |
597 | containing all keyword arguments except for those corresponding to | |
598 | a formal parameter. This may be | |
599 | combined with a formal parameter of the form | |
600 | <code>*<var>name</var></code> (described in the next subsection) which receives a | |
601 | tuple containing the positional arguments beyond the formal parameter | |
602 | list. (<code>*<var>name</var></code> must occur before <code>**<var>name</var></code>.) | |
603 | For example, if we define a function like this: | |
604 | ||
605 | <P> | |
606 | <div class="verbatim"><pre> | |
607 | def cheeseshop(kind, *arguments, **keywords): | |
608 | print "-- Do you have any", kind, '?' | |
609 | print "-- I'm sorry, we're all out of", kind | |
610 | for arg in arguments: print arg | |
611 | print '-'*40 | |
612 | keys = keywords.keys() | |
613 | keys.sort() | |
614 | for kw in keys: print kw, ':', keywords[kw] | |
615 | </pre></div> | |
616 | ||
617 | <P> | |
618 | It could be called like this: | |
619 | ||
620 | <P> | |
621 | <div class="verbatim"><pre> | |
622 | cheeseshop('Limburger', "It's very runny, sir.", | |
623 | "It's really very, VERY runny, sir.", | |
624 | client='John Cleese', | |
625 | shopkeeper='Michael Palin', | |
626 | sketch='Cheese Shop Sketch') | |
627 | </pre></div> | |
628 | ||
629 | <P> | |
630 | and of course it would print: | |
631 | ||
632 | <P> | |
633 | <div class="verbatim"><pre> | |
634 | -- Do you have any Limburger ? | |
635 | -- I'm sorry, we're all out of Limburger | |
636 | It's very runny, sir. | |
637 | It's really very, VERY runny, sir. | |
638 | ---------------------------------------- | |
639 | client : John Cleese | |
640 | shopkeeper : Michael Palin | |
641 | sketch : Cheese Shop Sketch | |
642 | </pre></div> | |
643 | ||
644 | <P> | |
645 | Note that the <tt class="method">sort()</tt> method of the list of keyword argument | |
646 | names is called before printing the contents of the <code>keywords</code> | |
647 | dictionary; if this is not done, the order in which the arguments are | |
648 | printed is undefined. | |
649 | ||
650 | <P> | |
651 | ||
652 | <H2><A NAME="SECTION006730000000000000000"></A><A NAME="arbitraryArgs"></A> | |
653 | <BR> | |
654 | 4.7.3 Arbitrary Argument Lists | |
655 | </H2> | |
656 | ||
657 | <P> | |
658 | Finally, the least frequently used option is to specify that a | |
659 | function can be called with an arbitrary number of arguments. These | |
660 | arguments will be wrapped up in a tuple. Before the variable number | |
661 | of arguments, zero or more normal arguments may occur. | |
662 | ||
663 | <P> | |
664 | <div class="verbatim"><pre> | |
665 | def fprintf(file, format, *args): | |
666 | file.write(format % args) | |
667 | </pre></div> | |
668 | ||
669 | <P> | |
670 | ||
671 | <H2><A NAME="SECTION006740000000000000000"></A><A NAME="unpacking-arguments"></A> | |
672 | <BR> | |
673 | 4.7.4 Unpacking Argument Lists | |
674 | </H2> | |
675 | ||
676 | <P> | |
677 | The reverse situation occurs when the arguments are already in a list | |
678 | or tuple but need to be unpacked for a function call requiring separate | |
679 | positional arguments. For instance, the built-in <tt class="function">range()</tt> | |
680 | function expects separate <var>start</var> and <var>stop</var> arguments. If they | |
681 | are not available separately, write the function call with the | |
682 | <code>*</code>-operator to unpack the arguments out of a list or tuple: | |
683 | ||
684 | <P> | |
685 | <div class="verbatim"><pre> | |
686 | >>> range(3, 6) # normal call with separate arguments | |
687 | [3, 4, 5] | |
688 | >>> args = [3, 6] | |
689 | >>> range(*args) # call with arguments unpacked from a list | |
690 | [3, 4, 5] | |
691 | </pre></div> | |
692 | ||
693 | <P> | |
694 | ||
695 | <H2><A NAME="SECTION006750000000000000000"></A><A NAME="lambda"></A> | |
696 | <BR> | |
697 | 4.7.5 Lambda Forms | |
698 | </H2> | |
699 | ||
700 | <P> | |
701 | By popular demand, a few features commonly found in functional | |
702 | programming languages like Lisp have been added to Python. With the | |
703 | <tt class="keyword">lambda</tt> keyword, small anonymous functions can be created. | |
704 | Here's a function that returns the sum of its two arguments: | |
705 | "<tt class="samp">lambda a, b: a+b</tt>". Lambda forms can be used wherever function | |
706 | objects are required. They are syntactically restricted to a single | |
707 | expression. Semantically, they are just syntactic sugar for a normal | |
708 | function definition. Like nested function definitions, lambda forms | |
709 | can reference variables from the containing scope: | |
710 | ||
711 | <P> | |
712 | <div class="verbatim"><pre> | |
713 | >>> def make_incrementor(n): | |
714 | ... return lambda x: x + n | |
715 | ... | |
716 | >>> f = make_incrementor(42) | |
717 | >>> f(0) | |
718 | 42 | |
719 | >>> f(1) | |
720 | 43 | |
721 | </pre></div> | |
722 | ||
723 | <P> | |
724 | ||
725 | <H2><A NAME="SECTION006760000000000000000"></A><A NAME="docstrings"></A> | |
726 | <BR> | |
727 | 4.7.6 Documentation Strings | |
728 | </H2> | |
729 | ||
730 | <P> | |
731 | There are emerging conventions about the content and formatting of | |
732 | documentation strings. | |
733 | <a id='l2h-8' xml:id='l2h-8'></a> | |
734 | ||
735 | <P> | |
736 | The first line should always be a short, concise summary of the | |
737 | object's purpose. For brevity, it should not explicitly state the | |
738 | object's name or type, since these are available by other means | |
739 | (except if the name happens to be a verb describing a function's | |
740 | operation). This line should begin with a capital letter and end with | |
741 | a period. | |
742 | ||
743 | <P> | |
744 | If there are more lines in the documentation string, the second line | |
745 | should be blank, visually separating the summary from the rest of the | |
746 | description. The following lines should be one or more paragraphs | |
747 | describing the object's calling conventions, its side effects, etc. | |
748 | ||
749 | <P> | |
750 | The Python parser does not strip indentation from multi-line string | |
751 | literals in Python, so tools that process documentation have to strip | |
752 | indentation if desired. This is done using the following convention. | |
753 | The first non-blank line <em>after</em> the first line of the string | |
754 | determines the amount of indentation for the entire documentation | |
755 | string. (We can't use the first line since it is generally adjacent | |
756 | to the string's opening quotes so its indentation is not apparent in | |
757 | the string literal.) Whitespace ``equivalent'' to this indentation is | |
758 | then stripped from the start of all lines of the string. Lines that | |
759 | are indented less should not occur, but if they occur all their | |
760 | leading whitespace should be stripped. Equivalence of whitespace | |
761 | should be tested after expansion of tabs (to 8 spaces, normally). | |
762 | ||
763 | <P> | |
764 | Here is an example of a multi-line docstring: | |
765 | ||
766 | <P> | |
767 | <div class="verbatim"><pre> | |
768 | >>> def my_function(): | |
769 | ... """Do nothing, but document it. | |
770 | ... | |
771 | ... No, really, it doesn't do anything. | |
772 | ... """ | |
773 | ... pass | |
774 | ... | |
775 | >>> print my_function.__doc__ | |
776 | Do nothing, but document it. | |
777 | ||
778 | No, really, it doesn't do anything. | |
779 | </pre></div> | |
780 | ||
781 | <P> | |
782 | <BR><HR><H4>Footnotes</H4> | |
783 | <DL> | |
784 | <DT><A NAME="foot1775">... object).</A><A | |
785 | HREF="node6.html#tex2html2"><SUP>4.1</SUP></A></DT> | |
786 | <DD> | |
787 | Actually, <em>call by object reference</em> would be a better | |
788 | description, since if a mutable object is passed, the caller | |
789 | will see any changes the callee makes to it (items | |
790 | inserted into a list). | |
791 | ||
792 | ||
793 | </DD> | |
794 | </DL> | |
795 | <DIV CLASS="navigation"> | |
796 | <div class='online-navigation'> | |
797 | <p></p><hr /> | |
798 | <table align="center" width="100%" cellpadding="0" cellspacing="2"> | |
799 | <tr> | |
800 | <td class='online-navigation'><a rel="prev" title="3. An Informal Introduction" | |
801 | href="node5.html"><img src='../icons/previous.png' | |
802 | border='0' height='32' alt='Previous Page' width='32' /></A></td> | |
803 | <td class='online-navigation'><a rel="parent" title="Python Tutorial" | |
804 | href="tut.html"><img src='../icons/up.png' | |
805 | border='0' height='32' alt='Up One Level' width='32' /></A></td> | |
806 | <td class='online-navigation'><a rel="next" title="5. Data Structures" | |
807 | href="node7.html"><img src='../icons/next.png' | |
808 | border='0' height='32' alt='Next Page' width='32' /></A></td> | |
809 | <td align="center" width="100%">Python Tutorial</td> | |
810 | <td class='online-navigation'><a rel="contents" title="Table of Contents" | |
811 | href="node2.html"><img src='../icons/contents.png' | |
812 | border='0' height='32' alt='Contents' width='32' /></A></td> | |
813 | <td class='online-navigation'><img src='../icons/blank.png' | |
814 | border='0' height='32' alt='' width='32' /></td> | |
815 | <td class='online-navigation'><a rel="index" title="Index" | |
816 | href="node19.html"><img src='../icons/index.png' | |
817 | border='0' height='32' alt='Index' width='32' /></A></td> | |
818 | </tr></table> | |
819 | <div class='online-navigation'> | |
820 | <b class="navlabel">Previous:</b> | |
821 | <a class="sectref" rel="prev" href="node5.html">3. An Informal Introduction</A> | |
822 | <b class="navlabel">Up:</b> | |
823 | <a class="sectref" rel="parent" href="tut.html">Python Tutorial</A> | |
824 | <b class="navlabel">Next:</b> | |
825 | <a class="sectref" rel="next" href="node7.html">5. Data Structures</A> | |
826 | </div> | |
827 | </div> | |
828 | <hr /> | |
829 | <span class="release-info">Release 2.4.2, documentation updated on 28 September 2005.</span> | |
830 | </DIV> | |
831 | <!--End of Navigation Panel--> | |
832 | <ADDRESS> | |
833 | See <i><a href="about.html">About this document...</a></i> for information on suggesting changes. | |
834 | </ADDRESS> | |
835 | </BODY> | |
836 | </HTML> |