blob: 488ba91dd048b08184f669965bdda8df2768c561 [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 Brandl116aa622007-08-15 14:28:22 +000020 >>> if x < 0:
21 ... x = 0
Guido van Rossum0616b792007-08-31 03:25:11 +000022 ... print('Negative changed to zero')
Georg Brandl116aa622007-08-15 14:28:22 +000023 ... elif x == 0:
Guido van Rossum0616b792007-08-31 03:25:11 +000024 ... print('Zero')
Georg Brandl116aa622007-08-15 14:28:22 +000025 ... elif x == 1:
Guido van Rossum0616b792007-08-31 03:25:11 +000026 ... print('Single')
Georg Brandl116aa622007-08-15 14:28:22 +000027 ... else:
Guido van Rossum0616b792007-08-31 03:25:11 +000028 ... print('More')
Georg Brandl116aa622007-08-15 14:28:22 +000029 ...
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` ...
Christian Heimes5b5e81c2007-12-31 16:14:33 +000034:keyword:`elif` ... sequence is a substitute for the ``switch`` or
35``case`` statements found in other languages.
Georg Brandl116aa622007-08-15 14:28:22 +000036
37
38.. _tut-for:
39
40:keyword:`for` Statements
41=========================
42
43.. index::
44 statement: for
Georg Brandl116aa622007-08-15 14:28:22 +000045
46The :keyword:`for` statement in Python differs a bit from what you may be used
47to in C or Pascal. Rather than always iterating over an arithmetic progression
48of numbers (like in Pascal), or giving the user the ability to define both the
49iteration step and halting condition (as C), Python's :keyword:`for` statement
50iterates over the items of any sequence (a list or a string), in the order that
51they appear in the sequence. For example (no pun intended):
52
Christian Heimes5b5e81c2007-12-31 16:14:33 +000053.. One suggestion was to give a real C example here, but that may only serve to
54 confuse non-C programmers.
Georg Brandl116aa622007-08-15 14:28:22 +000055
56::
57
58 >>> # Measure some strings:
59 ... a = ['cat', 'window', 'defenestrate']
60 >>> for x in a:
Guido van Rossum0616b792007-08-31 03:25:11 +000061 ... print(x, len(x))
Georg Brandl116aa622007-08-15 14:28:22 +000062 ...
63 cat 3
64 window 6
65 defenestrate 12
66
67It is not safe to modify the sequence being iterated over in the loop (this can
68only happen for mutable sequence types, such as lists). If you need to modify
69the list you are iterating over (for example, to duplicate selected items) you
70must iterate over a copy. The slice notation makes this particularly
71convenient::
72
73 >>> for x in a[:]: # make a slice copy of the entire list
74 ... if len(x) > 6: a.insert(0, x)
75 ...
76 >>> a
77 ['defenestrate', 'cat', 'window', 'defenestrate']
78
79
80.. _tut-range:
81
82The :func:`range` Function
83==========================
84
85If you do need to iterate over a sequence of numbers, the built-in function
Guido van Rossum0616b792007-08-31 03:25:11 +000086:func:`range` comes in handy. It generates arithmetic progressions::
Georg Brandl116aa622007-08-15 14:28:22 +000087
Guido van Rossum0616b792007-08-31 03:25:11 +000088
89 >>> for i in range(5):
90 ... print(i)
91 ...
92 0
93 1
94 2
95 3
96 4
97
98
Georg Brandl116aa622007-08-15 14:28:22 +000099
100The given end point is never part of the generated list; ``range(10)`` generates
Guido van Rossum0616b792007-08-31 03:25:11 +000010110 values, the legal indices for items of a sequence of length 10. It
Georg Brandl116aa622007-08-15 14:28:22 +0000102is possible to let the range start at another number, or to specify a different
103increment (even negative; sometimes this is called the 'step')::
104
Guido van Rossum0616b792007-08-31 03:25:11 +0000105 range(5, 10)
106 5 through 9
107
108 range(0, 10, 3)
109 0, 3, 6, 9
110
111 range(-10, -100, -30)
112 -10, -40, -70
Georg Brandl116aa622007-08-15 14:28:22 +0000113
114To iterate over the indices of a sequence, combine :func:`range` and :func:`len`
115as follows::
116
117 >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
118 >>> for i in range(len(a)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000119 ... print(i, a[i])
Georg Brandl116aa622007-08-15 14:28:22 +0000120 ...
121 0 Mary
122 1 had
123 2 a
124 3 little
125 4 lamb
126
Guido van Rossum0616b792007-08-31 03:25:11 +0000127A strange thing happens if you just print a range::
128
129 >>> print(range(10))
130 range(0, 10)
131
132In many ways the object returned by :func:`range` behaves as if it is a list,
133but in fact it isn't. It is an object which returns the successive items of
134the desired sequence when you iterate over it, but it doesn't really make
135the list, thus saving space.
136
137We say such an object is *iterable*, that is, suitable as a target for
138functions and constructs that expect something from which they can
139obtain successive items until the supply is exhausted. We have seen that
140the :keyword:`for` statement is such an *iterator*. The function :func:`list`
141is another; it creates lists from iterables::
142
143
144 >>> list(range(5))
145 [0, 1, 2, 3, 4]
146
147Later we will see more functions that return iterables and take iterables as argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000148
149.. _tut-break:
150
151:keyword:`break` and :keyword:`continue` Statements, and :keyword:`else` Clauses on Loops
152=========================================================================================
153
154The :keyword:`break` statement, like in C, breaks out of the smallest enclosing
155:keyword:`for` or :keyword:`while` loop.
156
157The :keyword:`continue` statement, also borrowed from C, continues with the next
158iteration of the loop.
159
160Loop statements may have an ``else`` clause; it is executed when the loop
161terminates through exhaustion of the list (with :keyword:`for`) or when the
162condition becomes false (with :keyword:`while`), but not when the loop is
163terminated by a :keyword:`break` statement. This is exemplified by the
164following loop, which searches for prime numbers::
165
166 >>> for n in range(2, 10):
167 ... for x in range(2, n):
168 ... if n % x == 0:
Georg Brandlb03c1d92008-05-01 18:06:50 +0000169 ... print(n, 'equals', x, '*', n//x)
Georg Brandl116aa622007-08-15 14:28:22 +0000170 ... break
171 ... else:
172 ... # loop fell through without finding a factor
Guido van Rossum0616b792007-08-31 03:25:11 +0000173 ... print(n, 'is a prime number')
Georg Brandl116aa622007-08-15 14:28:22 +0000174 ...
175 2 is a prime number
176 3 is a prime number
177 4 equals 2 * 2
178 5 is a prime number
179 6 equals 2 * 3
180 7 is a prime number
181 8 equals 2 * 4
182 9 equals 3 * 3
183
184
185.. _tut-pass:
186
187:keyword:`pass` Statements
188==========================
189
190The :keyword:`pass` statement does nothing. It can be used when a statement is
191required syntactically but the program requires no action. For example::
192
193 >>> while True:
194 ... pass # Busy-wait for keyboard interrupt
195 ...
196
197
198.. _tut-functions:
199
200Defining Functions
201==================
202
203We can create a function that writes the Fibonacci series to an arbitrary
204boundary::
205
206 >>> def fib(n): # write Fibonacci series up to n
207 ... """Print a Fibonacci series up to n."""
208 ... a, b = 0, 1
209 ... while b < n:
Georg Brandle4ac7502007-09-03 07:10:24 +0000210 ... print(b, end=' ')
Georg Brandl116aa622007-08-15 14:28:22 +0000211 ... a, b = b, a+b
Guido van Rossum0616b792007-08-31 03:25:11 +0000212 ... print()
Georg Brandl116aa622007-08-15 14:28:22 +0000213 ...
214 >>> # Now call the function we just defined:
215 ... fib(2000)
216 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
217
218.. index::
219 single: documentation strings
220 single: docstrings
221 single: strings, documentation
222
223The keyword :keyword:`def` introduces a function *definition*. It must be
224followed by the function name and the parenthesized list of formal parameters.
225The statements that form the body of the function start at the next line, and
226must be indented. The first statement of the function body can optionally be a
227string literal; this string literal is the function's documentation string, or
228:dfn:`docstring`.
229
230There are tools which use docstrings to automatically produce online or printed
231documentation, or to let the user interactively browse through code; it's good
232practice to include docstrings in code that you write, so try to make a habit of
233it.
234
235The *execution* of a function introduces a new symbol table used for the local
236variables of the function. More precisely, all variable assignments in a
237function store the value in the local symbol table; whereas variable references
Georg Brandl86def6c2008-01-21 20:36:10 +0000238first look in the local symbol table, then in the local symbol tables of
239enclosing functions, then in the global symbol table, and finally in the table
240of built-in names. Thus, global variables cannot be directly assigned a value
241within a function (unless named in a :keyword:`global` statement), although they
242may be referenced.
Georg Brandl116aa622007-08-15 14:28:22 +0000243
244The actual parameters (arguments) to a function call are introduced in the local
245symbol table of the called function when it is called; thus, arguments are
246passed using *call by value* (where the *value* is always an object *reference*,
247not the value of the object). [#]_ When a function calls another function, a new
248local symbol table is created for that call.
249
250A function definition introduces the function name in the current symbol table.
251The value of the function name has a type that is recognized by the interpreter
252as a user-defined function. This value can be assigned to another name which
253can then also be used as a function. This serves as a general renaming
254mechanism::
255
256 >>> fib
257 <function fib at 10042ed0>
258 >>> f = fib
259 >>> f(100)
260 1 1 2 3 5 8 13 21 34 55 89
261
262You might object that ``fib`` is not a function but a procedure. In Python,
263like in C, procedures are just functions that don't return a value. In fact,
264technically speaking, procedures do return a value, albeit a rather boring one.
265This value is called ``None`` (it's a built-in name). Writing the value
266``None`` is normally suppressed by the interpreter if it would be the only value
Georg Brandl78b11872008-01-20 11:22:21 +0000267written. You can see it if you really want to using :func:`print`::
Georg Brandl116aa622007-08-15 14:28:22 +0000268
Georg Brandl9afde1c2007-11-01 20:32:30 +0000269 >>> fib(0)
Guido van Rossum0616b792007-08-31 03:25:11 +0000270 >>> print(fib(0))
Georg Brandl116aa622007-08-15 14:28:22 +0000271 None
272
273It is simple to write a function that returns a list of the numbers of the
274Fibonacci series, instead of printing it::
275
276 >>> def fib2(n): # return Fibonacci series up to n
277 ... """Return a list containing the Fibonacci series up to n."""
278 ... result = []
279 ... a, b = 0, 1
280 ... while b < n:
281 ... result.append(b) # see below
282 ... a, b = b, a+b
283 ... return result
284 ...
285 >>> f100 = fib2(100) # call it
286 >>> f100 # write the result
287 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
288
289This example, as usual, demonstrates some new Python features:
290
291* The :keyword:`return` statement returns with a value from a function.
292 :keyword:`return` without an expression argument returns ``None``. Falling off
293 the end of a procedure also returns ``None``.
294
295* The statement ``result.append(b)`` calls a *method* of the list object
296 ``result``. A method is a function that 'belongs' to an object and is named
297 ``obj.methodname``, where ``obj`` is some object (this may be an expression),
298 and ``methodname`` is the name of a method that is defined by the object's type.
299 Different types define different methods. Methods of different types may have
300 the same name without causing ambiguity. (It is possible to define your own
301 object types and methods, using *classes*, as discussed later in this tutorial.)
302 The method :meth:`append` shown in the example is defined for list objects; it
303 adds a new element at the end of the list. In this example it is equivalent to
304 ``result = result + [b]``, but more efficient.
305
306
307.. _tut-defining:
308
309More on Defining Functions
310==========================
311
312It is also possible to define functions with a variable number of arguments.
313There are three forms, which can be combined.
314
315
316.. _tut-defaultargs:
317
318Default Argument Values
319-----------------------
320
321The most useful form is to specify a default value for one or more arguments.
322This creates a function that can be called with fewer arguments than it is
323defined to allow. For example::
324
Georg Brandl116aa622007-08-15 14:28:22 +0000325 def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
326 while True:
Georg Brandle9af2842007-08-17 05:54:09 +0000327 ok = input(prompt)
Georg Brandl116aa622007-08-15 14:28:22 +0000328 if ok in ('y', 'ye', 'yes'): return True
329 if ok in ('n', 'no', 'nop', 'nope'): return False
330 retries = retries - 1
Collin Winter58721bc2007-09-10 00:39:52 +0000331 if retries < 0:
332 raise IOError('refusenik user')
Guido van Rossum0616b792007-08-31 03:25:11 +0000333 print(complaint)
Georg Brandl116aa622007-08-15 14:28:22 +0000334
335This function can be called either like this: ``ask_ok('Do you really want to
336quit?')`` or like this: ``ask_ok('OK to overwrite the file?', 2)``.
337
338This example also introduces the :keyword:`in` keyword. This tests whether or
339not a sequence contains a certain value.
340
341The default values are evaluated at the point of function definition in the
342*defining* scope, so that ::
343
344 i = 5
345
346 def f(arg=i):
Guido van Rossum0616b792007-08-31 03:25:11 +0000347 print(arg)
Georg Brandl116aa622007-08-15 14:28:22 +0000348
349 i = 6
350 f()
351
352will print ``5``.
353
354**Important warning:** The default value is evaluated only once. This makes a
355difference when the default is a mutable object such as a list, dictionary, or
356instances of most classes. For example, the following function accumulates the
357arguments passed to it on subsequent calls::
358
359 def f(a, L=[]):
360 L.append(a)
361 return L
362
Guido van Rossum0616b792007-08-31 03:25:11 +0000363 print(f(1))
364 print(f(2))
365 print(f(3))
Georg Brandl116aa622007-08-15 14:28:22 +0000366
367This will print ::
368
369 [1]
370 [1, 2]
371 [1, 2, 3]
372
373If you don't want the default to be shared between subsequent calls, you can
374write the function like this instead::
375
376 def f(a, L=None):
377 if L is None:
378 L = []
379 L.append(a)
380 return L
381
382
383.. _tut-keywordargs:
384
385Keyword Arguments
386-----------------
387
388Functions can also be called using keyword arguments of the form ``keyword =
389value``. For instance, the following function::
390
391 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000392 print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000393 print("if you put", voltage, "volts through it.")
394 print("-- Lovely plumage, the", type)
395 print("-- It's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000396
397could be called in any of the following ways::
398
399 parrot(1000)
400 parrot(action = 'VOOOOOM', voltage = 1000000)
401 parrot('a thousand', state = 'pushing up the daisies')
402 parrot('a million', 'bereft of life', 'jump')
403
404but the following calls would all be invalid::
405
406 parrot() # required argument missing
407 parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
408 parrot(110, voltage=220) # duplicate value for argument
409 parrot(actor='John Cleese') # unknown keyword
410
411In general, an argument list must have any positional arguments followed by any
412keyword arguments, where the keywords must be chosen from the formal parameter
413names. It's not important whether a formal parameter has a default value or
414not. No argument may receive a value more than once --- formal parameter names
415corresponding to positional arguments cannot be used as keywords in the same
416calls. Here's an example that fails due to this restriction::
417
418 >>> def function(a):
419 ... pass
420 ...
421 >>> function(0, a=0)
422 Traceback (most recent call last):
423 File "<stdin>", line 1, in ?
424 TypeError: function() got multiple values for keyword argument 'a'
425
426When a final formal parameter of the form ``**name`` is present, it receives a
427dictionary (see :ref:`typesmapping`) containing all keyword arguments except for
428those corresponding to a formal parameter. This may be combined with a formal
429parameter of the form ``*name`` (described in the next subsection) which
430receives a tuple containing the positional arguments beyond the formal parameter
431list. (``*name`` must occur before ``**name``.) For example, if we define a
432function like this::
433
434 def cheeseshop(kind, *arguments, **keywords):
Guido van Rossum0616b792007-08-31 03:25:11 +0000435 print("-- Do you have any", kind, '?')
436 print("-- I'm sorry, we're all out of", kind)
Georg Brandl11e18b02008-08-05 09:04:16 +0000437 for arg in arguments: print(arg)
Guido van Rossum0616b792007-08-31 03:25:11 +0000438 print('-'*40)
Neal Norwitze0906d12007-08-31 03:46:28 +0000439 keys = sorted(keywords.keys())
Guido van Rossum0616b792007-08-31 03:25:11 +0000440 for kw in keys: print(kw, ':', keywords[kw])
Georg Brandl116aa622007-08-15 14:28:22 +0000441
442It could be called like this::
443
444 cheeseshop('Limburger', "It's very runny, sir.",
445 "It's really very, VERY runny, sir.",
446 client='John Cleese',
447 shopkeeper='Michael Palin',
448 sketch='Cheese Shop Sketch')
449
450and of course it would print::
451
452 -- Do you have any Limburger ?
453 -- I'm sorry, we're all out of Limburger
454 It's very runny, sir.
455 It's really very, VERY runny, sir.
456 ----------------------------------------
457 client : John Cleese
458 shopkeeper : Michael Palin
459 sketch : Cheese Shop Sketch
460
Georg Brandla6fa2722008-01-06 17:25:36 +0000461Note that the list of keyword argument names is created by sorting the result
462of the keywords dictionary's ``keys()`` method before printing its contents;
463if this is not done, the order in which the arguments are printed is undefined.
Georg Brandl116aa622007-08-15 14:28:22 +0000464
465.. _tut-arbitraryargs:
466
467Arbitrary Argument Lists
468------------------------
469
Christian Heimesdae2a892008-04-19 00:55:37 +0000470.. index::
471 statement: *
472
Georg Brandl116aa622007-08-15 14:28:22 +0000473Finally, the least frequently used option is to specify that a function can be
474called with an arbitrary number of arguments. These arguments will be wrapped
475up in a tuple. Before the variable number of arguments, zero or more normal
476arguments may occur. ::
477
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000478 def write_multiple_items(file, separator, *args):
479 file.write(separator.join(args))
Georg Brandl116aa622007-08-15 14:28:22 +0000480
Guido van Rossum0616b792007-08-31 03:25:11 +0000481
482Normally, these ``variadic`` arguments will be last in the list of formal
483parameters, because they scoop up all remaining input arguments that are
484passed to the function. Any formal parameters which occur after the ``*args``
485parameter are 'keyword-only' arguments, meaning that they can only be used as
Georg Brandle4ac7502007-09-03 07:10:24 +0000486keywords rather than positional arguments. ::
Guido van Rossum0616b792007-08-31 03:25:11 +0000487
488 >>> def concat(*args, sep="/"):
489 ... return sep.join(args)
490 ...
491 >>> concat("earth", "mars", "venus")
492 'earth/mars/venus'
493 >>> concat("earth", "mars", "venus", sep=".")
494 'earth.mars.venus'
Georg Brandl116aa622007-08-15 14:28:22 +0000495
496.. _tut-unpacking-arguments:
497
498Unpacking Argument Lists
499------------------------
500
501The reverse situation occurs when the arguments are already in a list or tuple
502but need to be unpacked for a function call requiring separate positional
503arguments. For instance, the built-in :func:`range` function expects separate
504*start* and *stop* arguments. If they are not available separately, write the
505function call with the ``*``\ -operator to unpack the arguments out of a list
506or tuple::
507
Guido van Rossum0616b792007-08-31 03:25:11 +0000508 >>> list(range(3, 6)) # normal call with separate arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000509 [3, 4, 5]
510 >>> args = [3, 6]
Guido van Rossum0616b792007-08-31 03:25:11 +0000511 >>> list(range(*args)) # call with arguments unpacked from a list
Georg Brandl116aa622007-08-15 14:28:22 +0000512 [3, 4, 5]
513
Christian Heimesdae2a892008-04-19 00:55:37 +0000514.. index::
515 statement: **
516
Georg Brandl116aa622007-08-15 14:28:22 +0000517In the same fashion, dictionaries can deliver keyword arguments with the ``**``\
518-operator::
519
520 >>> def parrot(voltage, state='a stiff', action='voom'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000521 ... print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000522 ... print("if you put", voltage, "volts through it.", end=' ')
523 ... print("E's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000524 ...
525 >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
526 >>> parrot(**d)
527 -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
528
529
530.. _tut-lambda:
531
532Lambda Forms
533------------
534
535By popular demand, a few features commonly found in functional programming
536languages like Lisp have been added to Python. With the :keyword:`lambda`
537keyword, small anonymous functions can be created. Here's a function that
538returns the sum of its two arguments: ``lambda a, b: a+b``. Lambda forms can be
539used wherever function objects are required. They are syntactically restricted
540to a single expression. Semantically, they are just syntactic sugar for a
541normal function definition. Like nested function definitions, lambda forms can
542reference variables from the containing scope::
543
544 >>> def make_incrementor(n):
545 ... return lambda x: x + n
546 ...
547 >>> f = make_incrementor(42)
548 >>> f(0)
549 42
550 >>> f(1)
551 43
552
553
554.. _tut-docstrings:
555
556Documentation Strings
557---------------------
558
559.. index::
560 single: docstrings
561 single: documentation strings
562 single: strings, documentation
563
Guido van Rossum0616b792007-08-31 03:25:11 +0000564Here are some conventions about the content and formatting of documentation
565strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000566
567The first line should always be a short, concise summary of the object's
568purpose. For brevity, it should not explicitly state the object's name or type,
569since these are available by other means (except if the name happens to be a
570verb describing a function's operation). This line should begin with a capital
571letter and end with a period.
572
573If there are more lines in the documentation string, the second line should be
574blank, visually separating the summary from the rest of the description. The
575following lines should be one or more paragraphs describing the object's calling
576conventions, its side effects, etc.
577
578The Python parser does not strip indentation from multi-line string literals in
579Python, so tools that process documentation have to strip indentation if
580desired. This is done using the following convention. The first non-blank line
581*after* the first line of the string determines the amount of indentation for
582the entire documentation string. (We can't use the first line since it is
583generally adjacent to the string's opening quotes so its indentation is not
584apparent in the string literal.) Whitespace "equivalent" to this indentation is
585then stripped from the start of all lines of the string. Lines that are
586indented less should not occur, but if they occur all their leading whitespace
587should be stripped. Equivalence of whitespace should be tested after expansion
588of tabs (to 8 spaces, normally).
589
590Here is an example of a multi-line docstring::
591
592 >>> def my_function():
593 ... """Do nothing, but document it.
594 ...
595 ... No, really, it doesn't do anything.
596 ... """
597 ... pass
598 ...
Guido van Rossum0616b792007-08-31 03:25:11 +0000599 >>> print(my_function.__doc__)
Georg Brandl116aa622007-08-15 14:28:22 +0000600 Do nothing, but document it.
601
602 No, really, it doesn't do anything.
603
604
Christian Heimes043d6f62008-01-07 17:19:16 +0000605.. _tut-codingstyle:
606
607Intermezzo: Coding Style
608========================
609
610.. sectionauthor:: Georg Brandl <georg@python.org>
611.. index:: pair: coding; style
612
613Now that you are about to write longer, more complex pieces of Python, it is a
614good time to talk about *coding style*. Most languages can be written (or more
615concise, *formatted*) in different styles; some are more readable than others.
616Making it easy for others to read your code is always a good idea, and adopting
617a nice coding style helps tremendously for that.
618
Christian Heimesdae2a892008-04-19 00:55:37 +0000619For Python, :pep:`8` has emerged as the style guide that most projects adhere to;
Christian Heimes043d6f62008-01-07 17:19:16 +0000620it promotes a very readable and eye-pleasing coding style. Every Python
621developer should read it at some point; here are the most important points
622extracted for you:
623
624* Use 4-space indentation, and no tabs.
625
626 4 spaces are a good compromise between small indentation (allows greater
627 nesting depth) and large indentation (easier to read). Tabs introduce
628 confusion, and are best left out.
629
630* Wrap lines so that they don't exceed 79 characters.
631
632 This helps users with small displays and makes it possible to have several
633 code files side-by-side on larger displays.
634
635* Use blank lines to separate functions and classes, and larger blocks of
636 code inside functions.
637
638* When possible, put comments on a line of their own.
639
640* Use docstrings.
641
642* Use spaces around operators and after commas, but not directly inside
643 bracketing constructs: ``a = f(1, 2) + g(3, 4)``.
644
645* Name your classes and functions consistently; the convention is to use
646 ``CamelCase`` for classes and ``lower_case_with_underscores`` for functions
647 and methods. Always use ``self`` as the name for the first method argument.
648
649* Don't use fancy encodings if your code is meant to be used in international
650 environments. Plain ASCII works best in any case.
651
Georg Brandl116aa622007-08-15 14:28:22 +0000652
653.. rubric:: Footnotes
654
Christian Heimes043d6f62008-01-07 17:19:16 +0000655.. [#] Actually, *call by object reference* would be a better description,
656 since if a mutable object is passed, the caller will see any changes the
657 callee makes to it (items inserted into a list).
Georg Brandl116aa622007-08-15 14:28:22 +0000658