Issue #7042: Use a better mechanism for testing timers in test_signal.
[python.git] / Doc / tutorial / controlflow.rst
blob55462d9cf3fb38adb761b97f90d1886d3e5b88f8
1 .. _tut-morecontrol:
3 ***********************
4 More Control Flow Tools
5 ***********************
7 Besides the :keyword:`while` statement just introduced, Python knows the usual
8 control flow statements known from other languages, with some twists.
11 .. _tut-if:
13 :keyword:`if` Statements
14 ========================
16 Perhaps the most well-known statement type is the :keyword:`if` statement.  For
17 example::
19    >>> x = int(raw_input("Please enter an integer: "))
20    Please enter an integer: 42
21    >>> if x < 0:
22    ...      x = 0
23    ...      print 'Negative changed to zero'
24    ... elif x == 0:
25    ...      print 'Zero'
26    ... elif x == 1:
27    ...      print 'Single'
28    ... else:
29    ...      print 'More'
30    ...
31    More
33 There can be zero or more :keyword:`elif` parts, and the :keyword:`else` part is
34 optional.  The keyword ':keyword:`elif`' is short for 'else if', and is useful
35 to avoid excessive indentation.  An  :keyword:`if` ... :keyword:`elif` ...
36 :keyword:`elif` ... sequence is a substitute for the ``switch`` or
37 ``case`` statements found in other languages.
40 .. _tut-for:
42 :keyword:`for` Statements
43 =========================
45 .. index::
46    statement: for
47    statement: for
49 The :keyword:`for` statement in Python differs a bit from what you may be used
50 to in C or Pascal.  Rather than always iterating over an arithmetic progression
51 of numbers (like in Pascal), or giving the user the ability to define both the
52 iteration step and halting condition (as C), Python's :keyword:`for` statement
53 iterates over the items of any sequence (a list or a string), in the order that
54 they appear in the sequence.  For example (no pun intended):
56 .. One suggestion was to give a real C example here, but that may only serve to
57    confuse non-C programmers.
61    >>> # Measure some strings:
62    ... a = ['cat', 'window', 'defenestrate']
63    >>> for x in a:
64    ...     print x, len(x)
65    ...
66    cat 3
67    window 6
68    defenestrate 12
70 It is not safe to modify the sequence being iterated over in the loop (this can
71 only happen for mutable sequence types, such as lists).  If you need to modify
72 the list you are iterating over (for example, to duplicate selected items) you
73 must iterate over a copy.  The slice notation makes this particularly
74 convenient::
76    >>> for x in a[:]: # make a slice copy of the entire list
77    ...    if len(x) > 6: a.insert(0, x)
78    ...
79    >>> a
80    ['defenestrate', 'cat', 'window', 'defenestrate']
83 .. _tut-range:
85 The :func:`range` Function
86 ==========================
88 If you do need to iterate over a sequence of numbers, the built-in function
89 :func:`range` comes in handy.  It generates lists containing arithmetic
90 progressions::
92    >>> range(10)
93    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
95 The given end point is never part of the generated list; ``range(10)`` generates
96 a list of 10 values, the legal indices for items of a sequence of length 10.  It
97 is possible to let the range start at another number, or to specify a different
98 increment (even negative; sometimes this is called the 'step')::
100    >>> range(5, 10)
101    [5, 6, 7, 8, 9]
102    >>> range(0, 10, 3)
103    [0, 3, 6, 9]
104    >>> range(-10, -100, -30)
105    [-10, -40, -70]
107 To iterate over the indices of a sequence, you can combine :func:`range` and
108 :func:`len` as follows::
110    >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
111    >>> for i in range(len(a)):
112    ...     print i, a[i]
113    ...
114    0 Mary
115    1 had
116    2 a
117    3 little
118    4 lamb
120 In most such cases, however, it is convenient to use the :func:`enumerate`
121 function, see :ref:`tut-loopidioms`.
124 .. _tut-break:
126 :keyword:`break` and :keyword:`continue` Statements, and :keyword:`else` Clauses on Loops
127 =========================================================================================
129 The :keyword:`break` statement, like in C, breaks out of the smallest enclosing
130 :keyword:`for` or :keyword:`while` loop.
132 The :keyword:`continue` statement, also borrowed from C, continues with the next
133 iteration of the loop.
135 Loop statements may have an ``else`` clause; it is executed when the loop
136 terminates through exhaustion of the list (with :keyword:`for`) or when the
137 condition becomes false (with :keyword:`while`), but not when the loop is
138 terminated by a :keyword:`break` statement.  This is exemplified by the
139 following loop, which searches for prime numbers::
141    >>> for n in range(2, 10):
142    ...     for x in range(2, n):
143    ...         if n % x == 0:
144    ...             print n, 'equals', x, '*', n/x
145    ...             break
146    ...     else:
147    ...         # loop fell through without finding a factor
148    ...         print n, 'is a prime number'
149    ...
150    2 is a prime number
151    3 is a prime number
152    4 equals 2 * 2
153    5 is a prime number
154    6 equals 2 * 3
155    7 is a prime number
156    8 equals 2 * 4
157    9 equals 3 * 3
160 .. _tut-pass:
162 :keyword:`pass` Statements
163 ==========================
165 The :keyword:`pass` statement does nothing. It can be used when a statement is
166 required syntactically but the program requires no action. For example::
168    >>> while True:
169    ...     pass  # Busy-wait for keyboard interrupt (Ctrl+C)
170    ...
172 This is commonly used for creating minimal classes::
174    >>> class MyEmptyClass:
175    ...     pass
176    ...
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::
182    >>> def initlog(*args):
183    ...     pass   # Remember to implement this!
184    ...
186 .. _tut-functions:
188 Defining Functions
189 ==================
191 We can create a function that writes the Fibonacci series to an arbitrary
192 boundary::
194    >>> def fib(n):    # write Fibonacci series up to n
195    ...     """Print a Fibonacci series up to n."""
196    ...     a, b = 0, 1
197    ...     while b < n:
198    ...         print b,
199    ...         a, b = b, a+b
200    ...
201    >>> # Now call the function we just defined:
202    ... fib(2000)
203    1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
205 .. index::
206    single: documentation strings
207    single: docstrings
208    single: strings, documentation
210 The keyword :keyword:`def` introduces a function *definition*.  It must be
211 followed by the function name and the parenthesized list of formal parameters.
212 The statements that form the body of the function start at the next line, and
213 must be indented.
215 The first statement of the function body can optionally be a string literal;
216 this string literal is the function's documentation string, or :dfn:`docstring`.
217 (More about docstrings can be found in the section :ref:`tut-docstrings`.)
218 There are tools which use docstrings to automatically produce online or printed
219 documentation, or to let the user interactively browse through code; it's good
220 practice to include docstrings in code that you write, so make a habit of it.
222 The *execution* of a function introduces a new symbol table used for the local
223 variables of the function.  More precisely, all variable assignments in a
224 function store the value in the local symbol table; whereas variable references
225 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
227 of built-in names. Thus, global variables cannot be directly assigned a value
228 within a function (unless named in a :keyword:`global` statement), although they
229 may be referenced.
231 The actual parameters (arguments) to a function call are introduced in the local
232 symbol table of the called function when it is called; thus, arguments are
233 passed using *call by value* (where the *value* is always an object *reference*,
234 not the value of the object). [#]_ When a function calls another function, a new
235 local symbol table is created for that call.
237 A function definition introduces the function name in the current symbol table.
238 The value of the function name has a type that is recognized by the interpreter
239 as a user-defined function.  This value can be assigned to another name which
240 can then also be used as a function.  This serves as a general renaming
241 mechanism::
243    >>> fib
244    <function fib at 10042ed0>
245    >>> f = fib
246    >>> f(100)
247    1 1 2 3 5 8 13 21 34 55 89
249 Coming from other languages, you might object that ``fib`` is not a function but
250 a procedure since it doesn't return a value.  In fact, even functions without a
251 :keyword:`return` statement do return a value, albeit a rather boring one.  This
252 value is called ``None`` (it's a built-in name).  Writing the value ``None`` is
253 normally suppressed by the interpreter if it would be the only value written.
254 You can see it if you really want to using :keyword:`print`::
256    >>> fib(0)
257    >>> print fib(0)
258    None
260 It is simple to write a function that returns a list of the numbers of the
261 Fibonacci series, instead of printing it::
263    >>> def fib2(n): # return Fibonacci series up to n
264    ...     """Return a list containing the Fibonacci series up to n."""
265    ...     result = []
266    ...     a, b = 0, 1
267    ...     while b < n:
268    ...         result.append(b)    # see below
269    ...         a, b = b, a+b
270    ...     return result
271    ...
272    >>> f100 = fib2(100)    # call it
273    >>> f100                # write the result
274    [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
276 This example, as usual, demonstrates some new Python features:
278 * The :keyword:`return` statement returns with a value from a function.
279   :keyword:`return` without an expression argument returns ``None``. Falling off
280   the end of a function also returns ``None``.
282 * The statement ``result.append(b)`` calls a *method* of the list object
283   ``result``.  A method is a function that 'belongs' to an object and is named
284   ``obj.methodname``, where ``obj`` is some object (this may be an expression),
285   and ``methodname`` is the name of a method that is defined by the object's type.
286   Different types define different methods.  Methods of different types may have
287   the same name without causing ambiguity.  (It is possible to define your own
288   object types and methods, using *classes*, see :ref:`tut-classes`)
289   The method :meth:`append` shown in the example is defined for list objects; it
290   adds a new element at the end of the list.  In this example it is equivalent to
291   ``result = result + [b]``, but more efficient.
294 .. _tut-defining:
296 More on Defining Functions
297 ==========================
299 It is also possible to define functions with a variable number of arguments.
300 There are three forms, which can be combined.
303 .. _tut-defaultargs:
305 Default Argument Values
306 -----------------------
308 The most useful form is to specify a default value for one or more arguments.
309 This creates a function that can be called with fewer arguments than it is
310 defined to allow.  For example::
312    def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
313        while True:
314            ok = raw_input(prompt)
315            if ok in ('y', 'ye', 'yes'):
316                return True
317            if ok in ('n', 'no', 'nop', 'nope'):
318                return False
319            retries = retries - 1
320            if retries < 0:
321                raise IOError('refusenik user')
322            print complaint
324 This function can be called in several ways:
326 * giving only the mandatory argument:
327   ``ask_ok('Do you really want to quit?')``
328 * giving one of the optional arguments:
329   ``ask_ok('OK to overwrite the file?', 2)``
330 * or even giving all arguments:
331   ``ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')``
333 This example also introduces the :keyword:`in` keyword. This tests whether or
334 not a sequence contains a certain value.
336 The default values are evaluated at the point of function definition in the
337 *defining* scope, so that ::
339    i = 5
341    def f(arg=i):
342        print arg
344    i = 6
345    f()
347 will print ``5``.
349 **Important warning:**  The default value is evaluated only once. This makes a
350 difference when the default is a mutable object such as a list, dictionary, or
351 instances of most classes.  For example, the following function accumulates the
352 arguments passed to it on subsequent calls::
354    def f(a, L=[]):
355        L.append(a)
356        return L
358    print f(1)
359    print f(2)
360    print f(3)
362 This will print ::
364    [1]
365    [1, 2]
366    [1, 2, 3]
368 If you don't want the default to be shared between subsequent calls, you can
369 write the function like this instead::
371    def f(a, L=None):
372        if L is None:
373            L = []
374        L.append(a)
375        return L
378 .. _tut-keywordargs:
380 Keyword Arguments
381 -----------------
383 Functions can also be called using keyword arguments of the form ``keyword =
384 value``.  For instance, the following function::
386    def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
387        print "-- This parrot wouldn't", action,
388        print "if you put", voltage, "volts through it."
389        print "-- Lovely plumage, the", type
390        print "-- It's", state, "!"
392 could be called in any of the following ways::
394    parrot(1000)
395    parrot(action = 'VOOOOOM', voltage = 1000000)
396    parrot('a thousand', state = 'pushing up the daisies')
397    parrot('a million', 'bereft of life', 'jump')
399 but the following calls would all be invalid::
401    parrot()                     # required argument missing
402    parrot(voltage=5.0, 'dead')  # non-keyword argument following keyword
403    parrot(110, voltage=220)     # duplicate value for argument
404    parrot(actor='John Cleese')  # unknown keyword
406 In general, an argument list must have any positional arguments followed by any
407 keyword arguments, where the keywords must be chosen from the formal parameter
408 names.  It's not important whether a formal parameter has a default value or
409 not.  No argument may receive a value more than once --- formal parameter names
410 corresponding to positional arguments cannot be used as keywords in the same
411 calls. Here's an example that fails due to this restriction::
413    >>> def function(a):
414    ...     pass
415    ...
416    >>> function(0, a=0)
417    Traceback (most recent call last):
418      File "<stdin>", line 1, in ?
419    TypeError: function() got multiple values for keyword argument 'a'
421 When a final formal parameter of the form ``**name`` is present, it receives a
422 dictionary (see :ref:`typesmapping`) containing all keyword arguments except for
423 those corresponding to a formal parameter.  This may be combined with a formal
424 parameter of the form ``*name`` (described in the next subsection) which
425 receives a tuple containing the positional arguments beyond the formal parameter
426 list.  (``*name`` must occur before ``**name``.) For example, if we define a
427 function like this::
429    def cheeseshop(kind, *arguments, **keywords):
430        print "-- Do you have any", kind, "?"
431        print "-- I'm sorry, we're all out of", kind
432        for arg in arguments: print arg
433        print "-" * 40
434        keys = keywords.keys()
435        keys.sort()
436        for kw in keys: print kw, ":", keywords[kw]
438 It could be called like this::
440    cheeseshop("Limburger", "It's very runny, sir.",
441               "It's really very, VERY runny, sir.",
442               shopkeeper='Michael Palin',
443               client="John Cleese",
444               sketch="Cheese Shop Sketch")
446 and of course it would print::
448    -- Do you have any Limburger ?
449    -- I'm sorry, we're all out of Limburger
450    It's very runny, sir.
451    It's really very, VERY runny, sir.
452    ----------------------------------------
453    client : John Cleese
454    shopkeeper : Michael Palin
455    sketch : Cheese Shop Sketch
457 Note that the :meth:`sort` method of the list of keyword argument names is
458 called before printing the contents of the ``keywords`` dictionary; if this is
459 not done, the order in which the arguments are printed is undefined.
462 .. _tut-arbitraryargs:
464 Arbitrary Argument Lists
465 ------------------------
467 .. index::
468   statement: *
470 Finally, the least frequently used option is to specify that a function can be
471 called with an arbitrary number of arguments.  These arguments will be wrapped
472 up in a tuple (see :ref:`tut-tuples`).  Before the variable number of arguments,
473 zero or more normal arguments may occur. ::
475    def write_multiple_items(file, separator, *args):
476        file.write(separator.join(args))
479 .. _tut-unpacking-arguments:
481 Unpacking Argument Lists
482 ------------------------
484 The reverse situation occurs when the arguments are already in a list or tuple
485 but need to be unpacked for a function call requiring separate positional
486 arguments.  For instance, the built-in :func:`range` function expects separate
487 *start* and *stop* arguments.  If they are not available separately, write the
488 function call with the  ``*``\ -operator to unpack the arguments out of a list
489 or tuple::
491    >>> range(3, 6)             # normal call with separate arguments
492    [3, 4, 5]
493    >>> args = [3, 6]
494    >>> range(*args)            # call with arguments unpacked from a list
495    [3, 4, 5]
497 .. index::
498   statement: **
500 In the same fashion, dictionaries can deliver keyword arguments with the ``**``\
501 -operator::
503    >>> def parrot(voltage, state='a stiff', action='voom'):
504    ...     print "-- This parrot wouldn't", action,
505    ...     print "if you put", voltage, "volts through it.",
506    ...     print "E's", state, "!"
507    ...
508    >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
509    >>> parrot(**d)
510    -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
513 .. _tut-lambda:
515 Lambda Forms
516 ------------
518 By popular demand, a few features commonly found in functional programming
519 languages like Lisp have been added to Python.  With the :keyword:`lambda`
520 keyword, small anonymous functions can be created. Here's a function that
521 returns the sum of its two arguments: ``lambda a, b: a+b``.  Lambda forms can be
522 used wherever function objects are required.  They are syntactically restricted
523 to a single expression.  Semantically, they are just syntactic sugar for a
524 normal function definition.  Like nested function definitions, lambda forms can
525 reference variables from the containing scope::
527    >>> def make_incrementor(n):
528    ...     return lambda x: x + n
529    ...
530    >>> f = make_incrementor(42)
531    >>> f(0)
532    42
533    >>> f(1)
534    43
537 .. _tut-docstrings:
539 Documentation Strings
540 ---------------------
542 .. index::
543    single: docstrings
544    single: documentation strings
545    single: strings, documentation
547 There are emerging conventions about the content and formatting of documentation
548 strings.
550 The first line should always be a short, concise summary of the object's
551 purpose.  For brevity, it should not explicitly state the object's name or type,
552 since these are available by other means (except if the name happens to be a
553 verb describing a function's operation).  This line should begin with a capital
554 letter and end with a period.
556 If there are more lines in the documentation string, the second line should be
557 blank, visually separating the summary from the rest of the description.  The
558 following lines should be one or more paragraphs describing the object's calling
559 conventions, its side effects, etc.
561 The Python parser does not strip indentation from multi-line string literals in
562 Python, so tools that process documentation have to strip indentation if
563 desired.  This is done using the following convention. The first non-blank line
564 *after* the first line of the string determines the amount of indentation for
565 the entire documentation string.  (We can't use the first line since it is
566 generally adjacent to the string's opening quotes so its indentation is not
567 apparent in the string literal.)  Whitespace "equivalent" to this indentation is
568 then stripped from the start of all lines of the string.  Lines that are
569 indented less should not occur, but if they occur all their leading whitespace
570 should be stripped.  Equivalence of whitespace should be tested after expansion
571 of tabs (to 8 spaces, normally).
573 Here is an example of a multi-line docstring::
575    >>> def my_function():
576    ...     """Do nothing, but document it.
577    ...
578    ...     No, really, it doesn't do anything.
579    ...     """
580    ...     pass
581    ...
582    >>> print my_function.__doc__
583    Do nothing, but document it.
585        No, really, it doesn't do anything.
588 .. _tut-codingstyle:
590 Intermezzo: Coding Style
591 ========================
593 .. sectionauthor:: Georg Brandl <georg@python.org>
594 .. index:: pair: coding; style
596 Now that you are about to write longer, more complex pieces of Python, it is a
597 good time to talk about *coding style*.  Most languages can be written (or more
598 concise, *formatted*) in different styles; some are more readable than others.
599 Making it easy for others to read your code is always a good idea, and adopting
600 a nice coding style helps tremendously for that.
602 For Python, :pep:`8` has emerged as the style guide that most projects adhere to;
603 it promotes a very readable and eye-pleasing coding style.  Every Python
604 developer should read it at some point; here are the most important points
605 extracted for you:
607 * Use 4-space indentation, and no tabs.
609   4 spaces are a good compromise between small indentation (allows greater
610   nesting depth) and large indentation (easier to read).  Tabs introduce
611   confusion, and are best left out.
613 * Wrap lines so that they don't exceed 79 characters.
615   This helps users with small displays and makes it possible to have several
616   code files side-by-side on larger displays.
618 * Use blank lines to separate functions and classes, and larger blocks of
619   code inside functions.
621 * When possible, put comments on a line of their own.
623 * Use docstrings.
625 * Use spaces around operators and after commas, but not directly inside
626   bracketing constructs: ``a = f(1, 2) + g(3, 4)``.
628 * Name your classes and functions consistently; the convention is to use
629   ``CamelCase`` for classes and ``lower_case_with_underscores`` for functions
630   and methods.  Always use ``self`` as the name for the first method argument
631   (see :ref:`tut-firstclasses` for more on classes and methods).
633 * Don't use fancy encodings if your code is meant to be used in international
634   environments.  Plain ASCII works best in any case.
637 .. rubric:: Footnotes
639 .. [#] Actually, *call by object reference* would be a better description,
640    since if a mutable object is passed, the caller will see any changes the
641    callee makes to it (items inserted into a list).