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