rest25/tutorial/controlflow.rst => rest262/tutorial/controlflow.rst
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: "))
n20+   Please enter an integer: 42
20   >>> if x < 0:
21   ...      x = 0
22   ...      print 'Negative changed to zero'
23   ... elif x == 0:
24   ...      print 'Zero'
25   ... elif x == 1:
26   ...      print 'Single'
27   ... else:
28   ...      print 'More'
n29-   ... 
n30+   ...
31+   More
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` ...
n34-:keyword:`elif` ... sequence is a substitute for the :keyword:`switch` or
n36+:keyword:`elif` ... sequence is a substitute for the ``switch`` or
35-:keyword:`case` statements found in other languages.
37+``case`` statements found in other languages.
36- 
37-.. % Weird spacings happen here if the wrapping of the source text
38-.. % gets changed in the wrong way.
39
40
41.. _tut-for:
42
43:keyword:`for` Statements
44=========================
45
46.. index::
49
50The :keyword:`for` statement in Python differs a bit from what you may be used
51to in C or Pascal.  Rather than always iterating over an arithmetic progression
52of numbers (like in Pascal), or giving the user the ability to define both the
53iteration step and halting condition (as C), Python's :keyword:`for` statement
54iterates over the items of any sequence (a list or a string), in the order that
55they appear in the sequence.  For example (no pun intended):
56
n57-.. % One suggestion was to give a real C example here, but that may only
n56+.. One suggestion was to give a real C example here, but that may only serve to
58-.. % serve to confuse non-C programmers.
57+   confuse non-C programmers.
59
60::
61
62   >>> # Measure some strings:
63   ... a = ['cat', 'window', 'defenestrate']
64   >>> for x in a:
65   ...     print x, len(x)
n66-   ... 
n65+   ...
67   cat 3
68   window 6
69   defenestrate 12
70
71It is not safe to modify the sequence being iterated over in the loop (this can
72only happen for mutable sequence types, such as lists).  If you need to modify
73the list you are iterating over (for example, to duplicate selected items) you
74must iterate over a copy.  The slice notation makes this particularly
75convenient::
76
77   >>> for x in a[:]: # make a slice copy of the entire list
78   ...    if len(x) > 6: a.insert(0, x)
n79-   ... 
n78+   ...
80   >>> a
81   ['defenestrate', 'cat', 'window', 'defenestrate']
82
83
84.. _tut-range:
85
86The :func:`range` Function
87==========================
100
101   >>> range(5, 10)
102   [5, 6, 7, 8, 9]
103   >>> range(0, 10, 3)
104   [0, 3, 6, 9]
105   >>> range(-10, -100, -30)
106   [-10, -40, -70]
107
n108-To iterate over the indices of a sequence, combine :func:`range` and :func:`len`
n107+To iterate over the indices of a sequence, you can combine :func:`range` and
109-as follows::
108+:func:`len` as follows::
110
111   >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
112   >>> for i in range(len(a)):
113   ...     print i, a[i]
n114-   ... 
n113+   ...
115   0 Mary
116   1 had
117   2 a
118   3 little
119   4 lamb
n119+ 
120+In most such cases, however, it is convenient to use the :func:`enumerate`
121+function, see :ref:`tut-loopidioms`.
120
121
122.. _tut-break:
123
124:keyword:`break` and :keyword:`continue` Statements, and :keyword:`else` Clauses on Loops
125=========================================================================================
126
127The :keyword:`break` statement, like in C, breaks out of the smallest enclosing
139   >>> for n in range(2, 10):
140   ...     for x in range(2, n):
141   ...         if n % x == 0:
142   ...             print n, 'equals', x, '*', n/x
143   ...             break
144   ...     else:
145   ...         # loop fell through without finding a factor
146   ...         print n, 'is a prime number'
n147-   ... 
n149+   ...
148   2 is a prime number
149   3 is a prime number
150   4 equals 2 * 2
151   5 is a prime number
152   6 equals 2 * 3
153   7 is a prime number
154   8 equals 2 * 4
155   9 equals 3 * 3
159
160:keyword:`pass` Statements
161==========================
162
163The :keyword:`pass` statement does nothing. It can be used when a statement is
164required syntactically but the program requires no action. For example::
165
166   >>> while True:
n167-   ...       pass # Busy-wait for keyboard interrupt
n169+   ...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
168-   ... 
170+   ...
169
n172+This is commonly used for creating minimal classes::
173+ 
174+   >>> class MyEmptyClass:
175+   ...     pass
176+   ...
177+ 
178+Another place :keyword:`pass` can be used is as a place-holder for a function or
179+conditional body when you are working on new code, allowing you to keep thinking
180+at a more abstract level.  The :keyword:`pass` is silently ignored::
181+ 
182+   >>> def initlog(*args):
183+   ...     pass   # Remember to implement this!
184+   ...
170
171.. _tut-functions:
172
173Defining Functions
174==================
175
176We can create a function that writes the Fibonacci series to an arbitrary
177boundary::
178
179   >>> def fib(n):    # write Fibonacci series up to n
180   ...     """Print a Fibonacci series up to n."""
181   ...     a, b = 0, 1
182   ...     while b < n:
183   ...         print b,
184   ...         a, b = b, a+b
n185-   ... 
n200+   ...
186   >>> # Now call the function we just defined:
187   ... fib(2000)
188   1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
189
190.. index::
191   single: documentation strings
192   single: docstrings
193   single: strings, documentation
194
195The keyword :keyword:`def` introduces a function *definition*.  It must be
196followed by the function name and the parenthesized list of formal parameters.
197The statements that form the body of the function start at the next line, and
n213+must be indented.
214+ 
198-must be indented.  The first statement of the function body can optionally be a
215+The first statement of the function body can optionally be a string literal;
199-string literal; this string literal is the function's documentation string, or
216+this string literal is the function's documentation string, or :dfn:`docstring`.
200-:dfn:`docstring`.
217+(More about docstrings can be found in the section :ref:`tut-docstrings`.)
201- 
202There are tools which use docstrings to automatically produce online or printed
203documentation, or to let the user interactively browse through code; it's good
n204-practice to include docstrings in code that you write, so try to make a habit of
n220+practice to include docstrings in code that you write, so make a habit of it.
205-it.
206
207The *execution* of a function introduces a new symbol table used for the local
208variables of the function.  More precisely, all variable assignments in a
209function store the value in the local symbol table; whereas variable references
n210-first look in the local symbol table, then in the global symbol table, and then
n225+first look in the local symbol table, then in the local symbol tables of
226+enclosing functions, then in the global symbol table, and finally in the table
211-in the table of built-in names. Thus,  global variables cannot be directly
227+of built-in names. Thus, global variables cannot be directly assigned a value
212-assigned a value within a function (unless named in a :keyword:`global`
228+within a function (unless named in a :keyword:`global` statement), although they
213-statement), although they may be referenced.
229+may be referenced.
214
215The actual parameters (arguments) to a function call are introduced in the local
216symbol table of the called function when it is called; thus, arguments are
217passed using *call by value* (where the *value* is always an object *reference*,
218not the value of the object). [#]_ When a function calls another function, a new
219local symbol table is created for that call.
220
221A function definition introduces the function name in the current symbol table.
225mechanism::
226
227   >>> fib
228   <function fib at 10042ed0>
229   >>> f = fib
230   >>> f(100)
231   1 1 2 3 5 8 13 21 34 55 89
232
n233-You might object that ``fib`` is not a function but a procedure.  In Python,
n249+Coming from other languages, you might object that ``fib`` is not a function but
234-like in C, procedures are just functions that don't return a value.  In fact,
250+a procedure since it doesn't return a value.  In fact, even functions without a
235-technically speaking, procedures do return a value, albeit a rather boring one.
251+:keyword:`return` statement do return a value, albeit a rather boring one.  This
236-This value is called ``None`` (it's a built-in name).  Writing the value
252+value is called ``None`` (it's a built-in name).  Writing the value ``None`` is
237-``None`` is normally suppressed by the interpreter if it would be the only value
253+normally suppressed by the interpreter if it would be the only value written.
238-written.  You can see it if you really want to::
254+You can see it if you really want to using :keyword:`print`::
239
n256+   >>> fib(0)
240   >>> print fib(0)
241   None
242
243It is simple to write a function that returns a list of the numbers of the
244Fibonacci series, instead of printing it::
245
246   >>> def fib2(n): # return Fibonacci series up to n
247   ...     """Return a list containing the Fibonacci series up to n."""
248   ...     result = []
249   ...     a, b = 0, 1
250   ...     while b < n:
251   ...         result.append(b)    # see below
252   ...         a, b = b, a+b
253   ...     return result
n254-   ... 
n271+   ...
255   >>> f100 = fib2(100)    # call it
256   >>> f100                # write the result
257   [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
258
259This example, as usual, demonstrates some new Python features:
260
261* The :keyword:`return` statement returns with a value from a function.
262  :keyword:`return` without an expression argument returns ``None``. Falling off
n263-  the end of a procedure also returns ``None``.
n280+  the end of a function also returns ``None``.
264
265* The statement ``result.append(b)`` calls a *method* of the list object
266  ``result``.  A method is a function that 'belongs' to an object and is named
267  ``obj.methodname``, where ``obj`` is some object (this may be an expression),
268  and ``methodname`` is the name of a method that is defined by the object's type.
269  Different types define different methods.  Methods of different types may have
270  the same name without causing ambiguity.  (It is possible to define your own
271  object types and methods, using *classes*, as discussed later in this tutorial.)
381keyword arguments, where the keywords must be chosen from the formal parameter
382names.  It's not important whether a formal parameter has a default value or
383not.  No argument may receive a value more than once --- formal parameter names
384corresponding to positional arguments cannot be used as keywords in the same
385calls. Here's an example that fails due to this restriction::
386
387   >>> def function(a):
388   ...     pass
n389-   ... 
n406+   ...
390   >>> function(0, a=0)
391   Traceback (most recent call last):
392     File "<stdin>", line 1, in ?
393   TypeError: function() got multiple values for keyword argument 'a'
394
395When a final formal parameter of the form ``**name`` is present, it receives a
n396-dictionary (XXX reference: ../lib/typesmapping.html) containing all keyword
n413+dictionary (see :ref:`typesmapping`) containing all keyword arguments except for
397-arguments except for those corresponding to a formal parameter.  This may be
414+those corresponding to a formal parameter.  This may be combined with a formal
398-combined with a formal parameter of the form ``*name`` (described in the next
415+parameter of the form ``*name`` (described in the next subsection) which
399-subsection) which receives a tuple containing the positional arguments beyond
416+receives a tuple containing the positional arguments beyond the formal parameter
400-the formal parameter list.  (``*name`` must occur before ``**name``.) For
417+list.  (``*name`` must occur before ``**name``.) For example, if we define a
401-example, if we define a function like this::
418+function like this::
402
403   def cheeseshop(kind, *arguments, **keywords):
n404-       print "-- Do you have any", kind, '?'
n421+       print "-- Do you have any", kind, "?"
405       print "-- I'm sorry, we're all out of", kind
406       for arg in arguments: print arg
n407-       print '-'*40
n424+       print "-* 40
408       keys = keywords.keys()
409       keys.sort()
n410-       for kw in keys: print kw, ':', keywords[kw]
n427+       for kw in keys: print kw, ":", keywords[kw]
411
412It could be called like this::
413
n414-   cheeseshop('Limburger', "It's very runny, sir.",
n431+   cheeseshop("Limburger", "It's very runny, sir.",
415              "It's really very, VERY runny, sir.",
n416-              client='John Cleese',
417              shopkeeper='Michael Palin',
n434+              client="John Cleese",
418-              sketch='Cheese Shop Sketch')
435+              sketch="Cheese Shop Sketch")
419
420and of course it would print::
421
422   -- Do you have any Limburger ?
423   -- I'm sorry, we're all out of Limburger
424   It's very runny, sir.
425   It's really very, VERY runny, sir.
426   ----------------------------------------
433not done, the order in which the arguments are printed is undefined.
434
435
436.. _tut-arbitraryargs:
437
438Arbitrary Argument Lists
439------------------------
440
n458+.. index::
459+  statement: *
460+ 
441Finally, the least frequently used option is to specify that a function can be
442called with an arbitrary number of arguments.  These arguments will be wrapped
n443-up in a tuple.  Before the variable number of arguments, zero or more normal
n463+up in a tuple (see :ref:`tut-tuples`).  Before the variable number of arguments,
444-arguments may occur. ::
464+zero or more normal arguments may occur. ::
445
n446-   def fprintf(file, format, *args):
n466+   def write_multiple_items(file, separator, *args):
447-       file.write(format % args)
467+       file.write(separator.join(args))
448
449
450.. _tut-unpacking-arguments:
451
452Unpacking Argument Lists
453------------------------
454
455The reverse situation occurs when the arguments are already in a list or tuple
459function call with the  ``*``\ -operator to unpack the arguments out of a list
460or tuple::
461
462   >>> range(3, 6)             # normal call with separate arguments
463   [3, 4, 5]
464   >>> args = [3, 6]
465   >>> range(*args)            # call with arguments unpacked from a list
466   [3, 4, 5]
n487+ 
488+.. index::
489+  statement: **
467
468In the same fashion, dictionaries can deliver keyword arguments with the ``**``\
469-operator::
470
471   >>> def parrot(voltage, state='a stiff', action='voom'):
472   ...     print "-- This parrot wouldn't", action,
473   ...     print "if you put", voltage, "volts through it.",
474   ...     print "E's", state, "!"
537indented less should not occur, but if they occur all their leading whitespace
538should be stripped.  Equivalence of whitespace should be tested after expansion
539of tabs (to 8 spaces, normally).
540
541Here is an example of a multi-line docstring::
542
543   >>> def my_function():
544   ...     """Do nothing, but document it.
n545-   ... 
n568+   ...
546   ...     No, really, it doesn't do anything.
547   ...     """
548   ...     pass
n549-   ... 
n572+   ...
550   >>> print my_function.__doc__
551   Do nothing, but document it.
552
553       No, really, it doesn't do anything.
554
555
n579+.. _tut-codingstyle:
580+ 
581+Intermezzo: Coding Style
582+========================
583+ 
584+.. sectionauthor:: Georg Brandl <georg@python.org>
585+.. index:: pair: coding; style
586+ 
587+Now that you are about to write longer, more complex pieces of Python, it is a
588+good time to talk about *coding style*.  Most languages can be written (or more
589+concise, *formatted*) in different styles; some are more readable than others.
590+Making it easy for others to read your code is always a good idea, and adopting
591+a nice coding style helps tremendously for that.
592+ 
593+For Python, :pep:`8` has emerged as the style guide that most projects adhere to;
594+it promotes a very readable and eye-pleasing coding style.  Every Python
595+developer should read it at some point; here are the most important points
596+extracted for you:
597+ 
598+* Use 4-space indentation, and no tabs.
599+ 
600+  4 spaces are a good compromise between small indentation (allows greater
601+  nesting depth) and large indentation (easier to read).  Tabs introduce
602+  confusion, and are best left out.
603+ 
604+* Wrap lines so that they don't exceed 79 characters.
605+ 
606+  This helps users with small displays and makes it possible to have several
607+  code files side-by-side on larger displays.
608+ 
609+* Use blank lines to separate functions and classes, and larger blocks of
610+  code inside functions.
611+ 
612+* When possible, put comments on a line of their own.
613+ 
614+* Use docstrings.
615+ 
616+* Use spaces around operators and after commas, but not directly inside
617+  bracketing constructs: ``a = f(1, 2) + g(3, 4)``.
618+ 
619+* Name your classes and functions consistently; the convention is to use
620+  ``CamelCase`` for classes and ``lower_case_with_underscores`` for functions
621+  and methods.  Always use ``self`` as the name for the first method argument
622+  (see :ref:`tut-firstclasses` for more on classes and methods).
623+ 
624+* Don't use fancy encodings if your code is meant to be used in international
625+  environments.  Plain ASCII works best in any case.
626+ 
556
557.. rubric:: Footnotes
558
t559-.. [#] Actually, *call by object reference* would be a better description, since if a
t630+.. [#] Actually, *call by object reference* would be a better description,
560-   mutable object is passed, the caller will see any changes the callee makes to it
631+   since if a mutable object is passed, the caller will see any changes the
561-   (items inserted into a list).
632+   callee makes to it (items inserted into a list).
562
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op