| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | .. _tut-morecontrol: | 
 | 2 |  | 
 | 3 | *********************** | 
 | 4 | More Control Flow Tools | 
 | 5 | *********************** | 
 | 6 |  | 
 | 7 | Besides the :keyword:`while` statement just introduced, Python knows the usual | 
 | 8 | control flow statements known from other languages, with some twists. | 
 | 9 |  | 
 | 10 |  | 
 | 11 | .. _tut-if: | 
 | 12 |  | 
 | 13 | :keyword:`if` Statements | 
 | 14 | ======================== | 
 | 15 |  | 
 | 16 | Perhaps the most well-known statement type is the :keyword:`if` statement.  For | 
 | 17 | example:: | 
 | 18 |  | 
| Georg Brandl | e9af284 | 2007-08-17 05:54:09 +0000 | [diff] [blame] | 19 |    >>> x = int(input("Please enter an integer: ")) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 20 |    >>> if x < 0: | 
 | 21 |    ...      x = 0 | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 22 |    ...      print('Negative changed to zero') | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 23 |    ... elif x == 0: | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 24 |    ...      print('Zero') | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 25 |    ... elif x == 1: | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 26 |    ...      print('Single') | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 27 |    ... else: | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 28 |    ...      print('More') | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 29 |    ...  | 
 | 30 |  | 
 | 31 | There can be zero or more :keyword:`elif` parts, and the :keyword:`else` part is | 
 | 32 | optional.  The keyword ':keyword:`elif`' is short for 'else if', and is useful | 
 | 33 | to avoid excessive indentation.  An  :keyword:`if` ... :keyword:`elif` ... | 
| Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 34 | :keyword:`elif` ... sequence is a substitute for the ``switch`` or | 
 | 35 | ``case`` statements found in other languages. | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 36 |  | 
 | 37 |  | 
 | 38 | .. _tut-for: | 
 | 39 |  | 
 | 40 | :keyword:`for` Statements | 
 | 41 | ========================= | 
 | 42 |  | 
 | 43 | .. index:: | 
 | 44 |    statement: for | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 45 |  | 
 | 46 | The :keyword:`for` statement in Python differs a bit from what you may be used | 
 | 47 | to in C or Pascal.  Rather than always iterating over an arithmetic progression | 
 | 48 | of numbers (like in Pascal), or giving the user the ability to define both the | 
 | 49 | iteration step and halting condition (as C), Python's :keyword:`for` statement | 
 | 50 | iterates over the items of any sequence (a list or a string), in the order that | 
 | 51 | they appear in the sequence.  For example (no pun intended): | 
 | 52 |  | 
| Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 53 | .. One suggestion was to give a real C example here, but that may only serve to | 
 | 54 |    confuse non-C programmers. | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 55 |  | 
 | 56 | :: | 
 | 57 |  | 
 | 58 |    >>> # Measure some strings: | 
 | 59 |    ... a = ['cat', 'window', 'defenestrate'] | 
 | 60 |    >>> for x in a: | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 61 |    ...     print(x, len(x)) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 62 |    ...  | 
 | 63 |    cat 3 | 
 | 64 |    window 6 | 
 | 65 |    defenestrate 12 | 
 | 66 |  | 
 | 67 | It is not safe to modify the sequence being iterated over in the loop (this can | 
 | 68 | only happen for mutable sequence types, such as lists).  If you need to modify | 
 | 69 | the list you are iterating over (for example, to duplicate selected items) you | 
 | 70 | must iterate over a copy.  The slice notation makes this particularly | 
 | 71 | convenient:: | 
 | 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 |  | 
 | 82 | The :func:`range` Function | 
 | 83 | ========================== | 
 | 84 |  | 
 | 85 | If you do need to iterate over a sequence of numbers, the built-in function | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 86 | :func:`range` comes in handy.  It generates arithmetic progressions:: | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 87 |  | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 88 |  | 
 | 89 |     >>> for i in range(5): | 
 | 90 |     ...     print(i) | 
 | 91 |     ... | 
 | 92 |     0 | 
 | 93 |     1 | 
 | 94 |     2 | 
 | 95 |     3 | 
 | 96 |     4 | 
 | 97 |      | 
 | 98 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 99 |  | 
 | 100 | The given end point is never part of the generated list; ``range(10)`` generates | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 101 | 10 values, the legal indices for items of a sequence of length 10.  It | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 102 | is possible to let the range start at another number, or to specify a different | 
 | 103 | increment (even negative; sometimes this is called the 'step'):: | 
 | 104 |  | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 105 |     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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 113 |  | 
 | 114 | To iterate over the indices of a sequence, combine :func:`range` and :func:`len` | 
 | 115 | as follows:: | 
 | 116 |  | 
 | 117 |    >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] | 
 | 118 |    >>> for i in range(len(a)): | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 119 |    ...     print(i, a[i]) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 120 |    ...  | 
 | 121 |    0 Mary | 
 | 122 |    1 had | 
 | 123 |    2 a | 
 | 124 |    3 little | 
 | 125 |    4 lamb | 
 | 126 |  | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 127 | A strange thing happens if you just print a range:: | 
 | 128 |  | 
 | 129 |    >>> print(range(10)) | 
 | 130 |    range(0, 10) | 
 | 131 |  | 
 | 132 | In many ways the object returned by :func:`range` behaves as if it is a list, | 
 | 133 | but in fact it isn't. It is an object which returns the successive items of  | 
 | 134 | the desired sequence when you iterate over it, but it doesn't really make  | 
 | 135 | the list, thus saving space.  | 
 | 136 |  | 
 | 137 | We say such an object is *iterable*, that is, suitable as a target for  | 
 | 138 | functions and constructs that expect something from which they can  | 
 | 139 | obtain successive items until the supply is exhausted. We have seen that | 
 | 140 | the :keyword:`for` statement is such an *iterator*. The function :func:`list` | 
 | 141 | is another; it creates lists from iterables:: | 
 | 142 |  | 
 | 143 |  | 
 | 144 |    >>> list(range(5)) | 
 | 145 |    [0, 1, 2, 3, 4] | 
 | 146 |  | 
 | 147 | Later we will see more functions that return iterables and take iterables as argument. | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 148 |  | 
 | 149 | .. _tut-break: | 
 | 150 |  | 
 | 151 | :keyword:`break` and :keyword:`continue` Statements, and :keyword:`else` Clauses on Loops | 
 | 152 | ========================================================================================= | 
 | 153 |  | 
 | 154 | The :keyword:`break` statement, like in C, breaks out of the smallest enclosing | 
 | 155 | :keyword:`for` or :keyword:`while` loop. | 
 | 156 |  | 
 | 157 | The :keyword:`continue` statement, also borrowed from C, continues with the next | 
 | 158 | iteration of the loop. | 
 | 159 |  | 
 | 160 | Loop statements may have an ``else`` clause; it is executed when the loop | 
 | 161 | terminates through exhaustion of the list (with :keyword:`for`) or when the | 
 | 162 | condition becomes false (with :keyword:`while`), but not when the loop is | 
 | 163 | terminated by a :keyword:`break` statement.  This is exemplified by the | 
 | 164 | following 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 Brandl | b03c1d9 | 2008-05-01 18:06:50 +0000 | [diff] [blame] | 169 |    ...             print(n, 'equals', x, '*', n//x) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 170 |    ...             break | 
 | 171 |    ...     else: | 
 | 172 |    ...         # loop fell through without finding a factor | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 173 |    ...         print(n, 'is a prime number') | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 174 |    ...  | 
 | 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 |  | 
 | 190 | The :keyword:`pass` statement does nothing. It can be used when a statement is | 
 | 191 | required 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 |  | 
 | 200 | Defining Functions | 
 | 201 | ================== | 
 | 202 |  | 
 | 203 | We can create a function that writes the Fibonacci series to an arbitrary | 
 | 204 | boundary:: | 
 | 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 Brandl | e4ac750 | 2007-09-03 07:10:24 +0000 | [diff] [blame] | 210 |    ...         print(b, end=' ') | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 211 |    ...         a, b = b, a+b | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 212 |    ...     print() | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 213 |    ...  | 
 | 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 |  | 
 | 223 | The keyword :keyword:`def` introduces a function *definition*.  It must be | 
 | 224 | followed by the function name and the parenthesized list of formal parameters. | 
 | 225 | The statements that form the body of the function start at the next line, and | 
 | 226 | must be indented.  The first statement of the function body can optionally be a | 
 | 227 | string literal; this string literal is the function's documentation string, or | 
 | 228 | :dfn:`docstring`. | 
 | 229 |  | 
 | 230 | There are tools which use docstrings to automatically produce online or printed | 
 | 231 | documentation, or to let the user interactively browse through code; it's good | 
 | 232 | practice to include docstrings in code that you write, so try to make a habit of | 
 | 233 | it. | 
 | 234 |  | 
 | 235 | The *execution* of a function introduces a new symbol table used for the local | 
 | 236 | variables of the function.  More precisely, all variable assignments in a | 
 | 237 | function store the value in the local symbol table; whereas variable references | 
| Georg Brandl | 86def6c | 2008-01-21 20:36:10 +0000 | [diff] [blame] | 238 | first look in the local symbol table, then in the local symbol tables of | 
 | 239 | enclosing functions, then in the global symbol table, and finally in the table | 
 | 240 | of built-in names. Thus, global variables cannot be directly assigned a value | 
 | 241 | within a function (unless named in a :keyword:`global` statement), although they | 
 | 242 | may be referenced. | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 243 |  | 
 | 244 | The actual parameters (arguments) to a function call are introduced in the local | 
 | 245 | symbol table of the called function when it is called; thus, arguments are | 
 | 246 | passed using *call by value* (where the *value* is always an object *reference*, | 
 | 247 | not the value of the object). [#]_ When a function calls another function, a new | 
 | 248 | local symbol table is created for that call. | 
 | 249 |  | 
 | 250 | A function definition introduces the function name in the current symbol table. | 
 | 251 | The value of the function name has a type that is recognized by the interpreter | 
 | 252 | as a user-defined function.  This value can be assigned to another name which | 
 | 253 | can then also be used as a function.  This serves as a general renaming | 
 | 254 | mechanism:: | 
 | 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 |  | 
 | 262 | You might object that ``fib`` is not a function but a procedure.  In Python, | 
 | 263 | like in C, procedures are just functions that don't return a value.  In fact, | 
 | 264 | technically speaking, procedures do return a value, albeit a rather boring one. | 
 | 265 | This 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 Brandl | 78b1187 | 2008-01-20 11:22:21 +0000 | [diff] [blame] | 267 | written.  You can see it if you really want to using :func:`print`:: | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 268 |  | 
| Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 269 |    >>> fib(0) | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 270 |    >>> print(fib(0)) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 271 |    None | 
 | 272 |  | 
 | 273 | It is simple to write a function that returns a list of the numbers of the | 
 | 274 | Fibonacci 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 |  | 
 | 289 | This 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 |  | 
 | 309 | More on Defining Functions | 
 | 310 | ========================== | 
 | 311 |  | 
 | 312 | It is also possible to define functions with a variable number of arguments. | 
 | 313 | There are three forms, which can be combined. | 
 | 314 |  | 
 | 315 |  | 
 | 316 | .. _tut-defaultargs: | 
 | 317 |  | 
 | 318 | Default Argument Values | 
 | 319 | ----------------------- | 
 | 320 |  | 
 | 321 | The most useful form is to specify a default value for one or more arguments. | 
 | 322 | This creates a function that can be called with fewer arguments than it is | 
 | 323 | defined to allow.  For example:: | 
 | 324 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 325 |    def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): | 
 | 326 |        while True: | 
| Georg Brandl | e9af284 | 2007-08-17 05:54:09 +0000 | [diff] [blame] | 327 |            ok = input(prompt) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 328 |            if ok in ('y', 'ye', 'yes'): return True | 
 | 329 |            if ok in ('n', 'no', 'nop', 'nope'): return False | 
 | 330 |            retries = retries - 1 | 
| Collin Winter | 58721bc | 2007-09-10 00:39:52 +0000 | [diff] [blame] | 331 |            if retries < 0: | 
 | 332 |                raise IOError('refusenik user') | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 333 |            print(complaint) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 334 |  | 
 | 335 | This function can be called either like this: ``ask_ok('Do you really want to | 
 | 336 | quit?')`` or like this: ``ask_ok('OK to overwrite the file?', 2)``. | 
 | 337 |  | 
 | 338 | This example also introduces the :keyword:`in` keyword. This tests whether or | 
 | 339 | not a sequence contains a certain value. | 
 | 340 |  | 
 | 341 | The 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 Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 347 |        print(arg) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 348 |  | 
 | 349 |    i = 6 | 
 | 350 |    f() | 
 | 351 |  | 
 | 352 | will print ``5``. | 
 | 353 |  | 
 | 354 | **Important warning:**  The default value is evaluated only once. This makes a | 
 | 355 | difference when the default is a mutable object such as a list, dictionary, or | 
 | 356 | instances of most classes.  For example, the following function accumulates the | 
 | 357 | arguments passed to it on subsequent calls:: | 
 | 358 |  | 
 | 359 |    def f(a, L=[]): | 
 | 360 |        L.append(a) | 
 | 361 |        return L | 
 | 362 |  | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 363 |    print(f(1)) | 
 | 364 |    print(f(2)) | 
 | 365 |    print(f(3)) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 366 |  | 
 | 367 | This will print :: | 
 | 368 |  | 
 | 369 |    [1] | 
 | 370 |    [1, 2] | 
 | 371 |    [1, 2, 3] | 
 | 372 |  | 
 | 373 | If you don't want the default to be shared between subsequent calls, you can | 
 | 374 | write 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 |  | 
 | 385 | Keyword Arguments | 
 | 386 | ----------------- | 
 | 387 |  | 
 | 388 | Functions can also be called using keyword arguments of the form ``keyword = | 
 | 389 | value``.  For instance, the following function:: | 
 | 390 |  | 
 | 391 |    def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): | 
| Georg Brandl | e4ac750 | 2007-09-03 07:10:24 +0000 | [diff] [blame] | 392 |        print("-- This parrot wouldn't", action, end=' ') | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 393 |        print("if you put", voltage, "volts through it.") | 
 | 394 |        print("-- Lovely plumage, the", type) | 
 | 395 |        print("-- It's", state, "!") | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 396 |  | 
 | 397 | could 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 |  | 
 | 404 | but 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 |  | 
 | 411 | In general, an argument list must have any positional arguments followed by any | 
 | 412 | keyword arguments, where the keywords must be chosen from the formal parameter | 
 | 413 | names.  It's not important whether a formal parameter has a default value or | 
 | 414 | not.  No argument may receive a value more than once --- formal parameter names | 
 | 415 | corresponding to positional arguments cannot be used as keywords in the same | 
 | 416 | calls. 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 |  | 
 | 426 | When a final formal parameter of the form ``**name`` is present, it receives a | 
 | 427 | dictionary (see :ref:`typesmapping`) containing all keyword arguments except for | 
 | 428 | those corresponding to a formal parameter.  This may be combined with a formal | 
 | 429 | parameter of the form ``*name`` (described in the next subsection) which | 
 | 430 | receives a tuple containing the positional arguments beyond the formal parameter | 
 | 431 | list.  (``*name`` must occur before ``**name``.) For example, if we define a | 
 | 432 | function like this:: | 
 | 433 |  | 
 | 434 |    def cheeseshop(kind, *arguments, **keywords): | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 435 |        print("-- Do you have any", kind, '?') | 
 | 436 |        print("-- I'm sorry, we're all out of", kind) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 437 |        for arg in arguments: print arg | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 438 |        print('-'*40) | 
| Neal Norwitz | e0906d1 | 2007-08-31 03:46:28 +0000 | [diff] [blame] | 439 |        keys = sorted(keywords.keys()) | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 440 |        for kw in keys: print(kw, ':', keywords[kw]) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 441 |  | 
 | 442 | It 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 |  | 
 | 450 | and 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 Brandl | a6fa272 | 2008-01-06 17:25:36 +0000 | [diff] [blame] | 461 | Note that the list of keyword argument names is created by sorting the result | 
 | 462 | of the keywords dictionary's ``keys()`` method before printing its contents; | 
 | 463 | if this is not done, the order in which the arguments are printed is undefined. | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 464 |  | 
 | 465 | .. _tut-arbitraryargs: | 
 | 466 |  | 
 | 467 | Arbitrary Argument Lists | 
 | 468 | ------------------------ | 
 | 469 |  | 
| Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 470 | .. index:: | 
 | 471 |   statement: *   | 
 | 472 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 473 | Finally, the least frequently used option is to specify that a function can be | 
 | 474 | called with an arbitrary number of arguments.  These arguments will be wrapped | 
 | 475 | up in a tuple.  Before the variable number of arguments, zero or more normal | 
 | 476 | arguments may occur. :: | 
 | 477 |  | 
 | 478 |    def fprintf(file, format, *args): | 
 | 479 |        file.write(format % args) | 
 | 480 |  | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 481 |   | 
 | 482 | Normally, these ``variadic`` arguments will be last in the list of formal | 
 | 483 | parameters, because they scoop up all remaining input arguments that are  | 
 | 484 | passed to the function. Any formal parameters which occur after the ``*args`` | 
 | 485 | parameter are 'keyword-only' arguments, meaning that they can only be used as  | 
| Georg Brandl | e4ac750 | 2007-09-03 07:10:24 +0000 | [diff] [blame] | 486 | keywords rather than positional arguments. :: | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 487 |   | 
 | 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 495 |  | 
 | 496 | .. _tut-unpacking-arguments: | 
 | 497 |  | 
 | 498 | Unpacking Argument Lists | 
 | 499 | ------------------------ | 
 | 500 |  | 
 | 501 | The reverse situation occurs when the arguments are already in a list or tuple | 
 | 502 | but need to be unpacked for a function call requiring separate positional | 
 | 503 | arguments.  For instance, the built-in :func:`range` function expects separate | 
 | 504 | *start* and *stop* arguments.  If they are not available separately, write the | 
 | 505 | function call with the  ``*``\ -operator to unpack the arguments out of a list | 
 | 506 | or tuple:: | 
 | 507 |  | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 508 |    >>> list(range(3, 6))            # normal call with separate arguments | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 509 |    [3, 4, 5] | 
 | 510 |    >>> args = [3, 6] | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 511 |    >>> list(range(*args))            # call with arguments unpacked from a list | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 512 |    [3, 4, 5] | 
 | 513 |  | 
| Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 514 | .. index:: | 
 | 515 |   statement: ** | 
 | 516 |  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 517 | In the same fashion, dictionaries can deliver keyword arguments with the ``**``\ | 
 | 518 | -operator:: | 
 | 519 |  | 
 | 520 |    >>> def parrot(voltage, state='a stiff', action='voom'): | 
| Georg Brandl | e4ac750 | 2007-09-03 07:10:24 +0000 | [diff] [blame] | 521 |    ...     print("-- This parrot wouldn't", action, end=' ') | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 522 |    ...     print("if you put", voltage, "volts through it.", end=' ') | 
 | 523 |    ...     print("E's", state, "!") | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 524 |    ... | 
 | 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 |  | 
 | 532 | Lambda Forms | 
 | 533 | ------------ | 
 | 534 |  | 
 | 535 | By popular demand, a few features commonly found in functional programming | 
 | 536 | languages like Lisp have been added to Python.  With the :keyword:`lambda` | 
 | 537 | keyword, small anonymous functions can be created. Here's a function that | 
 | 538 | returns the sum of its two arguments: ``lambda a, b: a+b``.  Lambda forms can be | 
 | 539 | used wherever function objects are required.  They are syntactically restricted | 
 | 540 | to a single expression.  Semantically, they are just syntactic sugar for a | 
 | 541 | normal function definition.  Like nested function definitions, lambda forms can | 
 | 542 | reference 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 |  | 
 | 556 | Documentation Strings | 
 | 557 | --------------------- | 
 | 558 |  | 
 | 559 | .. index:: | 
 | 560 |    single: docstrings | 
 | 561 |    single: documentation strings | 
 | 562 |    single: strings, documentation | 
 | 563 |  | 
| Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 564 | Here are some conventions about the content and formatting of documentation | 
 | 565 | strings.  | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 566 |  | 
 | 567 | The first line should always be a short, concise summary of the object's | 
 | 568 | purpose.  For brevity, it should not explicitly state the object's name or type, | 
 | 569 | since these are available by other means (except if the name happens to be a | 
 | 570 | verb describing a function's operation).  This line should begin with a capital | 
 | 571 | letter and end with a period. | 
 | 572 |  | 
 | 573 | If there are more lines in the documentation string, the second line should be | 
 | 574 | blank, visually separating the summary from the rest of the description.  The | 
 | 575 | following lines should be one or more paragraphs describing the object's calling | 
 | 576 | conventions, its side effects, etc. | 
 | 577 |  | 
 | 578 | The Python parser does not strip indentation from multi-line string literals in | 
 | 579 | Python, so tools that process documentation have to strip indentation if | 
 | 580 | desired.  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 | 
 | 582 | the entire documentation string.  (We can't use the first line since it is | 
 | 583 | generally adjacent to the string's opening quotes so its indentation is not | 
 | 584 | apparent in the string literal.)  Whitespace "equivalent" to this indentation is | 
 | 585 | then stripped from the start of all lines of the string.  Lines that are | 
 | 586 | indented less should not occur, but if they occur all their leading whitespace | 
 | 587 | should be stripped.  Equivalence of whitespace should be tested after expansion | 
 | 588 | of tabs (to 8 spaces, normally). | 
 | 589 |  | 
 | 590 | Here 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 Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 599 |    >>> print(my_function.__doc__) | 
| Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 600 |    Do nothing, but document it. | 
 | 601 |  | 
 | 602 |        No, really, it doesn't do anything. | 
 | 603 |  | 
 | 604 |  | 
| Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 605 | .. _tut-codingstyle: | 
 | 606 |  | 
 | 607 | Intermezzo: Coding Style | 
 | 608 | ======================== | 
 | 609 |  | 
 | 610 | .. sectionauthor:: Georg Brandl <georg@python.org> | 
 | 611 | .. index:: pair: coding; style | 
 | 612 |  | 
 | 613 | Now that you are about to write longer, more complex pieces of Python, it is a | 
 | 614 | good time to talk about *coding style*.  Most languages can be written (or more | 
 | 615 | concise, *formatted*) in different styles; some are more readable than others. | 
 | 616 | Making it easy for others to read your code is always a good idea, and adopting | 
 | 617 | a nice coding style helps tremendously for that. | 
 | 618 |  | 
| Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 619 | For Python, :pep:`8` has emerged as the style guide that most projects adhere to; | 
| Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 620 | it promotes a very readable and eye-pleasing coding style.  Every Python | 
 | 621 | developer should read it at some point; here are the most important points | 
 | 622 | extracted 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 652 |  | 
 | 653 | .. rubric:: Footnotes | 
 | 654 |  | 
| Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 655 | .. [#] 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 Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 658 |  |