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