blob: 2a55cf1261f6374cd59c6900c5fd9dd06a828e50 [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
Georg Brandle9af2842007-08-17 05:54:09 +000019 >>> x = int(input("Please enter an integer: "))
Georg Brandl5d955ed2008-09-13 17:18:21 +000020 Please enter an integer: 42
Georg Brandl116aa622007-08-15 14:28:22 +000021 >>> if x < 0:
22 ... x = 0
Guido van Rossum0616b792007-08-31 03:25:11 +000023 ... print('Negative changed to zero')
Georg Brandl116aa622007-08-15 14:28:22 +000024 ... elif x == 0:
Guido van Rossum0616b792007-08-31 03:25:11 +000025 ... print('Zero')
Georg Brandl116aa622007-08-15 14:28:22 +000026 ... elif x == 1:
Guido van Rossum0616b792007-08-31 03:25:11 +000027 ... print('Single')
Georg Brandl116aa622007-08-15 14:28:22 +000028 ... else:
Guido van Rossum0616b792007-08-31 03:25:11 +000029 ... print('More')
Georg Brandl5d955ed2008-09-13 17:18:21 +000030 ...
31 More
Georg Brandl116aa622007-08-15 14:28:22 +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` ...
Christian Heimes5b5e81c2007-12-31 16:14:33 +000036:keyword:`elif` ... sequence is a substitute for the ``switch`` or
37``case`` statements found in other languages.
Georg Brandl116aa622007-08-15 14:28:22 +000038
39
40.. _tut-for:
41
42:keyword:`for` Statements
43=========================
44
45.. index::
46 statement: for
Georg Brandl116aa622007-08-15 14:28:22 +000047
48The :keyword:`for` statement in Python differs a bit from what you may be used
49to in C or Pascal. Rather than always iterating over an arithmetic progression
50of numbers (like in Pascal), or giving the user the ability to define both the
51iteration step and halting condition (as C), Python's :keyword:`for` statement
52iterates over the items of any sequence (a list or a string), in the order that
53they appear in the sequence. For example (no pun intended):
54
Christian Heimes5b5e81c2007-12-31 16:14:33 +000055.. One suggestion was to give a real C example here, but that may only serve to
56 confuse non-C programmers.
Georg Brandl116aa622007-08-15 14:28:22 +000057
58::
59
60 >>> # Measure some strings:
61 ... a = ['cat', 'window', 'defenestrate']
62 >>> for x in a:
Guido van Rossum0616b792007-08-31 03:25:11 +000063 ... print(x, len(x))
Georg Brandl116aa622007-08-15 14:28:22 +000064 ...
65 cat 3
66 window 6
67 defenestrate 12
68
69It is not safe to modify the sequence being iterated over in the loop (this can
70only happen for mutable sequence types, such as lists). If you need to modify
71the list you are iterating over (for example, to duplicate selected items) you
72must iterate over a copy. The slice notation makes this particularly
73convenient::
74
75 >>> for x in a[:]: # make a slice copy of the entire list
76 ... if len(x) > 6: a.insert(0, x)
77 ...
78 >>> a
79 ['defenestrate', 'cat', 'window', 'defenestrate']
80
81
82.. _tut-range:
83
84The :func:`range` Function
85==========================
86
87If you do need to iterate over a sequence of numbers, the built-in function
Guido van Rossum0616b792007-08-31 03:25:11 +000088:func:`range` comes in handy. It generates arithmetic progressions::
Georg Brandl116aa622007-08-15 14:28:22 +000089
Guido van Rossum0616b792007-08-31 03:25:11 +000090
91 >>> for i in range(5):
92 ... print(i)
93 ...
94 0
95 1
96 2
97 3
98 4
99
100
Georg Brandl116aa622007-08-15 14:28:22 +0000101
102The given end point is never part of the generated list; ``range(10)`` generates
Guido van Rossum0616b792007-08-31 03:25:11 +000010310 values, the legal indices for items of a sequence of length 10. It
Georg Brandl116aa622007-08-15 14:28:22 +0000104is possible to let the range start at another number, or to specify a different
105increment (even negative; sometimes this is called the 'step')::
106
Guido van Rossum0616b792007-08-31 03:25:11 +0000107 range(5, 10)
108 5 through 9
109
110 range(0, 10, 3)
111 0, 3, 6, 9
112
113 range(-10, -100, -30)
114 -10, -40, -70
Georg Brandl116aa622007-08-15 14:28:22 +0000115
116To iterate over the indices of a sequence, combine :func:`range` and :func:`len`
117as follows::
118
119 >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
120 >>> for i in range(len(a)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000121 ... print(i, a[i])
Georg Brandl116aa622007-08-15 14:28:22 +0000122 ...
123 0 Mary
124 1 had
125 2 a
126 3 little
127 4 lamb
128
Guido van Rossum0616b792007-08-31 03:25:11 +0000129A strange thing happens if you just print a range::
130
131 >>> print(range(10))
132 range(0, 10)
133
134In many ways the object returned by :func:`range` behaves as if it is a list,
135but in fact it isn't. It is an object which returns the successive items of
136the desired sequence when you iterate over it, but it doesn't really make
137the list, thus saving space.
138
139We say such an object is *iterable*, that is, suitable as a target for
140functions and constructs that expect something from which they can
141obtain successive items until the supply is exhausted. We have seen that
142the :keyword:`for` statement is such an *iterator*. The function :func:`list`
143is another; it creates lists from iterables::
144
145
146 >>> list(range(5))
147 [0, 1, 2, 3, 4]
148
149Later we will see more functions that return iterables and take iterables as argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000150
151.. _tut-break:
152
153:keyword:`break` and :keyword:`continue` Statements, and :keyword:`else` Clauses on Loops
154=========================================================================================
155
156The :keyword:`break` statement, like in C, breaks out of the smallest enclosing
157:keyword:`for` or :keyword:`while` loop.
158
159The :keyword:`continue` statement, also borrowed from C, continues with the next
160iteration of the loop.
161
162Loop statements may have an ``else`` clause; it is executed when the loop
163terminates through exhaustion of the list (with :keyword:`for`) or when the
164condition becomes false (with :keyword:`while`), but not when the loop is
165terminated by a :keyword:`break` statement. This is exemplified by the
166following loop, which searches for prime numbers::
167
168 >>> for n in range(2, 10):
169 ... for x in range(2, n):
170 ... if n % x == 0:
Georg Brandlb03c1d92008-05-01 18:06:50 +0000171 ... print(n, 'equals', x, '*', n//x)
Georg Brandl116aa622007-08-15 14:28:22 +0000172 ... break
173 ... else:
174 ... # loop fell through without finding a factor
Guido van Rossum0616b792007-08-31 03:25:11 +0000175 ... print(n, 'is a prime number')
Georg Brandl116aa622007-08-15 14:28:22 +0000176 ...
177 2 is a prime number
178 3 is a prime number
179 4 equals 2 * 2
180 5 is a prime number
181 6 equals 2 * 3
182 7 is a prime number
183 8 equals 2 * 4
184 9 equals 3 * 3
185
186
187.. _tut-pass:
188
189:keyword:`pass` Statements
190==========================
191
192The :keyword:`pass` statement does nothing. It can be used when a statement is
193required syntactically but the program requires no action. For example::
194
195 >>> while True:
Georg Brandl5d955ed2008-09-13 17:18:21 +0000196 ... pass # Busy-wait for keyboard interrupt (Ctrl+C)
Georg Brandl116aa622007-08-15 14:28:22 +0000197 ...
198
Georg Brandla971c652008-11-07 09:39:56 +0000199This is commonly used for creating minimal classes such as exceptions, or
200for ignoring unwanted exceptions::
201
202 >>> class ParserError(Exception):
203 ... pass
204 ...
205 >>> try:
206 ... import audioop
207 ... except ImportError:
208 ... pass
209 ...
210
211Another place :keyword:`pass` can be used is as a place-holder for a function or
212conditional body when you are working on new code, allowing you to keep
213thinking at a more abstract level. However, as :keyword:`pass` is silently
214ignored, a better choice may be to raise a :exc:`NotImplementedError`
215exception::
216
217 >>> def initlog(*args):
218 ... raise NotImplementedError # Open logfile if not already open
219 ... if not logfp:
220 ... raise NotImplementedError # Set up dummy log back-end
221 ... raise NotImplementedError('Call log initialization handler')
222 ...
223
224If :keyword:`pass` were used here and you later ran tests, they may fail
225without indicating why. Using :exc:`NotImplementedError` causes this code
226to raise an exception, telling you exactly where the incomplete code
227is. Note the two calling styles of the exceptions above.
228The first style, with no message but with an accompanying comment,
229lets you easily leave the comment when you remove the exception,
230which ideally would be a good description for
231the block of code the exception is a placeholder for. However, the
232third example, providing a message for the exception, will produce
233a more useful traceback.
Georg Brandl116aa622007-08-15 14:28:22 +0000234
235.. _tut-functions:
236
237Defining Functions
238==================
239
240We can create a function that writes the Fibonacci series to an arbitrary
241boundary::
242
243 >>> def fib(n): # write Fibonacci series up to n
244 ... """Print a Fibonacci series up to n."""
245 ... a, b = 0, 1
246 ... while b < n:
Georg Brandle4ac7502007-09-03 07:10:24 +0000247 ... print(b, end=' ')
Georg Brandl116aa622007-08-15 14:28:22 +0000248 ... a, b = b, a+b
Guido van Rossum0616b792007-08-31 03:25:11 +0000249 ... print()
Georg Brandl116aa622007-08-15 14:28:22 +0000250 ...
251 >>> # Now call the function we just defined:
252 ... fib(2000)
253 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
254
255.. index::
256 single: documentation strings
257 single: docstrings
258 single: strings, documentation
259
260The keyword :keyword:`def` introduces a function *definition*. It must be
261followed by the function name and the parenthesized list of formal parameters.
262The statements that form the body of the function start at the next line, and
Georg Brandl5d955ed2008-09-13 17:18:21 +0000263must be indented.
Georg Brandl116aa622007-08-15 14:28:22 +0000264
Georg Brandl5d955ed2008-09-13 17:18:21 +0000265The first statement of the function body can optionally be a string literal;
266this string literal is the function's documentation string, or :dfn:`docstring`.
267(More about docstrings can be found in the section :ref:`tut-docstrings`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000268There are tools which use docstrings to automatically produce online or printed
269documentation, or to let the user interactively browse through code; it's good
Georg Brandl5d955ed2008-09-13 17:18:21 +0000270practice to include docstrings in code that you write, so make a habit of it.
Georg Brandl116aa622007-08-15 14:28:22 +0000271
272The *execution* of a function introduces a new symbol table used for the local
273variables of the function. More precisely, all variable assignments in a
274function store the value in the local symbol table; whereas variable references
Georg Brandl86def6c2008-01-21 20:36:10 +0000275first look in the local symbol table, then in the local symbol tables of
276enclosing functions, then in the global symbol table, and finally in the table
277of built-in names. Thus, global variables cannot be directly assigned a value
278within a function (unless named in a :keyword:`global` statement), although they
279may be referenced.
Georg Brandl116aa622007-08-15 14:28:22 +0000280
281The actual parameters (arguments) to a function call are introduced in the local
282symbol table of the called function when it is called; thus, arguments are
283passed using *call by value* (where the *value* is always an object *reference*,
284not the value of the object). [#]_ When a function calls another function, a new
285local symbol table is created for that call.
286
287A function definition introduces the function name in the current symbol table.
288The value of the function name has a type that is recognized by the interpreter
289as a user-defined function. This value can be assigned to another name which
290can then also be used as a function. This serves as a general renaming
291mechanism::
292
293 >>> fib
294 <function fib at 10042ed0>
295 >>> f = fib
296 >>> f(100)
297 1 1 2 3 5 8 13 21 34 55 89
298
Georg Brandl5d955ed2008-09-13 17:18:21 +0000299Coming from other languages, you might object that ``fib`` is not a function but
300a procedure since it doesn't return a value. In fact, even functions without a
301:keyword:`return` statement do return a value, albeit a rather boring one. This
302value is called ``None`` (it's a built-in name). Writing the value ``None`` is
303normally suppressed by the interpreter if it would be the only value written.
304You can see it if you really want to using :func:`print`::
Georg Brandl116aa622007-08-15 14:28:22 +0000305
Georg Brandl9afde1c2007-11-01 20:32:30 +0000306 >>> fib(0)
Guido van Rossum0616b792007-08-31 03:25:11 +0000307 >>> print(fib(0))
Georg Brandl116aa622007-08-15 14:28:22 +0000308 None
309
310It is simple to write a function that returns a list of the numbers of the
311Fibonacci series, instead of printing it::
312
313 >>> def fib2(n): # return Fibonacci series up to n
314 ... """Return a list containing the Fibonacci series up to n."""
315 ... result = []
316 ... a, b = 0, 1
317 ... while b < n:
318 ... result.append(b) # see below
319 ... a, b = b, a+b
320 ... return result
321 ...
322 >>> f100 = fib2(100) # call it
323 >>> f100 # write the result
324 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
325
326This example, as usual, demonstrates some new Python features:
327
328* The :keyword:`return` statement returns with a value from a function.
329 :keyword:`return` without an expression argument returns ``None``. Falling off
Georg Brandl5d955ed2008-09-13 17:18:21 +0000330 the end of a function also returns ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000331
332* The statement ``result.append(b)`` calls a *method* of the list object
333 ``result``. A method is a function that 'belongs' to an object and is named
334 ``obj.methodname``, where ``obj`` is some object (this may be an expression),
335 and ``methodname`` is the name of a method that is defined by the object's type.
336 Different types define different methods. Methods of different types may have
337 the same name without causing ambiguity. (It is possible to define your own
338 object types and methods, using *classes*, as discussed later in this tutorial.)
339 The method :meth:`append` shown in the example is defined for list objects; it
340 adds a new element at the end of the list. In this example it is equivalent to
341 ``result = result + [b]``, but more efficient.
342
343
344.. _tut-defining:
345
346More on Defining Functions
347==========================
348
349It is also possible to define functions with a variable number of arguments.
350There are three forms, which can be combined.
351
352
353.. _tut-defaultargs:
354
355Default Argument Values
356-----------------------
357
358The most useful form is to specify a default value for one or more arguments.
359This creates a function that can be called with fewer arguments than it is
360defined to allow. For example::
361
Georg Brandl116aa622007-08-15 14:28:22 +0000362 def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
363 while True:
Georg Brandle9af2842007-08-17 05:54:09 +0000364 ok = input(prompt)
Georg Brandl116aa622007-08-15 14:28:22 +0000365 if ok in ('y', 'ye', 'yes'): return True
366 if ok in ('n', 'no', 'nop', 'nope'): return False
367 retries = retries - 1
Collin Winter58721bc2007-09-10 00:39:52 +0000368 if retries < 0:
369 raise IOError('refusenik user')
Guido van Rossum0616b792007-08-31 03:25:11 +0000370 print(complaint)
Georg Brandl116aa622007-08-15 14:28:22 +0000371
372This function can be called either like this: ``ask_ok('Do you really want to
373quit?')`` or like this: ``ask_ok('OK to overwrite the file?', 2)``.
374
375This example also introduces the :keyword:`in` keyword. This tests whether or
376not a sequence contains a certain value.
377
378The default values are evaluated at the point of function definition in the
379*defining* scope, so that ::
380
381 i = 5
382
383 def f(arg=i):
Guido van Rossum0616b792007-08-31 03:25:11 +0000384 print(arg)
Georg Brandl116aa622007-08-15 14:28:22 +0000385
386 i = 6
387 f()
388
389will print ``5``.
390
391**Important warning:** The default value is evaluated only once. This makes a
392difference when the default is a mutable object such as a list, dictionary, or
393instances of most classes. For example, the following function accumulates the
394arguments passed to it on subsequent calls::
395
396 def f(a, L=[]):
397 L.append(a)
398 return L
399
Guido van Rossum0616b792007-08-31 03:25:11 +0000400 print(f(1))
401 print(f(2))
402 print(f(3))
Georg Brandl116aa622007-08-15 14:28:22 +0000403
404This will print ::
405
406 [1]
407 [1, 2]
408 [1, 2, 3]
409
410If you don't want the default to be shared between subsequent calls, you can
411write the function like this instead::
412
413 def f(a, L=None):
414 if L is None:
415 L = []
416 L.append(a)
417 return L
418
419
420.. _tut-keywordargs:
421
422Keyword Arguments
423-----------------
424
425Functions can also be called using keyword arguments of the form ``keyword =
426value``. For instance, the following function::
427
428 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000429 print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000430 print("if you put", voltage, "volts through it.")
431 print("-- Lovely plumage, the", type)
432 print("-- It's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000433
434could be called in any of the following ways::
435
436 parrot(1000)
437 parrot(action = 'VOOOOOM', voltage = 1000000)
438 parrot('a thousand', state = 'pushing up the daisies')
439 parrot('a million', 'bereft of life', 'jump')
440
441but the following calls would all be invalid::
442
443 parrot() # required argument missing
444 parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
445 parrot(110, voltage=220) # duplicate value for argument
446 parrot(actor='John Cleese') # unknown keyword
447
448In general, an argument list must have any positional arguments followed by any
449keyword arguments, where the keywords must be chosen from the formal parameter
450names. It's not important whether a formal parameter has a default value or
451not. No argument may receive a value more than once --- formal parameter names
452corresponding to positional arguments cannot be used as keywords in the same
453calls. Here's an example that fails due to this restriction::
454
455 >>> def function(a):
456 ... pass
457 ...
458 >>> function(0, a=0)
459 Traceback (most recent call last):
460 File "<stdin>", line 1, in ?
461 TypeError: function() got multiple values for keyword argument 'a'
462
463When a final formal parameter of the form ``**name`` is present, it receives a
464dictionary (see :ref:`typesmapping`) containing all keyword arguments except for
465those corresponding to a formal parameter. This may be combined with a formal
466parameter of the form ``*name`` (described in the next subsection) which
467receives a tuple containing the positional arguments beyond the formal parameter
468list. (``*name`` must occur before ``**name``.) For example, if we define a
469function like this::
470
471 def cheeseshop(kind, *arguments, **keywords):
Georg Brandl5d955ed2008-09-13 17:18:21 +0000472 print("-- Do you have any", kind, "?")
Guido van Rossum0616b792007-08-31 03:25:11 +0000473 print("-- I'm sorry, we're all out of", kind)
Georg Brandl11e18b02008-08-05 09:04:16 +0000474 for arg in arguments: print(arg)
Georg Brandl5d955ed2008-09-13 17:18:21 +0000475 print("-" * 40)
Neal Norwitze0906d12007-08-31 03:46:28 +0000476 keys = sorted(keywords.keys())
Georg Brandl5d955ed2008-09-13 17:18:21 +0000477 for kw in keys: print(kw, ":", keywords[kw])
Georg Brandl116aa622007-08-15 14:28:22 +0000478
479It could be called like this::
480
Georg Brandl5d955ed2008-09-13 17:18:21 +0000481 cheeseshop("Limburger", "It's very runny, sir.",
Georg Brandl116aa622007-08-15 14:28:22 +0000482 "It's really very, VERY runny, sir.",
Georg Brandl5d955ed2008-09-13 17:18:21 +0000483 shopkeeper="Michael Palin",
484 client="John Cleese",
485 sketch="Cheese Shop Sketch")
Georg Brandl116aa622007-08-15 14:28:22 +0000486
487and of course it would print::
488
489 -- Do you have any Limburger ?
490 -- I'm sorry, we're all out of Limburger
491 It's very runny, sir.
492 It's really very, VERY runny, sir.
493 ----------------------------------------
494 client : John Cleese
495 shopkeeper : Michael Palin
496 sketch : Cheese Shop Sketch
497
Georg Brandla6fa2722008-01-06 17:25:36 +0000498Note that the list of keyword argument names is created by sorting the result
499of the keywords dictionary's ``keys()`` method before printing its contents;
500if this is not done, the order in which the arguments are printed is undefined.
Georg Brandl116aa622007-08-15 14:28:22 +0000501
502.. _tut-arbitraryargs:
503
504Arbitrary Argument Lists
505------------------------
506
Christian Heimesdae2a892008-04-19 00:55:37 +0000507.. index::
508 statement: *
509
Georg Brandl116aa622007-08-15 14:28:22 +0000510Finally, the least frequently used option is to specify that a function can be
511called with an arbitrary number of arguments. These arguments will be wrapped
Georg Brandl5d955ed2008-09-13 17:18:21 +0000512up in a tuple (see :ref:`tut-tuples`). Before the variable number of arguments,
513zero or more normal arguments may occur. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000514
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000515 def write_multiple_items(file, separator, *args):
516 file.write(separator.join(args))
Georg Brandl116aa622007-08-15 14:28:22 +0000517
Guido van Rossum0616b792007-08-31 03:25:11 +0000518
519Normally, these ``variadic`` arguments will be last in the list of formal
520parameters, because they scoop up all remaining input arguments that are
521passed to the function. Any formal parameters which occur after the ``*args``
522parameter are 'keyword-only' arguments, meaning that they can only be used as
Georg Brandle4ac7502007-09-03 07:10:24 +0000523keywords rather than positional arguments. ::
Guido van Rossum0616b792007-08-31 03:25:11 +0000524
525 >>> def concat(*args, sep="/"):
526 ... return sep.join(args)
527 ...
528 >>> concat("earth", "mars", "venus")
529 'earth/mars/venus'
530 >>> concat("earth", "mars", "venus", sep=".")
531 'earth.mars.venus'
Georg Brandl116aa622007-08-15 14:28:22 +0000532
533.. _tut-unpacking-arguments:
534
535Unpacking Argument Lists
536------------------------
537
538The reverse situation occurs when the arguments are already in a list or tuple
539but need to be unpacked for a function call requiring separate positional
540arguments. For instance, the built-in :func:`range` function expects separate
541*start* and *stop* arguments. If they are not available separately, write the
542function call with the ``*``\ -operator to unpack the arguments out of a list
543or tuple::
544
Guido van Rossum0616b792007-08-31 03:25:11 +0000545 >>> list(range(3, 6)) # normal call with separate arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000546 [3, 4, 5]
547 >>> args = [3, 6]
Guido van Rossum0616b792007-08-31 03:25:11 +0000548 >>> list(range(*args)) # call with arguments unpacked from a list
Georg Brandl116aa622007-08-15 14:28:22 +0000549 [3, 4, 5]
550
Christian Heimesdae2a892008-04-19 00:55:37 +0000551.. index::
552 statement: **
553
Georg Brandl116aa622007-08-15 14:28:22 +0000554In the same fashion, dictionaries can deliver keyword arguments with the ``**``\
555-operator::
556
557 >>> def parrot(voltage, state='a stiff', action='voom'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000558 ... print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000559 ... print("if you put", voltage, "volts through it.", end=' ')
560 ... print("E's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000561 ...
562 >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
563 >>> parrot(**d)
564 -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
565
566
567.. _tut-lambda:
568
569Lambda Forms
570------------
571
572By popular demand, a few features commonly found in functional programming
573languages like Lisp have been added to Python. With the :keyword:`lambda`
574keyword, small anonymous functions can be created. Here's a function that
575returns the sum of its two arguments: ``lambda a, b: a+b``. Lambda forms can be
576used wherever function objects are required. They are syntactically restricted
577to a single expression. Semantically, they are just syntactic sugar for a
578normal function definition. Like nested function definitions, lambda forms can
579reference variables from the containing scope::
580
581 >>> def make_incrementor(n):
582 ... return lambda x: x + n
583 ...
584 >>> f = make_incrementor(42)
585 >>> f(0)
586 42
587 >>> f(1)
588 43
589
590
591.. _tut-docstrings:
592
593Documentation Strings
594---------------------
595
596.. index::
597 single: docstrings
598 single: documentation strings
599 single: strings, documentation
600
Guido van Rossum0616b792007-08-31 03:25:11 +0000601Here are some conventions about the content and formatting of documentation
602strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000603
604The first line should always be a short, concise summary of the object's
605purpose. For brevity, it should not explicitly state the object's name or type,
606since these are available by other means (except if the name happens to be a
607verb describing a function's operation). This line should begin with a capital
608letter and end with a period.
609
610If there are more lines in the documentation string, the second line should be
611blank, visually separating the summary from the rest of the description. The
612following lines should be one or more paragraphs describing the object's calling
613conventions, its side effects, etc.
614
615The Python parser does not strip indentation from multi-line string literals in
616Python, so tools that process documentation have to strip indentation if
617desired. This is done using the following convention. The first non-blank line
618*after* the first line of the string determines the amount of indentation for
619the entire documentation string. (We can't use the first line since it is
620generally adjacent to the string's opening quotes so its indentation is not
621apparent in the string literal.) Whitespace "equivalent" to this indentation is
622then stripped from the start of all lines of the string. Lines that are
623indented less should not occur, but if they occur all their leading whitespace
624should be stripped. Equivalence of whitespace should be tested after expansion
625of tabs (to 8 spaces, normally).
626
627Here is an example of a multi-line docstring::
628
629 >>> def my_function():
630 ... """Do nothing, but document it.
631 ...
632 ... No, really, it doesn't do anything.
633 ... """
634 ... pass
635 ...
Guido van Rossum0616b792007-08-31 03:25:11 +0000636 >>> print(my_function.__doc__)
Georg Brandl116aa622007-08-15 14:28:22 +0000637 Do nothing, but document it.
638
639 No, really, it doesn't do anything.
640
641
Christian Heimes043d6f62008-01-07 17:19:16 +0000642.. _tut-codingstyle:
643
644Intermezzo: Coding Style
645========================
646
647.. sectionauthor:: Georg Brandl <georg@python.org>
648.. index:: pair: coding; style
649
650Now that you are about to write longer, more complex pieces of Python, it is a
651good time to talk about *coding style*. Most languages can be written (or more
652concise, *formatted*) in different styles; some are more readable than others.
653Making it easy for others to read your code is always a good idea, and adopting
654a nice coding style helps tremendously for that.
655
Christian Heimesdae2a892008-04-19 00:55:37 +0000656For Python, :pep:`8` has emerged as the style guide that most projects adhere to;
Christian Heimes043d6f62008-01-07 17:19:16 +0000657it promotes a very readable and eye-pleasing coding style. Every Python
658developer should read it at some point; here are the most important points
659extracted for you:
660
661* Use 4-space indentation, and no tabs.
662
663 4 spaces are a good compromise between small indentation (allows greater
664 nesting depth) and large indentation (easier to read). Tabs introduce
665 confusion, and are best left out.
666
667* Wrap lines so that they don't exceed 79 characters.
668
669 This helps users with small displays and makes it possible to have several
670 code files side-by-side on larger displays.
671
672* Use blank lines to separate functions and classes, and larger blocks of
673 code inside functions.
674
675* When possible, put comments on a line of their own.
676
677* Use docstrings.
678
679* Use spaces around operators and after commas, but not directly inside
680 bracketing constructs: ``a = f(1, 2) + g(3, 4)``.
681
682* Name your classes and functions consistently; the convention is to use
683 ``CamelCase`` for classes and ``lower_case_with_underscores`` for functions
Georg Brandl5d955ed2008-09-13 17:18:21 +0000684 and methods. Always use ``self`` as the name for the first method argument
685 (see :ref:`tut-firstclasses` for more on classes and methods).
Christian Heimes043d6f62008-01-07 17:19:16 +0000686
687* Don't use fancy encodings if your code is meant to be used in international
688 environments. Plain ASCII works best in any case.
689
Georg Brandl116aa622007-08-15 14:28:22 +0000690
691.. rubric:: Footnotes
692
Christian Heimes043d6f62008-01-07 17:19:16 +0000693.. [#] Actually, *call by object reference* would be a better description,
694 since if a mutable object is passed, the caller will see any changes the
695 callee makes to it (items inserted into a list).
Georg Brandl116aa622007-08-15 14:28:22 +0000696