blob: 420c8d9a44d1b5317f9e2cf06a4df47c271e8650 [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
Georg Brandlaa0de3f2008-01-21 16:51:51 +0000207first look in the local symbol table, then in the local symbol tables of
208enclosing functions, then in the global symbol table, and finally in the table
209of built-in names. Thus, global variables cannot be directly assigned a value
210within a function (unless named in a :keyword:`global` statement), although they
211may be referenced.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000212
213The actual parameters (arguments) to a function call are introduced in the local
214symbol table of the called function when it is called; thus, arguments are
215passed using *call by value* (where the *value* is always an object *reference*,
216not the value of the object). [#]_ When a function calls another function, a new
217local symbol table is created for that call.
218
219A function definition introduces the function name in the current symbol table.
220The value of the function name has a type that is recognized by the interpreter
221as a user-defined function. This value can be assigned to another name which
222can then also be used as a function. This serves as a general renaming
223mechanism::
224
225 >>> fib
226 <function fib at 10042ed0>
227 >>> f = fib
228 >>> f(100)
229 1 1 2 3 5 8 13 21 34 55 89
230
231You might object that ``fib`` is not a function but a procedure. In Python,
232like in C, procedures are just functions that don't return a value. In fact,
233technically speaking, procedures do return a value, albeit a rather boring one.
234This value is called ``None`` (it's a built-in name). Writing the value
235``None`` is normally suppressed by the interpreter if it would be the only value
Georg Brandl706132b2007-10-30 17:57:12 +0000236written. You can see it if you really want to using :keyword:`print`::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000237
Georg Brandl706132b2007-10-30 17:57:12 +0000238 >>> fib(0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000239 >>> print fib(0)
240 None
241
242It is simple to write a function that returns a list of the numbers of the
243Fibonacci series, instead of printing it::
244
245 >>> def fib2(n): # return Fibonacci series up to n
246 ... """Return a list containing the Fibonacci series up to n."""
247 ... result = []
248 ... a, b = 0, 1
249 ... while b < n:
250 ... result.append(b) # see below
251 ... a, b = b, a+b
252 ... return result
253 ...
254 >>> f100 = fib2(100) # call it
255 >>> f100 # write the result
256 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
257
258This example, as usual, demonstrates some new Python features:
259
260* The :keyword:`return` statement returns with a value from a function.
261 :keyword:`return` without an expression argument returns ``None``. Falling off
262 the end of a procedure also returns ``None``.
263
264* The statement ``result.append(b)`` calls a *method* of the list object
265 ``result``. A method is a function that 'belongs' to an object and is named
266 ``obj.methodname``, where ``obj`` is some object (this may be an expression),
267 and ``methodname`` is the name of a method that is defined by the object's type.
268 Different types define different methods. Methods of different types may have
269 the same name without causing ambiguity. (It is possible to define your own
270 object types and methods, using *classes*, as discussed later in this tutorial.)
271 The method :meth:`append` shown in the example is defined for list objects; it
272 adds a new element at the end of the list. In this example it is equivalent to
273 ``result = result + [b]``, but more efficient.
274
275
276.. _tut-defining:
277
278More on Defining Functions
279==========================
280
281It is also possible to define functions with a variable number of arguments.
282There are three forms, which can be combined.
283
284
285.. _tut-defaultargs:
286
287Default Argument Values
288-----------------------
289
290The most useful form is to specify a default value for one or more arguments.
291This creates a function that can be called with fewer arguments than it is
292defined to allow. For example::
293
294 def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
295 while True:
296 ok = raw_input(prompt)
297 if ok in ('y', 'ye', 'yes'): return True
298 if ok in ('n', 'no', 'nop', 'nope'): return False
299 retries = retries - 1
300 if retries < 0: raise IOError, 'refusenik user'
301 print complaint
302
303This function can be called either like this: ``ask_ok('Do you really want to
304quit?')`` or like this: ``ask_ok('OK to overwrite the file?', 2)``.
305
306This example also introduces the :keyword:`in` keyword. This tests whether or
307not a sequence contains a certain value.
308
309The default values are evaluated at the point of function definition in the
310*defining* scope, so that ::
311
312 i = 5
313
314 def f(arg=i):
315 print arg
316
317 i = 6
318 f()
319
320will print ``5``.
321
322**Important warning:** The default value is evaluated only once. This makes a
323difference when the default is a mutable object such as a list, dictionary, or
324instances of most classes. For example, the following function accumulates the
325arguments passed to it on subsequent calls::
326
327 def f(a, L=[]):
328 L.append(a)
329 return L
330
331 print f(1)
332 print f(2)
333 print f(3)
334
335This will print ::
336
337 [1]
338 [1, 2]
339 [1, 2, 3]
340
341If you don't want the default to be shared between subsequent calls, you can
342write the function like this instead::
343
344 def f(a, L=None):
345 if L is None:
346 L = []
347 L.append(a)
348 return L
349
350
351.. _tut-keywordargs:
352
353Keyword Arguments
354-----------------
355
356Functions can also be called using keyword arguments of the form ``keyword =
357value``. For instance, the following function::
358
359 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
360 print "-- This parrot wouldn't", action,
361 print "if you put", voltage, "volts through it."
362 print "-- Lovely plumage, the", type
363 print "-- It's", state, "!"
364
365could be called in any of the following ways::
366
367 parrot(1000)
368 parrot(action = 'VOOOOOM', voltage = 1000000)
369 parrot('a thousand', state = 'pushing up the daisies')
370 parrot('a million', 'bereft of life', 'jump')
371
372but the following calls would all be invalid::
373
374 parrot() # required argument missing
375 parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
376 parrot(110, voltage=220) # duplicate value for argument
377 parrot(actor='John Cleese') # unknown keyword
378
379In general, an argument list must have any positional arguments followed by any
380keyword arguments, where the keywords must be chosen from the formal parameter
381names. It's not important whether a formal parameter has a default value or
382not. No argument may receive a value more than once --- formal parameter names
383corresponding to positional arguments cannot be used as keywords in the same
384calls. Here's an example that fails due to this restriction::
385
386 >>> def function(a):
387 ... pass
388 ...
389 >>> function(0, a=0)
390 Traceback (most recent call last):
391 File "<stdin>", line 1, in ?
392 TypeError: function() got multiple values for keyword argument 'a'
393
394When a final formal parameter of the form ``**name`` is present, it receives a
395dictionary (see :ref:`typesmapping`) containing all keyword arguments except for
396those corresponding to a formal parameter. This may be combined with a formal
397parameter of the form ``*name`` (described in the next subsection) which
398receives a tuple containing the positional arguments beyond the formal parameter
399list. (``*name`` must occur before ``**name``.) For example, if we define a
400function like this::
401
402 def cheeseshop(kind, *arguments, **keywords):
403 print "-- Do you have any", kind, '?'
404 print "-- I'm sorry, we're all out of", kind
405 for arg in arguments: print arg
406 print '-'*40
407 keys = keywords.keys()
408 keys.sort()
409 for kw in keys: print kw, ':', keywords[kw]
410
411It could be called like this::
412
413 cheeseshop('Limburger', "It's very runny, sir.",
414 "It's really very, VERY runny, sir.",
415 client='John Cleese',
416 shopkeeper='Michael Palin',
417 sketch='Cheese Shop Sketch')
418
419and of course it would print::
420
421 -- Do you have any Limburger ?
422 -- I'm sorry, we're all out of Limburger
423 It's very runny, sir.
424 It's really very, VERY runny, sir.
425 ----------------------------------------
426 client : John Cleese
427 shopkeeper : Michael Palin
428 sketch : Cheese Shop Sketch
429
430Note that the :meth:`sort` method of the list of keyword argument names is
431called before printing the contents of the ``keywords`` dictionary; if this is
432not done, the order in which the arguments are printed is undefined.
433
434
435.. _tut-arbitraryargs:
436
437Arbitrary Argument Lists
438------------------------
439
440Finally, the least frequently used option is to specify that a function can be
441called with an arbitrary number of arguments. These arguments will be wrapped
442up in a tuple. Before the variable number of arguments, zero or more normal
443arguments may occur. ::
444
445 def fprintf(file, format, *args):
446 file.write(format % args)
447
448
449.. _tut-unpacking-arguments:
450
451Unpacking Argument Lists
452------------------------
453
454The reverse situation occurs when the arguments are already in a list or tuple
455but need to be unpacked for a function call requiring separate positional
456arguments. For instance, the built-in :func:`range` function expects separate
457*start* and *stop* arguments. If they are not available separately, write the
458function call with the ``*``\ -operator to unpack the arguments out of a list
459or tuple::
460
461 >>> range(3, 6) # normal call with separate arguments
462 [3, 4, 5]
463 >>> args = [3, 6]
464 >>> range(*args) # call with arguments unpacked from a list
465 [3, 4, 5]
466
467In the same fashion, dictionaries can deliver keyword arguments with the ``**``\
468-operator::
469
470 >>> def parrot(voltage, state='a stiff', action='voom'):
471 ... print "-- This parrot wouldn't", action,
472 ... print "if you put", voltage, "volts through it.",
473 ... print "E's", state, "!"
474 ...
475 >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
476 >>> parrot(**d)
477 -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
478
479
480.. _tut-lambda:
481
482Lambda Forms
483------------
484
485By popular demand, a few features commonly found in functional programming
486languages like Lisp have been added to Python. With the :keyword:`lambda`
487keyword, small anonymous functions can be created. Here's a function that
488returns the sum of its two arguments: ``lambda a, b: a+b``. Lambda forms can be
489used wherever function objects are required. They are syntactically restricted
490to a single expression. Semantically, they are just syntactic sugar for a
491normal function definition. Like nested function definitions, lambda forms can
492reference variables from the containing scope::
493
494 >>> def make_incrementor(n):
495 ... return lambda x: x + n
496 ...
497 >>> f = make_incrementor(42)
498 >>> f(0)
499 42
500 >>> f(1)
501 43
502
503
504.. _tut-docstrings:
505
506Documentation Strings
507---------------------
508
509.. index::
510 single: docstrings
511 single: documentation strings
512 single: strings, documentation
513
514There are emerging conventions about the content and formatting of documentation
515strings.
516
517The first line should always be a short, concise summary of the object's
518purpose. For brevity, it should not explicitly state the object's name or type,
519since these are available by other means (except if the name happens to be a
520verb describing a function's operation). This line should begin with a capital
521letter and end with a period.
522
523If there are more lines in the documentation string, the second line should be
524blank, visually separating the summary from the rest of the description. The
525following lines should be one or more paragraphs describing the object's calling
526conventions, its side effects, etc.
527
528The Python parser does not strip indentation from multi-line string literals in
529Python, so tools that process documentation have to strip indentation if
530desired. This is done using the following convention. The first non-blank line
531*after* the first line of the string determines the amount of indentation for
532the entire documentation string. (We can't use the first line since it is
533generally adjacent to the string's opening quotes so its indentation is not
534apparent in the string literal.) Whitespace "equivalent" to this indentation is
535then stripped from the start of all lines of the string. Lines that are
536indented less should not occur, but if they occur all their leading whitespace
537should be stripped. Equivalence of whitespace should be tested after expansion
538of tabs (to 8 spaces, normally).
539
540Here is an example of a multi-line docstring::
541
542 >>> def my_function():
543 ... """Do nothing, but document it.
544 ...
545 ... No, really, it doesn't do anything.
546 ... """
547 ... pass
548 ...
549 >>> print my_function.__doc__
550 Do nothing, but document it.
551
552 No, really, it doesn't do anything.
553
554
Georg Brandl35f88612008-01-06 22:05:40 +0000555.. _tut-codingstyle:
556
557Intermezzo: Coding Style
558========================
559
560.. sectionauthor:: Georg Brandl <georg@python.org>
561.. index:: pair: coding; style
562
563Now that you are about to write longer, more complex pieces of Python, it is a
564good time to talk about *coding style*. Most languages can be written (or more
565concise, *formatted*) in different styles; some are more readable than others.
566Making it easy for others to read your code is always a good idea, and adopting
567a nice coding style helps tremendously for that.
568
569For Python, :pep:`8` has emerged as the style guide that most projects adher to;
570it promotes a very readable and eye-pleasing coding style. Every Python
571developer should read it at some point; here are the most important points
572extracted for you:
573
574* Use 4-space indentation, and no tabs.
575
576 4 spaces are a good compromise between small indentation (allows greater
577 nesting depth) and large indentation (easier to read). Tabs introduce
578 confusion, and are best left out.
579
580* Wrap lines so that they don't exceed 79 characters.
581
582 This helps users with small displays and makes it possible to have several
583 code files side-by-side on larger displays.
584
585* Use blank lines to separate functions and classes, and larger blocks of
586 code inside functions.
587
588* When possible, put comments on a line of their own.
589
590* Use docstrings.
591
592* Use spaces around operators and after commas, but not directly inside
593 bracketing constructs: ``a = f(1, 2) + g(3, 4)``.
594
595* Name your classes and functions consistently; the convention is to use
596 ``CamelCase`` for classes and ``lower_case_with_underscores`` for functions
597 and methods. Always use ``self`` as the name for the first method argument.
598
599* Don't use fancy encodings if your code is meant to be used in international
600 environments. Plain ASCII works best in any case.
601
Georg Brandl8ec7f652007-08-15 14:28:01 +0000602
603.. rubric:: Footnotes
604
Georg Brandl35f88612008-01-06 22:05:40 +0000605.. [#] Actually, *call by object reference* would be a better description,
606 since if a mutable object is passed, the caller will see any changes the
607 callee makes to it (items inserted into a list).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000608