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.
13 :keyword:`if` Statements
14 ========================
16 Perhaps the most well-known statement type is the :keyword:`if` statement. For
19 >>> x = int(raw_input("Please enter an integer: "))
20 Please enter an integer: 42
23 ... print 'Negative changed to zero'
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.
42 :keyword:`for` Statements
43 =========================
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']
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
76 >>> for x in a[:]: # make a slice copy of the entire list
77 ... if len(x) > 6: a.insert(0, x)
80 ['defenestrate', 'cat', 'window', 'defenestrate']
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
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')::
104 >>> range(-10, -100, -30)
107 To iterate over the indices of a sequence, combine :func:`range` and :func:`len`
110 >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
111 >>> for i in range(len(a)):
123 :keyword:`break` and :keyword:`continue` Statements, and :keyword:`else` Clauses on Loops
124 =========================================================================================
126 The :keyword:`break` statement, like in C, breaks out of the smallest enclosing
127 :keyword:`for` or :keyword:`while` loop.
129 The :keyword:`continue` statement, also borrowed from C, continues with the next
130 iteration of the loop.
132 Loop statements may have an ``else`` clause; it is executed when the loop
133 terminates through exhaustion of the list (with :keyword:`for`) or when the
134 condition becomes false (with :keyword:`while`), but not when the loop is
135 terminated by a :keyword:`break` statement. This is exemplified by the
136 following loop, which searches for prime numbers::
138 >>> for n in range(2, 10):
139 ... for x in range(2, n):
141 ... print n, 'equals', x, '*', n/x
144 ... # loop fell through without finding a factor
145 ... print n, 'is a prime number'
159 :keyword:`pass` Statements
160 ==========================
162 The :keyword:`pass` statement does nothing. It can be used when a statement is
163 required syntactically but the program requires no action. For example::
166 ... pass # Busy-wait for keyboard interrupt (Ctrl+C)
175 We can create a function that writes the Fibonacci series to an arbitrary
178 >>> def fib(n): # write Fibonacci series up to n
179 ... """Print a Fibonacci series up to n."""
185 >>> # Now call the function we just defined:
187 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
190 single: documentation strings
192 single: strings, documentation
194 The keyword :keyword:`def` introduces a function *definition*. It must be
195 followed by the function name and the parenthesized list of formal parameters.
196 The statements that form the body of the function start at the next line, and
199 The first statement of the function body can optionally be a string literal;
200 this string literal is the function's documentation string, or :dfn:`docstring`.
201 (More about docstrings can be found in the section :ref:`tut-docstrings`.)
202 There are tools which use docstrings to automatically produce online or printed
203 documentation, or to let the user interactively browse through code; it's good
204 practice to include docstrings in code that you write, so make a habit of it.
206 The *execution* of a function introduces a new symbol table used for the local
207 variables of the function. More precisely, all variable assignments in a
208 function store the value in the local symbol table; whereas variable references
209 first look in the local symbol table, then in the local symbol tables of
210 enclosing functions, then in the global symbol table, and finally in the table
211 of built-in names. Thus, global variables cannot be directly assigned a value
212 within a function (unless named in a :keyword:`global` statement), although they
215 The actual parameters (arguments) to a function call are introduced in the local
216 symbol table of the called function when it is called; thus, arguments are
217 passed using *call by value* (where the *value* is always an object *reference*,
218 not the value of the object). [#]_ When a function calls another function, a new
219 local symbol table is created for that call.
221 A function definition introduces the function name in the current symbol table.
222 The value of the function name has a type that is recognized by the interpreter
223 as a user-defined function. This value can be assigned to another name which
224 can then also be used as a function. This serves as a general renaming
228 <function fib at 10042ed0>
231 1 1 2 3 5 8 13 21 34 55 89
233 Coming from other languages, you might object that ``fib`` is not a function but
234 a procedure since it doesn't return a value. In fact, even functions without a
235 :keyword:`return` statement do return a value, albeit a rather boring one. This
236 value is called ``None`` (it's a built-in name). Writing the value ``None`` is
237 normally suppressed by the interpreter if it would be the only value written.
238 You can see it if you really want to using :keyword:`print`::
244 It is simple to write a function that returns a list of the numbers of the
245 Fibonacci series, instead of printing it::
247 >>> def fib2(n): # return Fibonacci series up to n
248 ... """Return a list containing the Fibonacci series up to n."""
252 ... result.append(b) # see below
256 >>> f100 = fib2(100) # call it
257 >>> f100 # write the result
258 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
260 This example, as usual, demonstrates some new Python features:
262 * The :keyword:`return` statement returns with a value from a function.
263 :keyword:`return` without an expression argument returns ``None``. Falling off
264 the end of a function also returns ``None``.
266 * The statement ``result.append(b)`` calls a *method* of the list object
267 ``result``. A method is a function that 'belongs' to an object and is named
268 ``obj.methodname``, where ``obj`` is some object (this may be an expression),
269 and ``methodname`` is the name of a method that is defined by the object's type.
270 Different types define different methods. Methods of different types may have
271 the same name without causing ambiguity. (It is possible to define your own
272 object types and methods, using *classes*, as discussed later in this tutorial.)
273 The method :meth:`append` shown in the example is defined for list objects; it
274 adds a new element at the end of the list. In this example it is equivalent to
275 ``result = result + [b]``, but more efficient.
280 More on Defining Functions
281 ==========================
283 It is also possible to define functions with a variable number of arguments.
284 There are three forms, which can be combined.
289 Default Argument Values
290 -----------------------
292 The most useful form is to specify a default value for one or more arguments.
293 This creates a function that can be called with fewer arguments than it is
294 defined to allow. For example::
296 def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
298 ok = raw_input(prompt)
299 if ok in ('y', 'ye', 'yes'): return True
300 if ok in ('n', 'no', 'nop', 'nope'): return False
301 retries = retries - 1
302 if retries < 0: raise IOError, 'refusenik user'
305 This function can be called either like this: ``ask_ok('Do you really want to
306 quit?')`` or like this: ``ask_ok('OK to overwrite the file?', 2)``.
308 This example also introduces the :keyword:`in` keyword. This tests whether or
309 not a sequence contains a certain value.
311 The default values are evaluated at the point of function definition in the
312 *defining* scope, so that ::
324 **Important warning:** The default value is evaluated only once. This makes a
325 difference when the default is a mutable object such as a list, dictionary, or
326 instances of most classes. For example, the following function accumulates the
327 arguments passed to it on subsequent calls::
343 If you don't want the default to be shared between subsequent calls, you can
344 write the function like this instead::
358 Functions can also be called using keyword arguments of the form ``keyword =
359 value``. For instance, the following function::
361 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
362 print "-- This parrot wouldn't", action,
363 print "if you put", voltage, "volts through it."
364 print "-- Lovely plumage, the", type
365 print "-- It's", state, "!"
367 could be called in any of the following ways::
370 parrot(action = 'VOOOOOM', voltage = 1000000)
371 parrot('a thousand', state = 'pushing up the daisies')
372 parrot('a million', 'bereft of life', 'jump')
374 but the following calls would all be invalid::
376 parrot() # required argument missing
377 parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
378 parrot(110, voltage=220) # duplicate value for argument
379 parrot(actor='John Cleese') # unknown keyword
381 In general, an argument list must have any positional arguments followed by any
382 keyword arguments, where the keywords must be chosen from the formal parameter
383 names. It's not important whether a formal parameter has a default value or
384 not. No argument may receive a value more than once --- formal parameter names
385 corresponding to positional arguments cannot be used as keywords in the same
386 calls. Here's an example that fails due to this restriction::
392 Traceback (most recent call last):
393 File "<stdin>", line 1, in ?
394 TypeError: function() got multiple values for keyword argument 'a'
396 When a final formal parameter of the form ``**name`` is present, it receives a
397 dictionary (see :ref:`typesmapping`) containing all keyword arguments except for
398 those corresponding to a formal parameter. This may be combined with a formal
399 parameter of the form ``*name`` (described in the next subsection) which
400 receives a tuple containing the positional arguments beyond the formal parameter
401 list. (``*name`` must occur before ``**name``.) For example, if we define a
404 def cheeseshop(kind, *arguments, **keywords):
405 print "-- Do you have any", kind, "?"
406 print "-- I'm sorry, we're all out of", kind
407 for arg in arguments: print arg
409 keys = keywords.keys()
411 for kw in keys: print kw, ":", keywords[kw]
413 It could be called like this::
415 cheeseshop("Limburger", "It's very runny, sir.",
416 "It's really very, VERY runny, sir.",
417 shopkeeper='Michael Palin',
418 client="John Cleese",
419 sketch="Cheese Shop Sketch")
421 and of course it would print::
423 -- Do you have any Limburger ?
424 -- I'm sorry, we're all out of Limburger
425 It's very runny, sir.
426 It's really very, VERY runny, sir.
427 ----------------------------------------
429 shopkeeper : Michael Palin
430 sketch : Cheese Shop Sketch
432 Note that the :meth:`sort` method of the list of keyword argument names is
433 called before printing the contents of the ``keywords`` dictionary; if this is
434 not done, the order in which the arguments are printed is undefined.
437 .. _tut-arbitraryargs:
439 Arbitrary Argument Lists
440 ------------------------
445 Finally, the least frequently used option is to specify that a function can be
446 called with an arbitrary number of arguments. These arguments will be wrapped
447 up in a tuple (see :ref:`tut-tuples`). Before the variable number of arguments,
448 zero or more normal arguments may occur. ::
450 def write_multiple_items(file, separator, *args):
451 file.write(separator.join(args))
454 .. _tut-unpacking-arguments:
456 Unpacking Argument Lists
457 ------------------------
459 The reverse situation occurs when the arguments are already in a list or tuple
460 but need to be unpacked for a function call requiring separate positional
461 arguments. For instance, the built-in :func:`range` function expects separate
462 *start* and *stop* arguments. If they are not available separately, write the
463 function call with the ``*``\ -operator to unpack the arguments out of a list
466 >>> range(3, 6) # normal call with separate arguments
469 >>> range(*args) # call with arguments unpacked from a list
475 In the same fashion, dictionaries can deliver keyword arguments with the ``**``\
478 >>> def parrot(voltage, state='a stiff', action='voom'):
479 ... print "-- This parrot wouldn't", action,
480 ... print "if you put", voltage, "volts through it.",
481 ... print "E's", state, "!"
483 >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
485 -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
493 By popular demand, a few features commonly found in functional programming
494 languages like Lisp have been added to Python. With the :keyword:`lambda`
495 keyword, small anonymous functions can be created. Here's a function that
496 returns the sum of its two arguments: ``lambda a, b: a+b``. Lambda forms can be
497 used wherever function objects are required. They are syntactically restricted
498 to a single expression. Semantically, they are just syntactic sugar for a
499 normal function definition. Like nested function definitions, lambda forms can
500 reference variables from the containing scope::
502 >>> def make_incrementor(n):
503 ... return lambda x: x + n
505 >>> f = make_incrementor(42)
514 Documentation Strings
515 ---------------------
519 single: documentation strings
520 single: strings, documentation
522 There are emerging conventions about the content and formatting of documentation
525 The first line should always be a short, concise summary of the object's
526 purpose. For brevity, it should not explicitly state the object's name or type,
527 since these are available by other means (except if the name happens to be a
528 verb describing a function's operation). This line should begin with a capital
529 letter and end with a period.
531 If there are more lines in the documentation string, the second line should be
532 blank, visually separating the summary from the rest of the description. The
533 following lines should be one or more paragraphs describing the object's calling
534 conventions, its side effects, etc.
536 The Python parser does not strip indentation from multi-line string literals in
537 Python, so tools that process documentation have to strip indentation if
538 desired. This is done using the following convention. The first non-blank line
539 *after* the first line of the string determines the amount of indentation for
540 the entire documentation string. (We can't use the first line since it is
541 generally adjacent to the string's opening quotes so its indentation is not
542 apparent in the string literal.) Whitespace "equivalent" to this indentation is
543 then stripped from the start of all lines of the string. Lines that are
544 indented less should not occur, but if they occur all their leading whitespace
545 should be stripped. Equivalence of whitespace should be tested after expansion
546 of tabs (to 8 spaces, normally).
548 Here is an example of a multi-line docstring::
550 >>> def my_function():
551 ... """Do nothing, but document it.
553 ... No, really, it doesn't do anything.
557 >>> print my_function.__doc__
558 Do nothing, but document it.
560 No, really, it doesn't do anything.
565 Intermezzo: Coding Style
566 ========================
568 .. sectionauthor:: Georg Brandl <georg@python.org>
569 .. index:: pair: coding; style
571 Now that you are about to write longer, more complex pieces of Python, it is a
572 good time to talk about *coding style*. Most languages can be written (or more
573 concise, *formatted*) in different styles; some are more readable than others.
574 Making it easy for others to read your code is always a good idea, and adopting
575 a nice coding style helps tremendously for that.
577 For Python, :pep:`8` has emerged as the style guide that most projects adhere to;
578 it promotes a very readable and eye-pleasing coding style. Every Python
579 developer should read it at some point; here are the most important points
582 * Use 4-space indentation, and no tabs.
584 4 spaces are a good compromise between small indentation (allows greater
585 nesting depth) and large indentation (easier to read). Tabs introduce
586 confusion, and are best left out.
588 * Wrap lines so that they don't exceed 79 characters.
590 This helps users with small displays and makes it possible to have several
591 code files side-by-side on larger displays.
593 * Use blank lines to separate functions and classes, and larger blocks of
594 code inside functions.
596 * When possible, put comments on a line of their own.
600 * Use spaces around operators and after commas, but not directly inside
601 bracketing constructs: ``a = f(1, 2) + g(3, 4)``.
603 * Name your classes and functions consistently; the convention is to use
604 ``CamelCase`` for classes and ``lower_case_with_underscores`` for functions
605 and methods. Always use ``self`` as the name for the first method argument
606 (see :ref:`tut-firstclasses` for more on classes and methods).
608 * Don't use fancy encodings if your code is meant to be used in international
609 environments. Plain ASCII works best in any case.
612 .. rubric:: Footnotes
614 .. [#] Actually, *call by object reference* would be a better description,
615 since if a mutable object is passed, the caller will see any changes the
616 callee makes to it (items inserted into a list).