blob: f6f41b33b7aabf290cf1ec95f3e785eb8d20a04d [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. _tut-morecontrol:
2
3***********************
4More Control Flow Tools
5***********************
6
7Besides the :keyword:`while` statement just introduced, Python knows the usual
8control flow statements known from other languages, with some twists.
9
10
11.. _tut-if:
12
13:keyword:`if` Statements
14========================
15
16Perhaps the most well-known statement type is the :keyword:`if` statement. For
17example::
18
19 >>> def raw_input(prompt):
20 ... import sys
21 ... sys.stdout.write(prompt)
22 ... sys.stdout.flush()
23 ... return sys.stdin.readline()
24 ...
25 >>> x = int(raw_input("Please enter an integer: "))
26 >>> if x < 0:
27 ... x = 0
28 ... print 'Negative changed to zero'
29 ... elif x == 0:
30 ... print 'Zero'
31 ... elif x == 1:
32 ... print 'Single'
33 ... else:
34 ... print 'More'
35 ...
36
37There can be zero or more :keyword:`elif` parts, and the :keyword:`else` part is
38optional. The keyword ':keyword:`elif`' is short for 'else if', and is useful
39to avoid excessive indentation. An :keyword:`if` ... :keyword:`elif` ...
40:keyword:`elif` ... sequence is a substitute for the :keyword:`switch` or
41:keyword:`case` statements found in other languages.
42
43.. % Weird spacings happen here if the wrapping of the source text
44.. % gets changed in the wrong way.
45
46
47.. _tut-for:
48
49:keyword:`for` Statements
50=========================
51
52.. index::
53 statement: for
54 statement: for
55
56The :keyword:`for` statement in Python differs a bit from what you may be used
57to in C or Pascal. Rather than always iterating over an arithmetic progression
58of numbers (like in Pascal), or giving the user the ability to define both the
59iteration step and halting condition (as C), Python's :keyword:`for` statement
60iterates over the items of any sequence (a list or a string), in the order that
61they appear in the sequence. For example (no pun intended):
62
63.. % One suggestion was to give a real C example here, but that may only
64.. % serve to confuse non-C programmers.
65
66::
67
68 >>> # Measure some strings:
69 ... a = ['cat', 'window', 'defenestrate']
70 >>> for x in a:
71 ... print x, len(x)
72 ...
73 cat 3
74 window 6
75 defenestrate 12
76
77It is not safe to modify the sequence being iterated over in the loop (this can
78only happen for mutable sequence types, such as lists). If you need to modify
79the list you are iterating over (for example, to duplicate selected items) you
80must iterate over a copy. The slice notation makes this particularly
81convenient::
82
83 >>> for x in a[:]: # make a slice copy of the entire list
84 ... if len(x) > 6: a.insert(0, x)
85 ...
86 >>> a
87 ['defenestrate', 'cat', 'window', 'defenestrate']
88
89
90.. _tut-range:
91
92The :func:`range` Function
93==========================
94
95If you do need to iterate over a sequence of numbers, the built-in function
96:func:`range` comes in handy. It generates lists containing arithmetic
97progressions::
98
99 >>> range(10)
100 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
101
102The given end point is never part of the generated list; ``range(10)`` generates
103a list of 10 values, the legal indices for items of a sequence of length 10. It
104is possible to let the range start at another number, or to specify a different
105increment (even negative; sometimes this is called the 'step')::
106
107 >>> range(5, 10)
108 [5, 6, 7, 8, 9]
109 >>> range(0, 10, 3)
110 [0, 3, 6, 9]
111 >>> range(-10, -100, -30)
112 [-10, -40, -70]
113
114To iterate over the indices of a sequence, combine :func:`range` and :func:`len`
115as follows::
116
117 >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
118 >>> for i in range(len(a)):
119 ... print i, a[i]
120 ...
121 0 Mary
122 1 had
123 2 a
124 3 little
125 4 lamb
126
127
128.. _tut-break:
129
130:keyword:`break` and :keyword:`continue` Statements, and :keyword:`else` Clauses on Loops
131=========================================================================================
132
133The :keyword:`break` statement, like in C, breaks out of the smallest enclosing
134:keyword:`for` or :keyword:`while` loop.
135
136The :keyword:`continue` statement, also borrowed from C, continues with the next
137iteration of the loop.
138
139Loop statements may have an ``else`` clause; it is executed when the loop
140terminates through exhaustion of the list (with :keyword:`for`) or when the
141condition becomes false (with :keyword:`while`), but not when the loop is
142terminated by a :keyword:`break` statement. This is exemplified by the
143following loop, which searches for prime numbers::
144
145 >>> for n in range(2, 10):
146 ... for x in range(2, n):
147 ... if n % x == 0:
148 ... print n, 'equals', x, '*', n/x
149 ... break
150 ... else:
151 ... # loop fell through without finding a factor
152 ... print n, 'is a prime number'
153 ...
154 2 is a prime number
155 3 is a prime number
156 4 equals 2 * 2
157 5 is a prime number
158 6 equals 2 * 3
159 7 is a prime number
160 8 equals 2 * 4
161 9 equals 3 * 3
162
163
164.. _tut-pass:
165
166:keyword:`pass` Statements
167==========================
168
169The :keyword:`pass` statement does nothing. It can be used when a statement is
170required syntactically but the program requires no action. For example::
171
172 >>> while True:
173 ... pass # Busy-wait for keyboard interrupt
174 ...
175
176
177.. _tut-functions:
178
179Defining Functions
180==================
181
182We can create a function that writes the Fibonacci series to an arbitrary
183boundary::
184
185 >>> def fib(n): # write Fibonacci series up to n
186 ... """Print a Fibonacci series up to n."""
187 ... a, b = 0, 1
188 ... while b < n:
189 ... print b,
190 ... a, b = b, a+b
191 ...
192 >>> # Now call the function we just defined:
193 ... fib(2000)
194 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
195
196.. index::
197 single: documentation strings
198 single: docstrings
199 single: strings, documentation
200
201The keyword :keyword:`def` introduces a function *definition*. It must be
202followed by the function name and the parenthesized list of formal parameters.
203The statements that form the body of the function start at the next line, and
204must be indented. The first statement of the function body can optionally be a
205string literal; this string literal is the function's documentation string, or
206:dfn:`docstring`.
207
208There are tools which use docstrings to automatically produce online or printed
209documentation, or to let the user interactively browse through code; it's good
210practice to include docstrings in code that you write, so try to make a habit of
211it.
212
213The *execution* of a function introduces a new symbol table used for the local
214variables of the function. More precisely, all variable assignments in a
215function store the value in the local symbol table; whereas variable references
216first look in the local symbol table, then in the global symbol table, and then
217in the table of built-in names. Thus, global variables cannot be directly
218assigned a value within a function (unless named in a :keyword:`global`
219statement), although they may be referenced.
220
221The actual parameters (arguments) to a function call are introduced in the local
222symbol table of the called function when it is called; thus, arguments are
223passed using *call by value* (where the *value* is always an object *reference*,
224not the value of the object). [#]_ When a function calls another function, a new
225local symbol table is created for that call.
226
227A function definition introduces the function name in the current symbol table.
228The value of the function name has a type that is recognized by the interpreter
229as a user-defined function. This value can be assigned to another name which
230can then also be used as a function. This serves as a general renaming
231mechanism::
232
233 >>> fib
234 <function fib at 10042ed0>
235 >>> f = fib
236 >>> f(100)
237 1 1 2 3 5 8 13 21 34 55 89
238
239You might object that ``fib`` is not a function but a procedure. In Python,
240like in C, procedures are just functions that don't return a value. In fact,
241technically speaking, procedures do return a value, albeit a rather boring one.
242This value is called ``None`` (it's a built-in name). Writing the value
243``None`` is normally suppressed by the interpreter if it would be the only value
244written. You can see it if you really want to::
245
246 >>> print fib(0)
247 None
248
249It is simple to write a function that returns a list of the numbers of the
250Fibonacci series, instead of printing it::
251
252 >>> def fib2(n): # return Fibonacci series up to n
253 ... """Return a list containing the Fibonacci series up to n."""
254 ... result = []
255 ... a, b = 0, 1
256 ... while b < n:
257 ... result.append(b) # see below
258 ... a, b = b, a+b
259 ... return result
260 ...
261 >>> f100 = fib2(100) # call it
262 >>> f100 # write the result
263 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
264
265This example, as usual, demonstrates some new Python features:
266
267* The :keyword:`return` statement returns with a value from a function.
268 :keyword:`return` without an expression argument returns ``None``. Falling off
269 the end of a procedure also returns ``None``.
270
271* The statement ``result.append(b)`` calls a *method* of the list object
272 ``result``. A method is a function that 'belongs' to an object and is named
273 ``obj.methodname``, where ``obj`` is some object (this may be an expression),
274 and ``methodname`` is the name of a method that is defined by the object's type.
275 Different types define different methods. Methods of different types may have
276 the same name without causing ambiguity. (It is possible to define your own
277 object types and methods, using *classes*, as discussed later in this tutorial.)
278 The method :meth:`append` shown in the example is defined for list objects; it
279 adds a new element at the end of the list. In this example it is equivalent to
280 ``result = result + [b]``, but more efficient.
281
282
283.. _tut-defining:
284
285More on Defining Functions
286==========================
287
288It is also possible to define functions with a variable number of arguments.
289There are three forms, which can be combined.
290
291
292.. _tut-defaultargs:
293
294Default Argument Values
295-----------------------
296
297The most useful form is to specify a default value for one or more arguments.
298This creates a function that can be called with fewer arguments than it is
299defined to allow. For example::
300
301 def raw_input(prompt):
302 import sys
303 sys.stdout.write(prompt)
304 sys.stdout.flush()
305 return sys.stdin.readline()
306
307 def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
308 while True:
309 ok = raw_input(prompt)
310 if ok in ('y', 'ye', 'yes'): return True
311 if ok in ('n', 'no', 'nop', 'nope'): return False
312 retries = retries - 1
313 if retries < 0: raise IOError, 'refusenik user'
314 print complaint
315
316This function can be called either like this: ``ask_ok('Do you really want to
317quit?')`` or like this: ``ask_ok('OK to overwrite the file?', 2)``.
318
319This example also introduces the :keyword:`in` keyword. This tests whether or
320not a sequence contains a certain value.
321
322The default values are evaluated at the point of function definition in the
323*defining* scope, so that ::
324
325 i = 5
326
327 def f(arg=i):
328 print arg
329
330 i = 6
331 f()
332
333will print ``5``.
334
335**Important warning:** The default value is evaluated only once. This makes a
336difference when the default is a mutable object such as a list, dictionary, or
337instances of most classes. For example, the following function accumulates the
338arguments passed to it on subsequent calls::
339
340 def f(a, L=[]):
341 L.append(a)
342 return L
343
344 print f(1)
345 print f(2)
346 print f(3)
347
348This will print ::
349
350 [1]
351 [1, 2]
352 [1, 2, 3]
353
354If you don't want the default to be shared between subsequent calls, you can
355write the function like this instead::
356
357 def f(a, L=None):
358 if L is None:
359 L = []
360 L.append(a)
361 return L
362
363
364.. _tut-keywordargs:
365
366Keyword Arguments
367-----------------
368
369Functions can also be called using keyword arguments of the form ``keyword =
370value``. For instance, the following function::
371
372 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
373 print "-- This parrot wouldn't", action,
374 print "if you put", voltage, "volts through it."
375 print "-- Lovely plumage, the", type
376 print "-- It's", state, "!"
377
378could be called in any of the following ways::
379
380 parrot(1000)
381 parrot(action = 'VOOOOOM', voltage = 1000000)
382 parrot('a thousand', state = 'pushing up the daisies')
383 parrot('a million', 'bereft of life', 'jump')
384
385but the following calls would all be invalid::
386
387 parrot() # required argument missing
388 parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
389 parrot(110, voltage=220) # duplicate value for argument
390 parrot(actor='John Cleese') # unknown keyword
391
392In general, an argument list must have any positional arguments followed by any
393keyword arguments, where the keywords must be chosen from the formal parameter
394names. It's not important whether a formal parameter has a default value or
395not. No argument may receive a value more than once --- formal parameter names
396corresponding to positional arguments cannot be used as keywords in the same
397calls. Here's an example that fails due to this restriction::
398
399 >>> def function(a):
400 ... pass
401 ...
402 >>> function(0, a=0)
403 Traceback (most recent call last):
404 File "<stdin>", line 1, in ?
405 TypeError: function() got multiple values for keyword argument 'a'
406
407When a final formal parameter of the form ``**name`` is present, it receives a
408dictionary (see :ref:`typesmapping`) containing all keyword arguments except for
409those corresponding to a formal parameter. This may be combined with a formal
410parameter of the form ``*name`` (described in the next subsection) which
411receives a tuple containing the positional arguments beyond the formal parameter
412list. (``*name`` must occur before ``**name``.) For example, if we define a
413function like this::
414
415 def cheeseshop(kind, *arguments, **keywords):
416 print "-- Do you have any", kind, '?'
417 print "-- I'm sorry, we're all out of", kind
418 for arg in arguments: print arg
419 print '-'*40
420 keys = keywords.keys()
421 keys.sort()
422 for kw in keys: print kw, ':', keywords[kw]
423
424It could be called like this::
425
426 cheeseshop('Limburger', "It's very runny, sir.",
427 "It's really very, VERY runny, sir.",
428 client='John Cleese',
429 shopkeeper='Michael Palin',
430 sketch='Cheese Shop Sketch')
431
432and of course it would print::
433
434 -- Do you have any Limburger ?
435 -- I'm sorry, we're all out of Limburger
436 It's very runny, sir.
437 It's really very, VERY runny, sir.
438 ----------------------------------------
439 client : John Cleese
440 shopkeeper : Michael Palin
441 sketch : Cheese Shop Sketch
442
443Note that the :meth:`sort` method of the list of keyword argument names is
444called before printing the contents of the ``keywords`` dictionary; if this is
445not done, the order in which the arguments are printed is undefined.
446
447
448.. _tut-arbitraryargs:
449
450Arbitrary Argument Lists
451------------------------
452
453Finally, the least frequently used option is to specify that a function can be
454called with an arbitrary number of arguments. These arguments will be wrapped
455up in a tuple. Before the variable number of arguments, zero or more normal
456arguments may occur. ::
457
458 def fprintf(file, format, *args):
459 file.write(format % args)
460
461
462.. _tut-unpacking-arguments:
463
464Unpacking Argument Lists
465------------------------
466
467The reverse situation occurs when the arguments are already in a list or tuple
468but need to be unpacked for a function call requiring separate positional
469arguments. For instance, the built-in :func:`range` function expects separate
470*start* and *stop* arguments. If they are not available separately, write the
471function call with the ``*``\ -operator to unpack the arguments out of a list
472or tuple::
473
474 >>> range(3, 6) # normal call with separate arguments
475 [3, 4, 5]
476 >>> args = [3, 6]
477 >>> range(*args) # call with arguments unpacked from a list
478 [3, 4, 5]
479
480In the same fashion, dictionaries can deliver keyword arguments with the ``**``\
481-operator::
482
483 >>> def parrot(voltage, state='a stiff', action='voom'):
484 ... print "-- This parrot wouldn't", action,
485 ... print "if you put", voltage, "volts through it.",
486 ... print "E's", state, "!"
487 ...
488 >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
489 >>> parrot(**d)
490 -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
491
492
493.. _tut-lambda:
494
495Lambda Forms
496------------
497
498By popular demand, a few features commonly found in functional programming
499languages like Lisp have been added to Python. With the :keyword:`lambda`
500keyword, small anonymous functions can be created. Here's a function that
501returns the sum of its two arguments: ``lambda a, b: a+b``. Lambda forms can be
502used wherever function objects are required. They are syntactically restricted
503to a single expression. Semantically, they are just syntactic sugar for a
504normal function definition. Like nested function definitions, lambda forms can
505reference variables from the containing scope::
506
507 >>> def make_incrementor(n):
508 ... return lambda x: x + n
509 ...
510 >>> f = make_incrementor(42)
511 >>> f(0)
512 42
513 >>> f(1)
514 43
515
516
517.. _tut-docstrings:
518
519Documentation Strings
520---------------------
521
522.. index::
523 single: docstrings
524 single: documentation strings
525 single: strings, documentation
526
527There are emerging conventions about the content and formatting of documentation
528strings.
529
530The first line should always be a short, concise summary of the object's
531purpose. For brevity, it should not explicitly state the object's name or type,
532since these are available by other means (except if the name happens to be a
533verb describing a function's operation). This line should begin with a capital
534letter and end with a period.
535
536If there are more lines in the documentation string, the second line should be
537blank, visually separating the summary from the rest of the description. The
538following lines should be one or more paragraphs describing the object's calling
539conventions, its side effects, etc.
540
541The Python parser does not strip indentation from multi-line string literals in
542Python, so tools that process documentation have to strip indentation if
543desired. This is done using the following convention. The first non-blank line
544*after* the first line of the string determines the amount of indentation for
545the entire documentation string. (We can't use the first line since it is
546generally adjacent to the string's opening quotes so its indentation is not
547apparent in the string literal.) Whitespace "equivalent" to this indentation is
548then stripped from the start of all lines of the string. Lines that are
549indented less should not occur, but if they occur all their leading whitespace
550should be stripped. Equivalence of whitespace should be tested after expansion
551of tabs (to 8 spaces, normally).
552
553Here is an example of a multi-line docstring::
554
555 >>> def my_function():
556 ... """Do nothing, but document it.
557 ...
558 ... No, really, it doesn't do anything.
559 ... """
560 ... pass
561 ...
562 >>> print my_function.__doc__
563 Do nothing, but document it.
564
565 No, really, it doesn't do anything.
566
567
568
569.. rubric:: Footnotes
570
571.. [#] Actually, *call by object reference* would be a better description, since if a
572 mutable object is passed, the caller will see any changes the callee makes to it
573 (items inserted into a list).
574