blob: 3d3af4e9374966d027b9810261cce492da45b667 [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: "))
Georg Brandl3ce0dee2008-09-13 17:18:11 +000020 Please enter an integer: 42
Georg Brandl8ec7f652007-08-15 14:28:01 +000021 >>> if x < 0:
22 ... x = 0
23 ... print 'Negative changed to zero'
24 ... elif x == 0:
25 ... print 'Zero'
26 ... elif x == 1:
27 ... print 'Single'
28 ... else:
29 ... print 'More'
Georg Brandl3ce0dee2008-09-13 17:18:11 +000030 ...
31 More
Georg Brandl8ec7f652007-08-15 14:28:01 +000032
33There can be zero or more :keyword:`elif` parts, and the :keyword:`else` part is
34optional. The keyword ':keyword:`elif`' is short for 'else if', and is useful
35to avoid excessive indentation. An :keyword:`if` ... :keyword:`elif` ...
Georg Brandlb19be572007-12-29 10:57:00 +000036:keyword:`elif` ... sequence is a substitute for the ``switch`` or
37``case`` statements found in other languages.
Georg Brandl8ec7f652007-08-15 14:28:01 +000038
39
40.. _tut-for:
41
42:keyword:`for` Statements
43=========================
44
45.. index::
46 statement: for
47 statement: for
48
49The :keyword:`for` statement in Python differs a bit from what you may be used
50to in C or Pascal. Rather than always iterating over an arithmetic progression
51of numbers (like in Pascal), or giving the user the ability to define both the
52iteration step and halting condition (as C), Python's :keyword:`for` statement
53iterates over the items of any sequence (a list or a string), in the order that
54they appear in the sequence. For example (no pun intended):
55
Georg Brandlb19be572007-12-29 10:57:00 +000056.. One suggestion was to give a real C example here, but that may only serve to
57 confuse non-C programmers.
Georg Brandl8ec7f652007-08-15 14:28:01 +000058
59::
60
61 >>> # Measure some strings:
62 ... a = ['cat', 'window', 'defenestrate']
63 >>> for x in a:
64 ... print x, len(x)
Georg Brandlc62ef8b2009-01-03 20:55:06 +000065 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +000066 cat 3
67 window 6
68 defenestrate 12
69
70It is not safe to modify the sequence being iterated over in the loop (this can
71only happen for mutable sequence types, such as lists). If you need to modify
72the list you are iterating over (for example, to duplicate selected items) you
73must iterate over a copy. The slice notation makes this particularly
74convenient::
75
76 >>> for x in a[:]: # make a slice copy of the entire list
77 ... if len(x) > 6: a.insert(0, x)
Georg Brandlc62ef8b2009-01-03 20:55:06 +000078 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +000079 >>> a
80 ['defenestrate', 'cat', 'window', 'defenestrate']
81
82
83.. _tut-range:
84
85The :func:`range` Function
86==========================
87
88If you do need to iterate over a sequence of numbers, the built-in function
89:func:`range` comes in handy. It generates lists containing arithmetic
90progressions::
91
92 >>> range(10)
93 [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
94
95The given end point is never part of the generated list; ``range(10)`` generates
96a list of 10 values, the legal indices for items of a sequence of length 10. It
97is possible to let the range start at another number, or to specify a different
98increment (even negative; sometimes this is called the 'step')::
99
100 >>> range(5, 10)
101 [5, 6, 7, 8, 9]
102 >>> range(0, 10, 3)
103 [0, 3, 6, 9]
104 >>> range(-10, -100, -30)
105 [-10, -40, -70]
106
Georg Brandl34196c82008-12-04 18:54:05 +0000107To iterate over the indices of a sequence, you can combine :func:`range` and
108:func:`len` as follows::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000109
110 >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
111 >>> for i in range(len(a)):
112 ... print i, a[i]
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000113 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000114 0 Mary
115 1 had
116 2 a
117 3 little
118 4 lamb
119
Georg Brandl34196c82008-12-04 18:54:05 +0000120In most such cases, however, it is convenient to use the :func:`enumerate`
121function, see :ref:`tut-loopidioms`.
122
Georg Brandl8ec7f652007-08-15 14:28:01 +0000123
124.. _tut-break:
125
126:keyword:`break` and :keyword:`continue` Statements, and :keyword:`else` Clauses on Loops
127=========================================================================================
128
129The :keyword:`break` statement, like in C, breaks out of the smallest enclosing
130:keyword:`for` or :keyword:`while` loop.
131
Georg Brandl8ec7f652007-08-15 14:28:01 +0000132Loop statements may have an ``else`` clause; it is executed when the loop
133terminates through exhaustion of the list (with :keyword:`for`) or when the
134condition becomes false (with :keyword:`while`), but not when the loop is
135terminated by a :keyword:`break` statement. This is exemplified by the
136following loop, which searches for prime numbers::
137
138 >>> for n in range(2, 10):
139 ... for x in range(2, n):
140 ... if n % x == 0:
141 ... print n, 'equals', x, '*', n/x
142 ... break
Benjamin Peterson80790282008-08-02 03:05:11 +0000143 ... else:
144 ... # loop fell through without finding a factor
145 ... print n, 'is a prime number'
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000146 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000147 2 is a prime number
148 3 is a prime number
149 4 equals 2 * 2
150 5 is a prime number
151 6 equals 2 * 3
152 7 is a prime number
153 8 equals 2 * 4
154 9 equals 3 * 3
155
Georg Brandla350f0f2011-08-08 21:45:13 +0200156(Yes, this is the correct code. Look closely: the ``else`` clause belongs to
157the :keyword:`for` loop, **not** the :keyword:`if` statement.)
158
Nick Coghlan0a09f3e2012-06-07 22:57:35 +1000159When used with a loop, the ``else`` clause has more in common with the
160``else`` clause of a :keyword:`try` statement than it does that of
161:keyword:`if` statements: a :keyword:`try` statement's ``else`` clause runs
162when no exception occurs, and a loop's ``else`` clause runs when no ``break``
163occurs. For more on the :keyword:`try` statement and exceptions, see
164:ref:`tut-handling`.
165
Senthil Kumaran2f76f732012-08-12 11:58:53 -0700166The :keyword:`continue` statement, also borrowed from C, continues with the next
167iteration of the loop::
168
169 >>> for num in range(2, 10):
Eli Bendersky2cc49742012-08-18 09:51:37 +0300170 ... if num % 2 == 0:
Senthil Kumaran2f76f732012-08-12 11:58:53 -0700171 ... print("Found an even number", num)
172 ... continue
173 ... print("Found a number", num)
174 Found an even number 2
175 Found a number 3
176 Found an even number 4
177 Found a number 5
178 Found an even number 6
179 Found a number 7
180 Found an even number 8
181 Found a number 9
Georg Brandl8ec7f652007-08-15 14:28:01 +0000182
183.. _tut-pass:
184
185:keyword:`pass` Statements
186==========================
187
188The :keyword:`pass` statement does nothing. It can be used when a statement is
189required syntactically but the program requires no action. For example::
190
191 >>> while True:
Georg Brandl3ce0dee2008-09-13 17:18:11 +0000192 ... pass # Busy-wait for keyboard interrupt (Ctrl+C)
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000193 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000194
Benjamin Peterson42d19e62008-12-24 16:10:05 +0000195This is commonly used for creating minimal classes::
Georg Brandla8bb5502008-11-06 18:49:15 +0000196
Benjamin Peterson42d19e62008-12-24 16:10:05 +0000197 >>> class MyEmptyClass:
Georg Brandla8bb5502008-11-06 18:49:15 +0000198 ... pass
Benjamin Peterson42d19e62008-12-24 16:10:05 +0000199 ...
Georg Brandla8bb5502008-11-06 18:49:15 +0000200
Andrew M. Kuchlingfcdc80b2008-11-06 19:23:02 +0000201Another place :keyword:`pass` can be used is as a place-holder for a function or
Benjamin Peterson42d19e62008-12-24 16:10:05 +0000202conditional body when you are working on new code, allowing you to keep thinking
203at a more abstract level. The :keyword:`pass` is silently ignored::
Georg Brandla8bb5502008-11-06 18:49:15 +0000204
205 >>> def initlog(*args):
Benjamin Peterson42d19e62008-12-24 16:10:05 +0000206 ... pass # Remember to implement this!
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000207 ...
Georg Brandla8bb5502008-11-06 18:49:15 +0000208
Georg Brandl8ec7f652007-08-15 14:28:01 +0000209.. _tut-functions:
210
211Defining Functions
212==================
213
214We can create a function that writes the Fibonacci series to an arbitrary
215boundary::
216
217 >>> def fib(n): # write Fibonacci series up to n
218 ... """Print a Fibonacci series up to n."""
219 ... a, b = 0, 1
Mark Dickinsonf058d2d2009-11-23 16:39:05 +0000220 ... while a < n:
221 ... print a,
Georg Brandl8ec7f652007-08-15 14:28:01 +0000222 ... a, b = b, a+b
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000223 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000224 >>> # Now call the function we just defined:
225 ... fib(2000)
Mark Dickinsonf058d2d2009-11-23 16:39:05 +0000226 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Georg Brandl8ec7f652007-08-15 14:28:01 +0000227
228.. index::
229 single: documentation strings
230 single: docstrings
231 single: strings, documentation
232
233The keyword :keyword:`def` introduces a function *definition*. It must be
234followed by the function name and the parenthesized list of formal parameters.
235The statements that form the body of the function start at the next line, and
Georg Brandl3ce0dee2008-09-13 17:18:11 +0000236must be indented.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000237
Georg Brandl3ce0dee2008-09-13 17:18:11 +0000238The first statement of the function body can optionally be a string literal;
239this string literal is the function's documentation string, or :dfn:`docstring`.
240(More about docstrings can be found in the section :ref:`tut-docstrings`.)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000241There are tools which use docstrings to automatically produce online or printed
242documentation, or to let the user interactively browse through code; it's good
Georg Brandl3ce0dee2008-09-13 17:18:11 +0000243practice to include docstrings in code that you write, so make a habit of it.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000244
245The *execution* of a function introduces a new symbol table used for the local
246variables of the function. More precisely, all variable assignments in a
247function store the value in the local symbol table; whereas variable references
Georg Brandlaa0de3f2008-01-21 16:51:51 +0000248first look in the local symbol table, then in the local symbol tables of
249enclosing functions, then in the global symbol table, and finally in the table
250of built-in names. Thus, global variables cannot be directly assigned a value
251within a function (unless named in a :keyword:`global` statement), although they
252may be referenced.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000253
254The actual parameters (arguments) to a function call are introduced in the local
255symbol table of the called function when it is called; thus, arguments are
256passed using *call by value* (where the *value* is always an object *reference*,
257not the value of the object). [#]_ When a function calls another function, a new
258local symbol table is created for that call.
259
260A function definition introduces the function name in the current symbol table.
261The value of the function name has a type that is recognized by the interpreter
262as a user-defined function. This value can be assigned to another name which
263can then also be used as a function. This serves as a general renaming
264mechanism::
265
266 >>> fib
267 <function fib at 10042ed0>
268 >>> f = fib
269 >>> f(100)
Mark Dickinsonf058d2d2009-11-23 16:39:05 +0000270 0 1 1 2 3 5 8 13 21 34 55 89
Georg Brandl8ec7f652007-08-15 14:28:01 +0000271
Georg Brandl3ce0dee2008-09-13 17:18:11 +0000272Coming from other languages, you might object that ``fib`` is not a function but
273a procedure since it doesn't return a value. In fact, even functions without a
274:keyword:`return` statement do return a value, albeit a rather boring one. This
275value is called ``None`` (it's a built-in name). Writing the value ``None`` is
276normally suppressed by the interpreter if it would be the only value written.
277You can see it if you really want to using :keyword:`print`::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000278
Georg Brandl706132b2007-10-30 17:57:12 +0000279 >>> fib(0)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000280 >>> print fib(0)
281 None
282
283It is simple to write a function that returns a list of the numbers of the
284Fibonacci series, instead of printing it::
285
286 >>> def fib2(n): # return Fibonacci series up to n
287 ... """Return a list containing the Fibonacci series up to n."""
288 ... result = []
289 ... a, b = 0, 1
Mark Dickinsonf058d2d2009-11-23 16:39:05 +0000290 ... while a < n:
291 ... result.append(a) # see below
Georg Brandl8ec7f652007-08-15 14:28:01 +0000292 ... a, b = b, a+b
293 ... return result
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000294 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000295 >>> f100 = fib2(100) # call it
296 >>> f100 # write the result
Mark Dickinsonf058d2d2009-11-23 16:39:05 +0000297 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000298
299This example, as usual, demonstrates some new Python features:
300
301* The :keyword:`return` statement returns with a value from a function.
302 :keyword:`return` without an expression argument returns ``None``. Falling off
Georg Brandl3ce0dee2008-09-13 17:18:11 +0000303 the end of a function also returns ``None``.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000304
Mark Dickinsonf058d2d2009-11-23 16:39:05 +0000305* The statement ``result.append(a)`` calls a *method* of the list object
Georg Brandl8ec7f652007-08-15 14:28:01 +0000306 ``result``. A method is a function that 'belongs' to an object and is named
307 ``obj.methodname``, where ``obj`` is some object (this may be an expression),
308 and ``methodname`` is the name of a method that is defined by the object's type.
309 Different types define different methods. Methods of different types may have
310 the same name without causing ambiguity. (It is possible to define your own
Georg Brandle3b9b5e2009-06-06 17:51:31 +0000311 object types and methods, using *classes*, see :ref:`tut-classes`)
Georg Brandl8ec7f652007-08-15 14:28:01 +0000312 The method :meth:`append` shown in the example is defined for list objects; it
313 adds a new element at the end of the list. In this example it is equivalent to
Mark Dickinsonf058d2d2009-11-23 16:39:05 +0000314 ``result = result + [a]``, but more efficient.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000315
316
317.. _tut-defining:
318
319More on Defining Functions
320==========================
321
322It is also possible to define functions with a variable number of arguments.
323There are three forms, which can be combined.
324
325
326.. _tut-defaultargs:
327
328Default Argument Values
329-----------------------
330
331The most useful form is to specify a default value for one or more arguments.
332This creates a function that can be called with fewer arguments than it is
333defined to allow. For example::
334
335 def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
336 while True:
337 ok = raw_input(prompt)
Georg Brandl4c324b92009-06-06 17:50:05 +0000338 if ok in ('y', 'ye', 'yes'):
339 return True
340 if ok in ('n', 'no', 'nop', 'nope'):
341 return False
Georg Brandl8ec7f652007-08-15 14:28:01 +0000342 retries = retries - 1
Georg Brandl4c324b92009-06-06 17:50:05 +0000343 if retries < 0:
344 raise IOError('refusenik user')
Georg Brandl8ec7f652007-08-15 14:28:01 +0000345 print complaint
346
Georg Brandl4c324b92009-06-06 17:50:05 +0000347This function can be called in several ways:
348
349* giving only the mandatory argument:
350 ``ask_ok('Do you really want to quit?')``
351* giving one of the optional arguments:
352 ``ask_ok('OK to overwrite the file?', 2)``
353* or even giving all arguments:
354 ``ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')``
Georg Brandl8ec7f652007-08-15 14:28:01 +0000355
356This example also introduces the :keyword:`in` keyword. This tests whether or
357not a sequence contains a certain value.
358
359The default values are evaluated at the point of function definition in the
360*defining* scope, so that ::
361
362 i = 5
363
364 def f(arg=i):
365 print arg
366
367 i = 6
368 f()
369
370will print ``5``.
371
372**Important warning:** The default value is evaluated only once. This makes a
373difference when the default is a mutable object such as a list, dictionary, or
374instances of most classes. For example, the following function accumulates the
375arguments passed to it on subsequent calls::
376
377 def f(a, L=[]):
378 L.append(a)
379 return L
380
381 print f(1)
382 print f(2)
383 print f(3)
384
385This will print ::
386
387 [1]
388 [1, 2]
389 [1, 2, 3]
390
391If you don't want the default to be shared between subsequent calls, you can
392write the function like this instead::
393
394 def f(a, L=None):
395 if L is None:
396 L = []
397 L.append(a)
398 return L
399
400
401.. _tut-keywordargs:
402
403Keyword Arguments
404-----------------
405
Ezio Melotti05a7f0d2011-12-13 15:49:22 +0200406Functions can also be called using :term:`keyword arguments <keyword argument>`
407of the form ``kwarg=value``. For instance, the following function::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000408
409 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
410 print "-- This parrot wouldn't", action,
411 print "if you put", voltage, "volts through it."
412 print "-- Lovely plumage, the", type
413 print "-- It's", state, "!"
414
Ezio Melotti05a7f0d2011-12-13 15:49:22 +0200415accepts one required argument (``voltage``) and three optional arguments
416(``state``, ``action``, and ``type``). This function can be called in any
417of the following ways::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000418
Ezio Melotti05a7f0d2011-12-13 15:49:22 +0200419 parrot(1000) # 1 positional argument
420 parrot(voltage=1000) # 1 keyword argument
421 parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
422 parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
423 parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
424 parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
Georg Brandl8ec7f652007-08-15 14:28:01 +0000425
Ezio Melotti05a7f0d2011-12-13 15:49:22 +0200426but all the following calls would be invalid::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000427
428 parrot() # required argument missing
Ezio Melotti05a7f0d2011-12-13 15:49:22 +0200429 parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument
430 parrot(110, voltage=220) # duplicate value for the same argument
431 parrot(actor='John Cleese') # unknown keyword argument
Georg Brandl8ec7f652007-08-15 14:28:01 +0000432
Ezio Melotti05a7f0d2011-12-13 15:49:22 +0200433In a function call, keyword arguments must follow positional arguments.
434All the keyword arguments passed must match one of the arguments
435accepted by the function (e.g. ``actor`` is not a valid argument for the
436``parrot`` function), and their order is not important. This also includes
437non-optional arguments (e.g. ``parrot(voltage=1000)`` is valid too).
438No argument may receive a value more than once.
439Here's an example that fails due to this restriction::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000440
441 >>> def function(a):
442 ... pass
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000443 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000444 >>> function(0, a=0)
445 Traceback (most recent call last):
446 File "<stdin>", line 1, in ?
447 TypeError: function() got multiple values for keyword argument 'a'
448
449When a final formal parameter of the form ``**name`` is present, it receives a
450dictionary (see :ref:`typesmapping`) containing all keyword arguments except for
451those corresponding to a formal parameter. This may be combined with a formal
452parameter of the form ``*name`` (described in the next subsection) which
453receives a tuple containing the positional arguments beyond the formal parameter
454list. (``*name`` must occur before ``**name``.) For example, if we define a
455function like this::
456
457 def cheeseshop(kind, *arguments, **keywords):
Georg Brandl3ce0dee2008-09-13 17:18:11 +0000458 print "-- Do you have any", kind, "?"
Georg Brandl8ec7f652007-08-15 14:28:01 +0000459 print "-- I'm sorry, we're all out of", kind
Georg Brandl78f11ed2010-11-26 07:34:20 +0000460 for arg in arguments:
461 print arg
Georg Brandl3ce0dee2008-09-13 17:18:11 +0000462 print "-" * 40
Georg Brandl44c3ceb2010-10-15 15:31:09 +0000463 keys = sorted(keywords.keys())
464 for kw in keys:
465 print kw, ":", keywords[kw]
Georg Brandl8ec7f652007-08-15 14:28:01 +0000466
467It could be called like this::
468
Georg Brandl3ce0dee2008-09-13 17:18:11 +0000469 cheeseshop("Limburger", "It's very runny, sir.",
Georg Brandl8ec7f652007-08-15 14:28:01 +0000470 "It's really very, VERY runny, sir.",
Georg Brandl8ec7f652007-08-15 14:28:01 +0000471 shopkeeper='Michael Palin',
Georg Brandl3ce0dee2008-09-13 17:18:11 +0000472 client="John Cleese",
473 sketch="Cheese Shop Sketch")
Georg Brandl8ec7f652007-08-15 14:28:01 +0000474
475and of course it would print::
476
477 -- Do you have any Limburger ?
478 -- I'm sorry, we're all out of Limburger
479 It's very runny, sir.
480 It's really very, VERY runny, sir.
481 ----------------------------------------
482 client : John Cleese
483 shopkeeper : Michael Palin
484 sketch : Cheese Shop Sketch
485
Ezio Melottibfbd1a22011-05-17 05:39:22 +0300486Note that the list of keyword argument names is created by sorting the result
487of the keywords dictionary's ``keys()`` method before printing its contents;
488if this is not done, the order in which the arguments are printed is undefined.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000489
490.. _tut-arbitraryargs:
491
492Arbitrary Argument Lists
493------------------------
494
Andrew M. Kuchling3822af62008-04-15 13:10:07 +0000495.. index::
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000496 statement: *
Andrew M. Kuchling3822af62008-04-15 13:10:07 +0000497
Georg Brandl8ec7f652007-08-15 14:28:01 +0000498Finally, the least frequently used option is to specify that a function can be
499called with an arbitrary number of arguments. These arguments will be wrapped
Georg Brandl3ce0dee2008-09-13 17:18:11 +0000500up in a tuple (see :ref:`tut-tuples`). Before the variable number of arguments,
501zero or more normal arguments may occur. ::
Georg Brandl8ec7f652007-08-15 14:28:01 +0000502
Benjamin Petersondee01d82008-05-28 11:51:41 +0000503 def write_multiple_items(file, separator, *args):
504 file.write(separator.join(args))
Georg Brandl8ec7f652007-08-15 14:28:01 +0000505
506
507.. _tut-unpacking-arguments:
508
509Unpacking Argument Lists
510------------------------
511
512The reverse situation occurs when the arguments are already in a list or tuple
513but need to be unpacked for a function call requiring separate positional
514arguments. For instance, the built-in :func:`range` function expects separate
515*start* and *stop* arguments. If they are not available separately, write the
516function call with the ``*``\ -operator to unpack the arguments out of a list
517or tuple::
518
519 >>> range(3, 6) # normal call with separate arguments
520 [3, 4, 5]
521 >>> args = [3, 6]
522 >>> range(*args) # call with arguments unpacked from a list
523 [3, 4, 5]
524
Andrew M. Kuchling3822af62008-04-15 13:10:07 +0000525.. index::
526 statement: **
527
Georg Brandl8ec7f652007-08-15 14:28:01 +0000528In the same fashion, dictionaries can deliver keyword arguments with the ``**``\
529-operator::
530
531 >>> def parrot(voltage, state='a stiff', action='voom'):
532 ... print "-- This parrot wouldn't", action,
533 ... print "if you put", voltage, "volts through it.",
534 ... print "E's", state, "!"
535 ...
536 >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
537 >>> parrot(**d)
538 -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
539
540
541.. _tut-lambda:
542
543Lambda Forms
544------------
545
546By popular demand, a few features commonly found in functional programming
547languages like Lisp have been added to Python. With the :keyword:`lambda`
548keyword, small anonymous functions can be created. Here's a function that
549returns the sum of its two arguments: ``lambda a, b: a+b``. Lambda forms can be
550used wherever function objects are required. They are syntactically restricted
551to a single expression. Semantically, they are just syntactic sugar for a
552normal function definition. Like nested function definitions, lambda forms can
553reference variables from the containing scope::
554
555 >>> def make_incrementor(n):
556 ... return lambda x: x + n
557 ...
558 >>> f = make_incrementor(42)
559 >>> f(0)
560 42
561 >>> f(1)
562 43
563
564
565.. _tut-docstrings:
566
567Documentation Strings
568---------------------
569
570.. index::
571 single: docstrings
572 single: documentation strings
573 single: strings, documentation
574
575There are emerging conventions about the content and formatting of documentation
576strings.
577
578The first line should always be a short, concise summary of the object's
579purpose. For brevity, it should not explicitly state the object's name or type,
580since these are available by other means (except if the name happens to be a
581verb describing a function's operation). This line should begin with a capital
582letter and end with a period.
583
584If there are more lines in the documentation string, the second line should be
585blank, visually separating the summary from the rest of the description. The
586following lines should be one or more paragraphs describing the object's calling
587conventions, its side effects, etc.
588
589The Python parser does not strip indentation from multi-line string literals in
590Python, so tools that process documentation have to strip indentation if
591desired. This is done using the following convention. The first non-blank line
592*after* the first line of the string determines the amount of indentation for
593the entire documentation string. (We can't use the first line since it is
594generally adjacent to the string's opening quotes so its indentation is not
595apparent in the string literal.) Whitespace "equivalent" to this indentation is
596then stripped from the start of all lines of the string. Lines that are
597indented less should not occur, but if they occur all their leading whitespace
598should be stripped. Equivalence of whitespace should be tested after expansion
599of tabs (to 8 spaces, normally).
600
601Here is an example of a multi-line docstring::
602
603 >>> def my_function():
604 ... """Do nothing, but document it.
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000605 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000606 ... No, really, it doesn't do anything.
607 ... """
608 ... pass
Georg Brandlc62ef8b2009-01-03 20:55:06 +0000609 ...
Georg Brandl8ec7f652007-08-15 14:28:01 +0000610 >>> print my_function.__doc__
611 Do nothing, but document it.
612
613 No, really, it doesn't do anything.
614
615
Georg Brandl35f88612008-01-06 22:05:40 +0000616.. _tut-codingstyle:
617
618Intermezzo: Coding Style
619========================
620
621.. sectionauthor:: Georg Brandl <georg@python.org>
622.. index:: pair: coding; style
623
624Now that you are about to write longer, more complex pieces of Python, it is a
625good time to talk about *coding style*. Most languages can be written (or more
626concise, *formatted*) in different styles; some are more readable than others.
627Making it easy for others to read your code is always a good idea, and adopting
628a nice coding style helps tremendously for that.
629
Andrew M. Kuchling8c65b1e2008-04-15 13:10:41 +0000630For Python, :pep:`8` has emerged as the style guide that most projects adhere to;
Georg Brandl35f88612008-01-06 22:05:40 +0000631it promotes a very readable and eye-pleasing coding style. Every Python
632developer should read it at some point; here are the most important points
633extracted for you:
634
635* Use 4-space indentation, and no tabs.
636
637 4 spaces are a good compromise between small indentation (allows greater
638 nesting depth) and large indentation (easier to read). Tabs introduce
639 confusion, and are best left out.
640
641* Wrap lines so that they don't exceed 79 characters.
642
643 This helps users with small displays and makes it possible to have several
644 code files side-by-side on larger displays.
645
646* Use blank lines to separate functions and classes, and larger blocks of
647 code inside functions.
648
649* When possible, put comments on a line of their own.
650
651* Use docstrings.
652
653* Use spaces around operators and after commas, but not directly inside
654 bracketing constructs: ``a = f(1, 2) + g(3, 4)``.
655
656* Name your classes and functions consistently; the convention is to use
657 ``CamelCase`` for classes and ``lower_case_with_underscores`` for functions
Georg Brandl3ce0dee2008-09-13 17:18:11 +0000658 and methods. Always use ``self`` as the name for the first method argument
659 (see :ref:`tut-firstclasses` for more on classes and methods).
Georg Brandl35f88612008-01-06 22:05:40 +0000660
661* Don't use fancy encodings if your code is meant to be used in international
662 environments. Plain ASCII works best in any case.
663
Georg Brandl8ec7f652007-08-15 14:28:01 +0000664
665.. rubric:: Footnotes
666
Georg Brandl35f88612008-01-06 22:05:40 +0000667.. [#] Actually, *call by object reference* would be a better description,
668 since if a mutable object is passed, the caller will see any changes the
669 callee makes to it (items inserted into a list).
Georg Brandl8ec7f652007-08-15 14:28:01 +0000670