Initial commit of OpenSPARC T2 architecture model.
[OpenSPARC-T2-SAM] / sam-t2 / devtools / v9 / html / python / tut / node6.html
CommitLineData
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>
814. More Control Flow Tools
82</H1>
83
84<P>
85Besides the <tt class="keyword">while</tt> statement just introduced, Python knows
86the usual control flow statements known from other languages, with
87some twists.
88
89<P>
90
91<H1><A NAME="SECTION006100000000000000000"></A><A NAME="if"></A>
92<BR>
934.1 <tt class="keyword">if</tt> Statements
94</H1>
95
96<P>
97Perhaps 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&gt;&gt;&gt; x = int(raw_input("Please enter an integer: "))
103&gt;&gt;&gt; if x &lt; 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>
116There 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
118short 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
120is 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>
1274.2 <tt class="keyword">for</tt> Statements
128</H1>
129
130<P>
131The <tt class="keyword">for</tt><a id='l2h-4' xml:id='l2h-4'></a> statement in Python differs a bit from
132what you may be used to in C or Pascal. Rather than always
133iterating over an arithmetic progression of numbers (like in Pascal),
134or giving the user the ability to define both the iteration step and
135halting 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
137sequence (a list or a string), in the order that they appear in
138the sequence. For example (no pun intended):
139
140<P>
141<div class="verbatim"><pre>
142&gt;&gt;&gt; # Measure some strings:
143... a = ['cat', 'window', 'defenestrate']
144&gt;&gt;&gt; for x in a:
145... print x, len(x)
146...
147cat 3
148window 6
149defenestrate 12
150</pre></div>
151
152<P>
153It 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
155you need to modify the list you are iterating over (for example, to
156duplicate selected items) you must iterate over a copy. The slice
157notation makes this particularly convenient:
158
159<P>
160<div class="verbatim"><pre>
161&gt;&gt;&gt; for x in a[:]: # make a slice copy of the entire list
162... if len(x) &gt; 6: a.insert(0, x)
163...
164&gt;&gt;&gt; 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>
1724.3 The <tt class="function">range()</tt> Function
173</H1>
174
175<P>
176If you do need to iterate over a sequence of numbers, the built-in
177function <tt class="function">range()</tt> comes in handy. It generates lists
178containing arithmetic progressions:
179
180<P>
181<div class="verbatim"><pre>
182&gt;&gt;&gt; range(10)
183[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
184</pre></div>
185
186<P>
187The given end point is never part of the generated list;
188<code>range(10)</code> generates a list of 10 values, the legal
189indices for items of a sequence of length 10. It is possible to let
190the 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&gt;&gt;&gt; range(5, 10)
196[5, 6, 7, 8, 9]
197&gt;&gt;&gt; range(0, 10, 3)
198[0, 3, 6, 9]
199&gt;&gt;&gt; range(-10, -100, -30)
200[-10, -40, -70]
201</pre></div>
202
203<P>
204To 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&gt;&gt;&gt; a = ['Mary', 'had', 'a', 'little', 'lamb']
210&gt;&gt;&gt; for i in range(len(a)):
211... print i, a[i]
212...
2130 Mary
2141 had
2152 a
2163 little
2174 lamb
218</pre></div>
219
220<P>
221
222<H1><A NAME="SECTION006400000000000000000"></A><A NAME="break"></A>
223<BR>
2244.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>
230The <tt class="keyword">break</tt> statement, like in C, breaks out of the smallest
231enclosing <tt class="keyword">for</tt> or <tt class="keyword">while</tt> loop.
232
233<P>
234The <tt class="keyword">continue</tt> statement, also borrowed from C, continues
235with the next iteration of the loop.
236
237<P>
238Loop statements may have an <code>else</code> clause; it is executed when
239the 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,
243which searches for prime numbers:
244
245<P>
246<div class="verbatim"><pre>
247&gt;&gt;&gt; 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...
2562 is a prime number
2573 is a prime number
2584 equals 2 * 2
2595 is a prime number
2606 equals 2 * 3
2617 is a prime number
2628 equals 2 * 4
2639 equals 3 * 3
264</pre></div>
265
266<P>
267
268<H1><A NAME="SECTION006500000000000000000"></A><A NAME="pass"></A>
269<BR>
2704.5 <tt class="keyword">pass</tt> Statements
271</H1>
272
273<P>
274The <tt class="keyword">pass</tt> statement does nothing.
275It can be used when a statement is required syntactically but the
276program requires no action.
277For example:
278
279<P>
280<div class="verbatim"><pre>
281&gt;&gt;&gt; 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>
2904.6 Defining Functions
291</H1>
292
293<P>
294We can create a function that writes the Fibonacci series to an
295arbitrary boundary:
296
297<P>
298<div class="verbatim"><pre>
299&gt;&gt;&gt; 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 &lt; n:
303... print b,
304... a, b = b, a+b
305...
306&gt;&gt;&gt; # Now call the function we just defined:
307... fib(2000)
3081 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
309</pre></div>
310
311<P>
312The keyword <tt class="keyword">def</tt> introduces a function <em>definition</em>. It
313must be followed by the function name and the parenthesized list of
314formal parameters. The statements that form the body of the function
315start at the next line, and must be indented. The first statement of
316the function body can optionally be a string literal; this string
317literal is the function's <a id='l2h-6' xml:id='l2h-6'></a>documentation
318string, or <i class="dfn">docstring</i>.<a id='l2h-7' xml:id='l2h-7'></a>
319
320<P>
321There are tools which use docstrings to automatically produce online
322or printed documentation, or to let the user interactively browse
323through code; it's good practice to include docstrings in code that
324you write, so try to make a habit of it.
325
326<P>
327The <em>execution</em> of a function introduces a new symbol table used
328for the local variables of the function. More precisely, all variable
329assignments in a function store the value in the local symbol table;
330whereas variable references first look in the local symbol table, then
331in the global symbol table, and then in the table of built-in names.
332Thus, global variables cannot be directly assigned a value within a
333function (unless named in a <tt class="keyword">global</tt> statement), although
334they may be referenced.
335
336<P>
337The actual parameters (arguments) to a function call are introduced in
338the local symbol table of the called function when it is called; thus,
339arguments 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
341the object).<A NAME="tex2html2"
342 HREF="#foot1775"><SUP>4.1</SUP></A> When a function calls another function, a new local symbol table is
343created for that call.
344
345<P>
346A function definition introduces the function name in the current
347symbol table. The value of the function name
348has a type that is recognized by the interpreter as a user-defined
349function. This value can be assigned to another name which can then
350also be used as a function. This serves as a general renaming
351mechanism:
352
353<P>
354<div class="verbatim"><pre>
355&gt;&gt;&gt; fib
356&lt;function fib at 10042ed0&gt;
357&gt;&gt;&gt; f = fib
358&gt;&gt;&gt; f(100)
3591 1 2 3 5 8 13 21 34 55 89
360</pre></div>
361
362<P>
363You might object that <code>fib</code> is not a function but a procedure. In
364Python, like in C, procedures are just functions that don't return a
365value. In fact, technically speaking, procedures do return a value,
366albeit a rather boring one. This value is called <code>None</code> (it's a
367built-in name). Writing the value <code>None</code> is normally suppressed by
368the interpreter if it would be the only value written. You can see it
369if you really want to:
370
371<P>
372<div class="verbatim"><pre>
373&gt;&gt;&gt; print fib(0)
374None
375</pre></div>
376
377<P>
378It is simple to write a function that returns a list of the numbers of
379the Fibonacci series, instead of printing it:
380
381<P>
382<div class="verbatim"><pre>
383&gt;&gt;&gt; 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 &lt; n:
388... result.append(b) # see below
389... a, b = b, a+b
390... return result
391...
392&gt;&gt;&gt; f100 = fib2(100) # call it
393&gt;&gt;&gt; f100 # write the result
394[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
395</pre></div>
396
397<P>
398This 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>.
405Falling 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
410object <code>result</code>. A method is a function that `belongs' to an
411object and is named <code>obj.methodname</code>, where <code>obj</code> is some
412object (this may be an expression), and <code>methodname</code> is the name
413of a method that is defined by the object's type. Different types
414define different methods. Methods of different types may have the
415same name without causing ambiguity. (It is possible to define your
416own object types and methods, using <em>classes</em>, as discussed later
417in this tutorial.)
418The method <tt class="method">append()</tt> shown in the example is defined for
419list objects; it adds a new element at the end of the list. In this
420example it is equivalent to "<tt class="samp">result = result + [b]</tt>", but more
421efficient.
422
423<P>
424</LI>
425</UL>
426
427<P>
428
429<H1><A NAME="SECTION006700000000000000000"></A><A NAME="defining"></A>
430<BR>
4314.7 More on Defining Functions
432</H1>
433
434<P>
435It is also possible to define functions with a variable number of
436arguments. There are three forms, which can be combined.
437
438<P>
439
440<H2><A NAME="SECTION006710000000000000000"></A><A NAME="defaultArgs"></A>
441<BR>
4424.7.1 Default Argument Values
443</H2>
444
445<P>
446The most useful form is to specify a default value for one or more
447arguments. This creates a function that can be called with fewer
448arguments than it is defined to allow. For example:
449
450<P>
451<div class="verbatim"><pre>
452def 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 &lt; 0: raise IOError, 'refusenik user'
459 print complaint
460</pre></div>
461
462<P>
463This 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>
468This example also introduces the <tt class="keyword">in</tt> keyword. This tests
469whether or not a sequence contains a certain value.
470
471<P>
472The default values are evaluated at the point of function definition
473in the <em>defining</em> scope, so that
474
475<P>
476<div class="verbatim"><pre>
477i = 5
478
479def f(arg=i):
480 print arg
481
482i = 6
483f()
484</pre></div>
485
486<P>
487will print <code>5</code>.
488
489<P>
490<strong>Important warning:</strong> The default value is evaluated only once.
491This makes a difference when the default is a mutable object such as a
492list, dictionary, or instances of most classes. For example, the
493following function accumulates the arguments passed to it on
494subsequent calls:
495
496<P>
497<div class="verbatim"><pre>
498def f(a, L=[]):
499 L.append(a)
500 return L
501
502print f(1)
503print f(2)
504print f(3)
505</pre></div>
506
507<P>
508This 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>
518If you don't want the default to be shared between subsequent calls,
519you can write the function like this instead:
520
521<P>
522<div class="verbatim"><pre>
523def 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>
5344.7.2 Keyword Arguments
535</H2>
536
537<P>
538Functions can also be called using
539keyword arguments of the form "<tt class="samp"><var>keyword</var> = <var>value</var></tt>". For
540instance, the following function:
541
542<P>
543<div class="verbatim"><pre>
544def 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>
552could be called in any of the following ways:
553
554<P>
555<div class="verbatim"><pre>
556parrot(1000)
557parrot(action = 'VOOOOOM', voltage = 1000000)
558parrot('a thousand', state = 'pushing up the daisies')
559parrot('a million', 'bereft of life', 'jump')
560</pre></div>
561
562<P>
563but the following calls would all be invalid:
564
565<P>
566<div class="verbatim"><pre>
567parrot() # required argument missing
568parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
569parrot(110, voltage=220) # duplicate value for argument
570parrot(actor='John Cleese') # unknown keyword
571</pre></div>
572
573<P>
574In general, an argument list must have any positional arguments
575followed by any keyword arguments, where the keywords must be chosen
576from the formal parameter names. It's not important whether a formal
577parameter has a default value or not. No argument may receive a
578value more than once -- formal parameter names corresponding to
579positional arguments cannot be used as keywords in the same calls.
580Here's an example that fails due to this restriction:
581
582<P>
583<div class="verbatim"><pre>
584&gt;&gt;&gt; def function(a):
585... pass
586...
587&gt;&gt;&gt; function(0, a=0)
588Traceback (most recent call last):
589 File "&lt;stdin&gt;", line 1, in ?
590TypeError: function() got multiple values for keyword argument 'a'
591</pre></div>
592
593<P>
594When a final formal parameter of the form <code>**<var>name</var></code> is
595present, it receives a <a class="ulink" href="../lib/typesmapping.html"
596 >dictionary</a>
597containing all keyword arguments except for those corresponding to
598a formal parameter. This may be
599combined with a formal parameter of the form
600<code>*<var>name</var></code> (described in the next subsection) which receives a
601tuple containing the positional arguments beyond the formal parameter
602list. (<code>*<var>name</var></code> must occur before <code>**<var>name</var></code>.)
603For example, if we define a function like this:
604
605<P>
606<div class="verbatim"><pre>
607def 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>
618It could be called like this:
619
620<P>
621<div class="verbatim"><pre>
622cheeseshop('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>
630and 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
636It's very runny, sir.
637It's really very, VERY runny, sir.
638----------------------------------------
639client : John Cleese
640shopkeeper : Michael Palin
641sketch : Cheese Shop Sketch
642</pre></div>
643
644<P>
645Note that the <tt class="method">sort()</tt> method of the list of keyword argument
646names is called before printing the contents of the <code>keywords</code>
647dictionary; if this is not done, the order in which the arguments are
648printed is undefined.
649
650<P>
651
652<H2><A NAME="SECTION006730000000000000000"></A><A NAME="arbitraryArgs"></A>
653<BR>
6544.7.3 Arbitrary Argument Lists
655</H2>
656
657<P>
658Finally, the least frequently used option is to specify that a
659function can be called with an arbitrary number of arguments. These
660arguments will be wrapped up in a tuple. Before the variable number
661of arguments, zero or more normal arguments may occur.
662
663<P>
664<div class="verbatim"><pre>
665def 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>
6734.7.4 Unpacking Argument Lists
674</H2>
675
676<P>
677The reverse situation occurs when the arguments are already in a list
678or tuple but need to be unpacked for a function call requiring separate
679positional arguments. For instance, the built-in <tt class="function">range()</tt>
680function expects separate <var>start</var> and <var>stop</var> arguments. If they
681are 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&gt;&gt;&gt; range(3, 6) # normal call with separate arguments
687[3, 4, 5]
688&gt;&gt;&gt; args = [3, 6]
689&gt;&gt;&gt; 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>
6974.7.5 Lambda Forms
698</H2>
699
700<P>
701By popular demand, a few features commonly found in functional
702programming languages like Lisp have been added to Python. With the
703<tt class="keyword">lambda</tt> keyword, small anonymous functions can be created.
704Here'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
706objects are required. They are syntactically restricted to a single
707expression. Semantically, they are just syntactic sugar for a normal
708function definition. Like nested function definitions, lambda forms
709can reference variables from the containing scope:
710
711<P>
712<div class="verbatim"><pre>
713&gt;&gt;&gt; def make_incrementor(n):
714... return lambda x: x + n
715...
716&gt;&gt;&gt; f = make_incrementor(42)
717&gt;&gt;&gt; f(0)
71842
719&gt;&gt;&gt; f(1)
72043
721</pre></div>
722
723<P>
724
725<H2><A NAME="SECTION006760000000000000000"></A><A NAME="docstrings"></A>
726<BR>
7274.7.6 Documentation Strings
728</H2>
729
730<P>
731There are emerging conventions about the content and formatting of
732documentation strings.
733<a id='l2h-8' xml:id='l2h-8'></a>
734
735<P>
736The first line should always be a short, concise summary of the
737object's purpose. For brevity, it should not explicitly state the
738object'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
740operation). This line should begin with a capital letter and end with
741a period.
742
743<P>
744If there are more lines in the documentation string, the second line
745should be blank, visually separating the summary from the rest of the
746description. The following lines should be one or more paragraphs
747describing the object's calling conventions, its side effects, etc.
748
749<P>
750The Python parser does not strip indentation from multi-line string
751literals in Python, so tools that process documentation have to strip
752indentation if desired. This is done using the following convention.
753The first non-blank line <em>after</em> the first line of the string
754determines the amount of indentation for the entire documentation
755string. (We can't use the first line since it is generally adjacent
756to the string's opening quotes so its indentation is not apparent in
757the string literal.) Whitespace ``equivalent'' to this indentation is
758then stripped from the start of all lines of the string. Lines that
759are indented less should not occur, but if they occur all their
760leading whitespace should be stripped. Equivalence of whitespace
761should be tested after expansion of tabs (to 8 spaces, normally).
762
763<P>
764Here is an example of a multi-line docstring:
765
766<P>
767<div class="verbatim"><pre>
768&gt;&gt;&gt; def my_function():
769... """Do nothing, but document it.
770...
771... No, really, it doesn't do anything.
772... """
773... pass
774...
775&gt;&gt;&gt; print my_function.__doc__
776Do 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>
833See <i><a href="about.html">About this document...</a></i> for information on suggesting changes.
834</ADDRESS>
835</BODY>
836</HTML>