blob: 5fdddcb16dd132c977a0cbcf08eaaf9649e30095 [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
199
200.. _tut-functions:
201
202Defining Functions
203==================
204
205We can create a function that writes the Fibonacci series to an arbitrary
206boundary::
207
208 >>> def fib(n): # write Fibonacci series up to n
209 ... """Print a Fibonacci series up to n."""
210 ... a, b = 0, 1
211 ... while b < n:
Georg Brandle4ac7502007-09-03 07:10:24 +0000212 ... print(b, end=' ')
Georg Brandl116aa622007-08-15 14:28:22 +0000213 ... a, b = b, a+b
Guido van Rossum0616b792007-08-31 03:25:11 +0000214 ... print()
Georg Brandl116aa622007-08-15 14:28:22 +0000215 ...
216 >>> # Now call the function we just defined:
217 ... fib(2000)
218 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
219
220.. index::
221 single: documentation strings
222 single: docstrings
223 single: strings, documentation
224
225The keyword :keyword:`def` introduces a function *definition*. It must be
226followed by the function name and the parenthesized list of formal parameters.
227The statements that form the body of the function start at the next line, and
Georg Brandl5d955ed2008-09-13 17:18:21 +0000228must be indented.
Georg Brandl116aa622007-08-15 14:28:22 +0000229
Georg Brandl5d955ed2008-09-13 17:18:21 +0000230The first statement of the function body can optionally be a string literal;
231this string literal is the function's documentation string, or :dfn:`docstring`.
232(More about docstrings can be found in the section :ref:`tut-docstrings`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000233There are tools which use docstrings to automatically produce online or printed
234documentation, or to let the user interactively browse through code; it's good
Georg Brandl5d955ed2008-09-13 17:18:21 +0000235practice to include docstrings in code that you write, so make a habit of it.
Georg Brandl116aa622007-08-15 14:28:22 +0000236
237The *execution* of a function introduces a new symbol table used for the local
238variables of the function. More precisely, all variable assignments in a
239function store the value in the local symbol table; whereas variable references
Georg Brandl86def6c2008-01-21 20:36:10 +0000240first look in the local symbol table, then in the local symbol tables of
241enclosing functions, then in the global symbol table, and finally in the table
242of built-in names. Thus, global variables cannot be directly assigned a value
243within a function (unless named in a :keyword:`global` statement), although they
244may be referenced.
Georg Brandl116aa622007-08-15 14:28:22 +0000245
246The actual parameters (arguments) to a function call are introduced in the local
247symbol table of the called function when it is called; thus, arguments are
248passed using *call by value* (where the *value* is always an object *reference*,
249not the value of the object). [#]_ When a function calls another function, a new
250local symbol table is created for that call.
251
252A function definition introduces the function name in the current symbol table.
253The value of the function name has a type that is recognized by the interpreter
254as a user-defined function. This value can be assigned to another name which
255can then also be used as a function. This serves as a general renaming
256mechanism::
257
258 >>> fib
259 <function fib at 10042ed0>
260 >>> f = fib
261 >>> f(100)
262 1 1 2 3 5 8 13 21 34 55 89
263
Georg Brandl5d955ed2008-09-13 17:18:21 +0000264Coming from other languages, you might object that ``fib`` is not a function but
265a procedure since it doesn't return a value. In fact, even functions without a
266:keyword:`return` statement do return a value, albeit a rather boring one. This
267value is called ``None`` (it's a built-in name). Writing the value ``None`` is
268normally suppressed by the interpreter if it would be the only value written.
269You can see it if you really want to using :func:`print`::
Georg Brandl116aa622007-08-15 14:28:22 +0000270
Georg Brandl9afde1c2007-11-01 20:32:30 +0000271 >>> fib(0)
Guido van Rossum0616b792007-08-31 03:25:11 +0000272 >>> print(fib(0))
Georg Brandl116aa622007-08-15 14:28:22 +0000273 None
274
275It is simple to write a function that returns a list of the numbers of the
276Fibonacci series, instead of printing it::
277
278 >>> def fib2(n): # return Fibonacci series up to n
279 ... """Return a list containing the Fibonacci series up to n."""
280 ... result = []
281 ... a, b = 0, 1
282 ... while b < n:
283 ... result.append(b) # see below
284 ... a, b = b, a+b
285 ... return result
286 ...
287 >>> f100 = fib2(100) # call it
288 >>> f100 # write the result
289 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
290
291This example, as usual, demonstrates some new Python features:
292
293* The :keyword:`return` statement returns with a value from a function.
294 :keyword:`return` without an expression argument returns ``None``. Falling off
Georg Brandl5d955ed2008-09-13 17:18:21 +0000295 the end of a function also returns ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000296
297* The statement ``result.append(b)`` calls a *method* of the list object
298 ``result``. A method is a function that 'belongs' to an object and is named
299 ``obj.methodname``, where ``obj`` is some object (this may be an expression),
300 and ``methodname`` is the name of a method that is defined by the object's type.
301 Different types define different methods. Methods of different types may have
302 the same name without causing ambiguity. (It is possible to define your own
303 object types and methods, using *classes*, as discussed later in this tutorial.)
304 The method :meth:`append` shown in the example is defined for list objects; it
305 adds a new element at the end of the list. In this example it is equivalent to
306 ``result = result + [b]``, but more efficient.
307
308
309.. _tut-defining:
310
311More on Defining Functions
312==========================
313
314It is also possible to define functions with a variable number of arguments.
315There are three forms, which can be combined.
316
317
318.. _tut-defaultargs:
319
320Default Argument Values
321-----------------------
322
323The most useful form is to specify a default value for one or more arguments.
324This creates a function that can be called with fewer arguments than it is
325defined to allow. For example::
326
Georg Brandl116aa622007-08-15 14:28:22 +0000327 def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
328 while True:
Georg Brandle9af2842007-08-17 05:54:09 +0000329 ok = input(prompt)
Georg Brandl116aa622007-08-15 14:28:22 +0000330 if ok in ('y', 'ye', 'yes'): return True
331 if ok in ('n', 'no', 'nop', 'nope'): return False
332 retries = retries - 1
Collin Winter58721bc2007-09-10 00:39:52 +0000333 if retries < 0:
334 raise IOError('refusenik user')
Guido van Rossum0616b792007-08-31 03:25:11 +0000335 print(complaint)
Georg Brandl116aa622007-08-15 14:28:22 +0000336
337This function can be called either like this: ``ask_ok('Do you really want to
338quit?')`` or like this: ``ask_ok('OK to overwrite the file?', 2)``.
339
340This example also introduces the :keyword:`in` keyword. This tests whether or
341not a sequence contains a certain value.
342
343The default values are evaluated at the point of function definition in the
344*defining* scope, so that ::
345
346 i = 5
347
348 def f(arg=i):
Guido van Rossum0616b792007-08-31 03:25:11 +0000349 print(arg)
Georg Brandl116aa622007-08-15 14:28:22 +0000350
351 i = 6
352 f()
353
354will print ``5``.
355
356**Important warning:** The default value is evaluated only once. This makes a
357difference when the default is a mutable object such as a list, dictionary, or
358instances of most classes. For example, the following function accumulates the
359arguments passed to it on subsequent calls::
360
361 def f(a, L=[]):
362 L.append(a)
363 return L
364
Guido van Rossum0616b792007-08-31 03:25:11 +0000365 print(f(1))
366 print(f(2))
367 print(f(3))
Georg Brandl116aa622007-08-15 14:28:22 +0000368
369This will print ::
370
371 [1]
372 [1, 2]
373 [1, 2, 3]
374
375If you don't want the default to be shared between subsequent calls, you can
376write the function like this instead::
377
378 def f(a, L=None):
379 if L is None:
380 L = []
381 L.append(a)
382 return L
383
384
385.. _tut-keywordargs:
386
387Keyword Arguments
388-----------------
389
390Functions can also be called using keyword arguments of the form ``keyword =
391value``. For instance, the following function::
392
393 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000394 print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000395 print("if you put", voltage, "volts through it.")
396 print("-- Lovely plumage, the", type)
397 print("-- It's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399could be called in any of the following ways::
400
401 parrot(1000)
402 parrot(action = 'VOOOOOM', voltage = 1000000)
403 parrot('a thousand', state = 'pushing up the daisies')
404 parrot('a million', 'bereft of life', 'jump')
405
406but the following calls would all be invalid::
407
408 parrot() # required argument missing
409 parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
410 parrot(110, voltage=220) # duplicate value for argument
411 parrot(actor='John Cleese') # unknown keyword
412
413In general, an argument list must have any positional arguments followed by any
414keyword arguments, where the keywords must be chosen from the formal parameter
415names. It's not important whether a formal parameter has a default value or
416not. No argument may receive a value more than once --- formal parameter names
417corresponding to positional arguments cannot be used as keywords in the same
418calls. Here's an example that fails due to this restriction::
419
420 >>> def function(a):
421 ... pass
422 ...
423 >>> function(0, a=0)
424 Traceback (most recent call last):
425 File "<stdin>", line 1, in ?
426 TypeError: function() got multiple values for keyword argument 'a'
427
428When a final formal parameter of the form ``**name`` is present, it receives a
429dictionary (see :ref:`typesmapping`) containing all keyword arguments except for
430those corresponding to a formal parameter. This may be combined with a formal
431parameter of the form ``*name`` (described in the next subsection) which
432receives a tuple containing the positional arguments beyond the formal parameter
433list. (``*name`` must occur before ``**name``.) For example, if we define a
434function like this::
435
436 def cheeseshop(kind, *arguments, **keywords):
Georg Brandl5d955ed2008-09-13 17:18:21 +0000437 print("-- Do you have any", kind, "?")
Guido van Rossum0616b792007-08-31 03:25:11 +0000438 print("-- I'm sorry, we're all out of", kind)
Georg Brandl11e18b02008-08-05 09:04:16 +0000439 for arg in arguments: print(arg)
Georg Brandl5d955ed2008-09-13 17:18:21 +0000440 print("-" * 40)
Neal Norwitze0906d12007-08-31 03:46:28 +0000441 keys = sorted(keywords.keys())
Georg Brandl5d955ed2008-09-13 17:18:21 +0000442 for kw in keys: print(kw, ":", keywords[kw])
Georg Brandl116aa622007-08-15 14:28:22 +0000443
444It could be called like this::
445
Georg Brandl5d955ed2008-09-13 17:18:21 +0000446 cheeseshop("Limburger", "It's very runny, sir.",
Georg Brandl116aa622007-08-15 14:28:22 +0000447 "It's really very, VERY runny, sir.",
Georg Brandl5d955ed2008-09-13 17:18:21 +0000448 shopkeeper="Michael Palin",
449 client="John Cleese",
450 sketch="Cheese Shop Sketch")
Georg Brandl116aa622007-08-15 14:28:22 +0000451
452and of course it would print::
453
454 -- Do you have any Limburger ?
455 -- I'm sorry, we're all out of Limburger
456 It's very runny, sir.
457 It's really very, VERY runny, sir.
458 ----------------------------------------
459 client : John Cleese
460 shopkeeper : Michael Palin
461 sketch : Cheese Shop Sketch
462
Georg Brandla6fa2722008-01-06 17:25:36 +0000463Note that the list of keyword argument names is created by sorting the result
464of the keywords dictionary's ``keys()`` method before printing its contents;
465if this is not done, the order in which the arguments are printed is undefined.
Georg Brandl116aa622007-08-15 14:28:22 +0000466
467.. _tut-arbitraryargs:
468
469Arbitrary Argument Lists
470------------------------
471
Christian Heimesdae2a892008-04-19 00:55:37 +0000472.. index::
473 statement: *
474
Georg Brandl116aa622007-08-15 14:28:22 +0000475Finally, the least frequently used option is to specify that a function can be
476called with an arbitrary number of arguments. These arguments will be wrapped
Georg Brandl5d955ed2008-09-13 17:18:21 +0000477up in a tuple (see :ref:`tut-tuples`). Before the variable number of arguments,
478zero or more normal arguments may occur. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000479
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000480 def write_multiple_items(file, separator, *args):
481 file.write(separator.join(args))
Georg Brandl116aa622007-08-15 14:28:22 +0000482
Guido van Rossum0616b792007-08-31 03:25:11 +0000483
484Normally, these ``variadic`` arguments will be last in the list of formal
485parameters, because they scoop up all remaining input arguments that are
486passed to the function. Any formal parameters which occur after the ``*args``
487parameter are 'keyword-only' arguments, meaning that they can only be used as
Georg Brandle4ac7502007-09-03 07:10:24 +0000488keywords rather than positional arguments. ::
Guido van Rossum0616b792007-08-31 03:25:11 +0000489
490 >>> def concat(*args, sep="/"):
491 ... return sep.join(args)
492 ...
493 >>> concat("earth", "mars", "venus")
494 'earth/mars/venus'
495 >>> concat("earth", "mars", "venus", sep=".")
496 'earth.mars.venus'
Georg Brandl116aa622007-08-15 14:28:22 +0000497
498.. _tut-unpacking-arguments:
499
500Unpacking Argument Lists
501------------------------
502
503The reverse situation occurs when the arguments are already in a list or tuple
504but need to be unpacked for a function call requiring separate positional
505arguments. For instance, the built-in :func:`range` function expects separate
506*start* and *stop* arguments. If they are not available separately, write the
507function call with the ``*``\ -operator to unpack the arguments out of a list
508or tuple::
509
Guido van Rossum0616b792007-08-31 03:25:11 +0000510 >>> list(range(3, 6)) # normal call with separate arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000511 [3, 4, 5]
512 >>> args = [3, 6]
Guido van Rossum0616b792007-08-31 03:25:11 +0000513 >>> list(range(*args)) # call with arguments unpacked from a list
Georg Brandl116aa622007-08-15 14:28:22 +0000514 [3, 4, 5]
515
Christian Heimesdae2a892008-04-19 00:55:37 +0000516.. index::
517 statement: **
518
Georg Brandl116aa622007-08-15 14:28:22 +0000519In the same fashion, dictionaries can deliver keyword arguments with the ``**``\
520-operator::
521
522 >>> def parrot(voltage, state='a stiff', action='voom'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000523 ... print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000524 ... print("if you put", voltage, "volts through it.", end=' ')
525 ... print("E's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000526 ...
527 >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
528 >>> parrot(**d)
529 -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
530
531
532.. _tut-lambda:
533
534Lambda Forms
535------------
536
537By popular demand, a few features commonly found in functional programming
538languages like Lisp have been added to Python. With the :keyword:`lambda`
539keyword, small anonymous functions can be created. Here's a function that
540returns the sum of its two arguments: ``lambda a, b: a+b``. Lambda forms can be
541used wherever function objects are required. They are syntactically restricted
542to a single expression. Semantically, they are just syntactic sugar for a
543normal function definition. Like nested function definitions, lambda forms can
544reference variables from the containing scope::
545
546 >>> def make_incrementor(n):
547 ... return lambda x: x + n
548 ...
549 >>> f = make_incrementor(42)
550 >>> f(0)
551 42
552 >>> f(1)
553 43
554
555
556.. _tut-docstrings:
557
558Documentation Strings
559---------------------
560
561.. index::
562 single: docstrings
563 single: documentation strings
564 single: strings, documentation
565
Guido van Rossum0616b792007-08-31 03:25:11 +0000566Here are some conventions about the content and formatting of documentation
567strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000568
569The first line should always be a short, concise summary of the object's
570purpose. For brevity, it should not explicitly state the object's name or type,
571since these are available by other means (except if the name happens to be a
572verb describing a function's operation). This line should begin with a capital
573letter and end with a period.
574
575If there are more lines in the documentation string, the second line should be
576blank, visually separating the summary from the rest of the description. The
577following lines should be one or more paragraphs describing the object's calling
578conventions, its side effects, etc.
579
580The Python parser does not strip indentation from multi-line string literals in
581Python, so tools that process documentation have to strip indentation if
582desired. This is done using the following convention. The first non-blank line
583*after* the first line of the string determines the amount of indentation for
584the entire documentation string. (We can't use the first line since it is
585generally adjacent to the string's opening quotes so its indentation is not
586apparent in the string literal.) Whitespace "equivalent" to this indentation is
587then stripped from the start of all lines of the string. Lines that are
588indented less should not occur, but if they occur all their leading whitespace
589should be stripped. Equivalence of whitespace should be tested after expansion
590of tabs (to 8 spaces, normally).
591
592Here is an example of a multi-line docstring::
593
594 >>> def my_function():
595 ... """Do nothing, but document it.
596 ...
597 ... No, really, it doesn't do anything.
598 ... """
599 ... pass
600 ...
Guido van Rossum0616b792007-08-31 03:25:11 +0000601 >>> print(my_function.__doc__)
Georg Brandl116aa622007-08-15 14:28:22 +0000602 Do nothing, but document it.
603
604 No, really, it doesn't do anything.
605
606
Christian Heimes043d6f62008-01-07 17:19:16 +0000607.. _tut-codingstyle:
608
609Intermezzo: Coding Style
610========================
611
612.. sectionauthor:: Georg Brandl <georg@python.org>
613.. index:: pair: coding; style
614
615Now that you are about to write longer, more complex pieces of Python, it is a
616good time to talk about *coding style*. Most languages can be written (or more
617concise, *formatted*) in different styles; some are more readable than others.
618Making it easy for others to read your code is always a good idea, and adopting
619a nice coding style helps tremendously for that.
620
Christian Heimesdae2a892008-04-19 00:55:37 +0000621For Python, :pep:`8` has emerged as the style guide that most projects adhere to;
Christian Heimes043d6f62008-01-07 17:19:16 +0000622it promotes a very readable and eye-pleasing coding style. Every Python
623developer should read it at some point; here are the most important points
624extracted for you:
625
626* Use 4-space indentation, and no tabs.
627
628 4 spaces are a good compromise between small indentation (allows greater
629 nesting depth) and large indentation (easier to read). Tabs introduce
630 confusion, and are best left out.
631
632* Wrap lines so that they don't exceed 79 characters.
633
634 This helps users with small displays and makes it possible to have several
635 code files side-by-side on larger displays.
636
637* Use blank lines to separate functions and classes, and larger blocks of
638 code inside functions.
639
640* When possible, put comments on a line of their own.
641
642* Use docstrings.
643
644* Use spaces around operators and after commas, but not directly inside
645 bracketing constructs: ``a = f(1, 2) + g(3, 4)``.
646
647* Name your classes and functions consistently; the convention is to use
648 ``CamelCase`` for classes and ``lower_case_with_underscores`` for functions
Georg Brandl5d955ed2008-09-13 17:18:21 +0000649 and methods. Always use ``self`` as the name for the first method argument
650 (see :ref:`tut-firstclasses` for more on classes and methods).
Christian Heimes043d6f62008-01-07 17:19:16 +0000651
652* Don't use fancy encodings if your code is meant to be used in international
653 environments. Plain ASCII works best in any case.
654
Georg Brandl116aa622007-08-15 14:28:22 +0000655
656.. rubric:: Footnotes
657
Christian Heimes043d6f62008-01-07 17:19:16 +0000658.. [#] Actually, *call by object reference* would be a better description,
659 since if a mutable object is passed, the caller will see any changes the
660 callee makes to it (items inserted into a list).
Georg Brandl116aa622007-08-15 14:28:22 +0000661