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