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