Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | .. _tut-morecontrol: |
| 2 | |
| 3 | *********************** |
| 4 | More Control Flow Tools |
| 5 | *********************** |
| 6 | |
Diego Alberto Barriga MartÃnez | b574813 | 2019-09-17 11:57:55 -0500 | [diff] [blame] | 7 | Besides the :keyword:`while` statement just introduced, Python uses the usual |
| 8 | flow control statements known from other languages, with some twists. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 9 | |
| 10 | |
| 11 | .. _tut-if: |
| 12 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 13 | :keyword:`!if` Statements |
| 14 | ========================= |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 34 | optional. The keyword ':keyword:`!elif`' is short for 'else if', and is useful |
| 35 | to avoid excessive indentation. An :keyword:`!if` ... :keyword:`!elif` ... |
| 36 | :keyword:`!elif` ... sequence is a substitute for the ``switch`` or |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 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 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 42 | :keyword:`!for` Statements |
| 43 | ========================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 51 | iteration step and halting condition (as C), Python's :keyword:`!for` statement |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 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 | |
Raymond Hettinger | 6fcb6cf | 2019-08-22 23:44:19 -0700 | [diff] [blame] | 69 | Code that modifies a collection while iterating over that same collection can |
| 70 | be tricky to get right. Instead, it is usually more straight-forward to loop |
| 71 | over a copy of the collection or to create a new collection:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 72 | |
Raymond Hettinger | 6fcb6cf | 2019-08-22 23:44:19 -0700 | [diff] [blame] | 73 | # Strategy: Iterate over a copy |
| 74 | for user, status in users.copy().items(): |
| 75 | if status == 'inactive': |
| 76 | del users[user] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 77 | |
Raymond Hettinger | 6fcb6cf | 2019-08-22 23:44:19 -0700 | [diff] [blame] | 78 | # Strategy: Create a new collection |
| 79 | active_users = {} |
| 80 | for user, status in users.items(): |
| 81 | if status == 'active': |
| 82 | active_users[user] = status |
Georg Brandl | 40383c8 | 2016-02-15 17:50:33 +0100 | [diff] [blame] | 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 | |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 142 | We say such an object is :term:`iterable`, that is, suitable as a target for |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 143 | functions and constructs that expect something from which they can |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 144 | obtain successive items until the supply is exhausted. We have seen that |
Don Kirkby | 3ed4d25 | 2020-02-09 16:57:46 -0800 | [diff] [blame] | 145 | the :keyword:`for` statement is such a construct, while an example of a function |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 146 | that takes an iterable is :func:`sum`:: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 147 | |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 148 | >>> sum(range(4)) # 0 + 1 + 2 + 3 |
| 149 | 6 |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 150 | |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 151 | Later we will see more functions that return iterables and take iterables as |
| 152 | arguments. Lastly, maybe you are curious about how to get a list from a range. |
| 153 | Here is the solution:: |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 154 | |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 155 | >>> list(range(4)) |
| 156 | [0, 1, 2, 3] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 157 | |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 158 | In chapter :ref:`tut-structures`, we will discuss in more detail about |
| 159 | :func:`list`. |
Georg Brandl | af265f4 | 2008-12-07 15:06:20 +0000 | [diff] [blame] | 160 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 161 | .. _tut-break: |
| 162 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 163 | :keyword:`!break` and :keyword:`!continue` Statements, and :keyword:`!else` Clauses on Loops |
| 164 | ============================================================================================ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 165 | |
regexaurus | 36fc896 | 2017-06-27 18:40:41 -0400 | [diff] [blame] | 166 | 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] | 167 | :keyword:`for` or :keyword:`while` loop. |
| 168 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 169 | Loop statements may have an :keyword:`!else` clause; it is executed when the loop |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 170 | terminates through exhaustion of the iterable (with :keyword:`for`) or when the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 171 | condition becomes false (with :keyword:`while`), but not when the loop is |
| 172 | terminated by a :keyword:`break` statement. This is exemplified by the |
| 173 | following loop, which searches for prime numbers:: |
| 174 | |
| 175 | >>> for n in range(2, 10): |
| 176 | ... for x in range(2, n): |
| 177 | ... if n % x == 0: |
Georg Brandl | b03c1d9 | 2008-05-01 18:06:50 +0000 | [diff] [blame] | 178 | ... print(n, 'equals', x, '*', n//x) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 179 | ... break |
| 180 | ... else: |
| 181 | ... # loop fell through without finding a factor |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 182 | ... print(n, 'is a prime number') |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 183 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 184 | 2 is a prime number |
| 185 | 3 is a prime number |
| 186 | 4 equals 2 * 2 |
| 187 | 5 is a prime number |
| 188 | 6 equals 2 * 3 |
| 189 | 7 is a prime number |
| 190 | 8 equals 2 * 4 |
| 191 | 9 equals 3 * 3 |
| 192 | |
Georg Brandl | bdbdfb1 | 2011-08-08 21:45:13 +0200 | [diff] [blame] | 193 | (Yes, this is the correct code. Look closely: the ``else`` clause belongs to |
| 194 | the :keyword:`for` loop, **not** the :keyword:`if` statement.) |
| 195 | |
Nick Coghlan | a3a164a | 2012-06-07 22:41:34 +1000 | [diff] [blame] | 196 | When used with a loop, the ``else`` clause has more in common with the |
Marco Buttu | 218e47b | 2019-06-01 23:11:48 +0200 | [diff] [blame] | 197 | ``else`` clause of a :keyword:`try` statement than it does with that of |
| 198 | :keyword:`if` statements: a :keyword:`try` statement's ``else`` clause runs |
Nick Coghlan | a3a164a | 2012-06-07 22:41:34 +1000 | [diff] [blame] | 199 | when no exception occurs, and a loop's ``else`` clause runs when no ``break`` |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 200 | occurs. For more on the :keyword:`!try` statement and exceptions, see |
Nick Coghlan | a3a164a | 2012-06-07 22:41:34 +1000 | [diff] [blame] | 201 | :ref:`tut-handling`. |
| 202 | |
Senthil Kumaran | 1ef9caa | 2012-08-12 12:01:47 -0700 | [diff] [blame] | 203 | The :keyword:`continue` statement, also borrowed from C, continues with the next |
| 204 | iteration of the loop:: |
| 205 | |
| 206 | >>> for num in range(2, 10): |
Eli Bendersky | 31a1190 | 2012-08-18 09:50:09 +0300 | [diff] [blame] | 207 | ... if num % 2 == 0: |
Senthil Kumaran | 1ef9caa | 2012-08-12 12:01:47 -0700 | [diff] [blame] | 208 | ... print("Found an even number", num) |
| 209 | ... continue |
Miss Islington (bot) | 0cc037f | 2020-09-15 06:56:28 -0700 | [diff] [blame] | 210 | ... print("Found an odd number", num) |
Senthil Kumaran | 1ef9caa | 2012-08-12 12:01:47 -0700 | [diff] [blame] | 211 | Found an even number 2 |
Miss Islington (bot) | 0cc037f | 2020-09-15 06:56:28 -0700 | [diff] [blame] | 212 | Found an odd number 3 |
Senthil Kumaran | 1ef9caa | 2012-08-12 12:01:47 -0700 | [diff] [blame] | 213 | Found an even number 4 |
Miss Islington (bot) | 0cc037f | 2020-09-15 06:56:28 -0700 | [diff] [blame] | 214 | Found an odd number 5 |
Senthil Kumaran | 1ef9caa | 2012-08-12 12:01:47 -0700 | [diff] [blame] | 215 | Found an even number 6 |
Miss Islington (bot) | 0cc037f | 2020-09-15 06:56:28 -0700 | [diff] [blame] | 216 | Found an odd number 7 |
Senthil Kumaran | 1ef9caa | 2012-08-12 12:01:47 -0700 | [diff] [blame] | 217 | Found an even number 8 |
Miss Islington (bot) | 0cc037f | 2020-09-15 06:56:28 -0700 | [diff] [blame] | 218 | Found an odd number 9 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 219 | |
| 220 | .. _tut-pass: |
| 221 | |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 222 | :keyword:`!pass` Statements |
| 223 | =========================== |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 224 | |
| 225 | The :keyword:`pass` statement does nothing. It can be used when a statement is |
| 226 | required syntactically but the program requires no action. For example:: |
| 227 | |
| 228 | >>> while True: |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 229 | ... pass # Busy-wait for keyboard interrupt (Ctrl+C) |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 230 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 231 | |
Benjamin Peterson | 9203501 | 2008-12-27 16:00:54 +0000 | [diff] [blame] | 232 | This is commonly used for creating minimal classes:: |
Georg Brandl | a971c65 | 2008-11-07 09:39:56 +0000 | [diff] [blame] | 233 | |
Benjamin Peterson | 9203501 | 2008-12-27 16:00:54 +0000 | [diff] [blame] | 234 | >>> class MyEmptyClass: |
Georg Brandl | a971c65 | 2008-11-07 09:39:56 +0000 | [diff] [blame] | 235 | ... pass |
Benjamin Peterson | 9203501 | 2008-12-27 16:00:54 +0000 | [diff] [blame] | 236 | ... |
Georg Brandl | a971c65 | 2008-11-07 09:39:56 +0000 | [diff] [blame] | 237 | |
| 238 | 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] | 239 | conditional body when you are working on new code, allowing you to keep thinking |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 240 | at a more abstract level. The :keyword:`!pass` is silently ignored:: |
Georg Brandl | a971c65 | 2008-11-07 09:39:56 +0000 | [diff] [blame] | 241 | |
| 242 | >>> def initlog(*args): |
Benjamin Peterson | 9203501 | 2008-12-27 16:00:54 +0000 | [diff] [blame] | 243 | ... pass # Remember to implement this! |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 244 | ... |
Georg Brandl | a971c65 | 2008-11-07 09:39:56 +0000 | [diff] [blame] | 245 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 246 | .. _tut-functions: |
| 247 | |
| 248 | Defining Functions |
| 249 | ================== |
| 250 | |
| 251 | We can create a function that writes the Fibonacci series to an arbitrary |
| 252 | boundary:: |
| 253 | |
| 254 | >>> def fib(n): # write Fibonacci series up to n |
| 255 | ... """Print a Fibonacci series up to n.""" |
| 256 | ... a, b = 0, 1 |
Mark Dickinson | c099ee2 | 2009-11-23 16:41:41 +0000 | [diff] [blame] | 257 | ... while a < n: |
| 258 | ... print(a, end=' ') |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 259 | ... a, b = b, a+b |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 260 | ... print() |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 261 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 262 | >>> # Now call the function we just defined: |
| 263 | ... fib(2000) |
Mark Dickinson | c099ee2 | 2009-11-23 16:41:41 +0000 | [diff] [blame] | 264 | 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] | 265 | |
| 266 | .. index:: |
| 267 | single: documentation strings |
| 268 | single: docstrings |
| 269 | single: strings, documentation |
| 270 | |
| 271 | The keyword :keyword:`def` introduces a function *definition*. It must be |
| 272 | followed by the function name and the parenthesized list of formal parameters. |
| 273 | 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] | 274 | must be indented. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 275 | |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 276 | The first statement of the function body can optionally be a string literal; |
| 277 | this string literal is the function's documentation string, or :dfn:`docstring`. |
| 278 | (More about docstrings can be found in the section :ref:`tut-docstrings`.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 279 | There are tools which use docstrings to automatically produce online or printed |
| 280 | 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] | 281 | 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] | 282 | |
| 283 | The *execution* of a function introduces a new symbol table used for the local |
| 284 | variables of the function. More precisely, all variable assignments in a |
| 285 | function store the value in the local symbol table; whereas variable references |
Georg Brandl | 86def6c | 2008-01-21 20:36:10 +0000 | [diff] [blame] | 286 | first look in the local symbol table, then in the local symbol tables of |
| 287 | enclosing functions, then in the global symbol table, and finally in the table |
pbhd | e1f95e7 | 2019-05-29 05:38:03 +0200 | [diff] [blame] | 288 | of built-in names. Thus, global variables and variables of enclosing functions |
| 289 | cannot be directly assigned a value within a function (unless, for global |
| 290 | variables, named in a :keyword:`global` statement, or, for variables of enclosing |
| 291 | functions, named in a :keyword:`nonlocal` statement), although they may be |
| 292 | referenced. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 293 | |
| 294 | The actual parameters (arguments) to a function call are introduced in the local |
| 295 | symbol table of the called function when it is called; thus, arguments are |
| 296 | passed using *call by value* (where the *value* is always an object *reference*, |
| 297 | not the value of the object). [#]_ When a function calls another function, a new |
| 298 | local symbol table is created for that call. |
| 299 | |
Miss Islington (bot) | 00c09f0 | 2020-07-05 19:07:32 -0700 | [diff] [blame] | 300 | A function definition associates the function name with the function object in |
| 301 | the current symbol table. The interpreter recognizes the object pointed to by |
| 302 | that name as a user-defined function. Other names can also point to that same |
| 303 | function object and can also be used to access the function:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 304 | |
| 305 | >>> fib |
| 306 | <function fib at 10042ed0> |
| 307 | >>> f = fib |
| 308 | >>> f(100) |
Mark Dickinson | c099ee2 | 2009-11-23 16:41:41 +0000 | [diff] [blame] | 309 | 0 1 1 2 3 5 8 13 21 34 55 89 |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 310 | |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 311 | Coming from other languages, you might object that ``fib`` is not a function but |
| 312 | a procedure since it doesn't return a value. In fact, even functions without a |
| 313 | :keyword:`return` statement do return a value, albeit a rather boring one. This |
| 314 | value is called ``None`` (it's a built-in name). Writing the value ``None`` is |
| 315 | normally suppressed by the interpreter if it would be the only value written. |
| 316 | You can see it if you really want to using :func:`print`:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 317 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 318 | >>> fib(0) |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 319 | >>> print(fib(0)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 320 | None |
| 321 | |
| 322 | It is simple to write a function that returns a list of the numbers of the |
| 323 | Fibonacci series, instead of printing it:: |
| 324 | |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 325 | >>> def fib2(n): # return Fibonacci series up to n |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 326 | ... """Return a list containing the Fibonacci series up to n.""" |
| 327 | ... result = [] |
| 328 | ... a, b = 0, 1 |
Mark Dickinson | c099ee2 | 2009-11-23 16:41:41 +0000 | [diff] [blame] | 329 | ... while a < n: |
| 330 | ... result.append(a) # see below |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 331 | ... a, b = b, a+b |
| 332 | ... return result |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 333 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 334 | >>> f100 = fib2(100) # call it |
| 335 | >>> f100 # write the result |
Mark Dickinson | c099ee2 | 2009-11-23 16:41:41 +0000 | [diff] [blame] | 336 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 337 | |
| 338 | This example, as usual, demonstrates some new Python features: |
| 339 | |
| 340 | * The :keyword:`return` statement returns with a value from a function. |
Serhiy Storchaka | 2b57c43 | 2018-12-19 08:09:46 +0200 | [diff] [blame] | 341 | :keyword:`!return` without an expression argument returns ``None``. Falling off |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 342 | the end of a function also returns ``None``. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 343 | |
Mark Dickinson | c099ee2 | 2009-11-23 16:41:41 +0000 | [diff] [blame] | 344 | * The statement ``result.append(a)`` calls a *method* of the list object |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 345 | ``result``. A method is a function that 'belongs' to an object and is named |
| 346 | ``obj.methodname``, where ``obj`` is some object (this may be an expression), |
| 347 | and ``methodname`` is the name of a method that is defined by the object's type. |
| 348 | Different types define different methods. Methods of different types may have |
| 349 | 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] | 350 | object types and methods, using *classes*, see :ref:`tut-classes`) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 351 | The method :meth:`append` shown in the example is defined for list objects; it |
| 352 | 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] | 353 | ``result = result + [a]``, but more efficient. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 354 | |
| 355 | |
| 356 | .. _tut-defining: |
| 357 | |
| 358 | More on Defining Functions |
| 359 | ========================== |
| 360 | |
| 361 | It is also possible to define functions with a variable number of arguments. |
| 362 | There are three forms, which can be combined. |
| 363 | |
| 364 | |
| 365 | .. _tut-defaultargs: |
| 366 | |
| 367 | Default Argument Values |
| 368 | ----------------------- |
| 369 | |
| 370 | The most useful form is to specify a default value for one or more arguments. |
| 371 | This creates a function that can be called with fewer arguments than it is |
| 372 | defined to allow. For example:: |
| 373 | |
Berker Peksag | 0a5120e | 2016-06-02 11:31:19 -0700 | [diff] [blame] | 374 | def ask_ok(prompt, retries=4, reminder='Please try again!'): |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 375 | while True: |
Georg Brandl | e9af284 | 2007-08-17 05:54:09 +0000 | [diff] [blame] | 376 | ok = input(prompt) |
Georg Brandl | c6c3178 | 2009-06-08 13:41:29 +0000 | [diff] [blame] | 377 | if ok in ('y', 'ye', 'yes'): |
| 378 | return True |
| 379 | if ok in ('n', 'no', 'nop', 'nope'): |
| 380 | return False |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 381 | retries = retries - 1 |
Collin Winter | 58721bc | 2007-09-10 00:39:52 +0000 | [diff] [blame] | 382 | if retries < 0: |
Berker Peksag | 0a5120e | 2016-06-02 11:31:19 -0700 | [diff] [blame] | 383 | raise ValueError('invalid user response') |
| 384 | print(reminder) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 385 | |
Georg Brandl | c6c3178 | 2009-06-08 13:41:29 +0000 | [diff] [blame] | 386 | This function can be called in several ways: |
| 387 | |
| 388 | * giving only the mandatory argument: |
| 389 | ``ask_ok('Do you really want to quit?')`` |
| 390 | * giving one of the optional arguments: |
| 391 | ``ask_ok('OK to overwrite the file?', 2)`` |
| 392 | * or even giving all arguments: |
| 393 | ``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] | 394 | |
| 395 | This example also introduces the :keyword:`in` keyword. This tests whether or |
| 396 | not a sequence contains a certain value. |
| 397 | |
| 398 | The default values are evaluated at the point of function definition in the |
| 399 | *defining* scope, so that :: |
| 400 | |
| 401 | i = 5 |
| 402 | |
| 403 | def f(arg=i): |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 404 | print(arg) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 405 | |
| 406 | i = 6 |
| 407 | f() |
| 408 | |
| 409 | will print ``5``. |
| 410 | |
| 411 | **Important warning:** The default value is evaluated only once. This makes a |
| 412 | difference when the default is a mutable object such as a list, dictionary, or |
| 413 | instances of most classes. For example, the following function accumulates the |
| 414 | arguments passed to it on subsequent calls:: |
| 415 | |
| 416 | def f(a, L=[]): |
| 417 | L.append(a) |
| 418 | return L |
| 419 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 420 | print(f(1)) |
| 421 | print(f(2)) |
| 422 | print(f(3)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 423 | |
| 424 | This will print :: |
| 425 | |
| 426 | [1] |
| 427 | [1, 2] |
| 428 | [1, 2, 3] |
| 429 | |
| 430 | If you don't want the default to be shared between subsequent calls, you can |
| 431 | write the function like this instead:: |
| 432 | |
| 433 | def f(a, L=None): |
| 434 | if L is None: |
| 435 | L = [] |
| 436 | L.append(a) |
| 437 | return L |
| 438 | |
| 439 | |
| 440 | .. _tut-keywordargs: |
| 441 | |
| 442 | Keyword Arguments |
| 443 | ----------------- |
| 444 | |
Ezio Melotti | 7b7e39a | 2011-12-13 15:49:22 +0200 | [diff] [blame] | 445 | Functions can also be called using :term:`keyword arguments <keyword argument>` |
| 446 | of the form ``kwarg=value``. For instance, the following function:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 447 | |
| 448 | def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): |
Georg Brandl | e4ac750 | 2007-09-03 07:10:24 +0000 | [diff] [blame] | 449 | print("-- This parrot wouldn't", action, end=' ') |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 450 | print("if you put", voltage, "volts through it.") |
| 451 | print("-- Lovely plumage, the", type) |
| 452 | print("-- It's", state, "!") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 453 | |
Ezio Melotti | 7b7e39a | 2011-12-13 15:49:22 +0200 | [diff] [blame] | 454 | accepts one required argument (``voltage``) and three optional arguments |
| 455 | (``state``, ``action``, and ``type``). This function can be called in any |
| 456 | of the following ways:: |
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 | parrot(1000) # 1 positional argument |
| 459 | parrot(voltage=1000) # 1 keyword argument |
| 460 | parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments |
| 461 | parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments |
| 462 | parrot('a million', 'bereft of life', 'jump') # 3 positional arguments |
| 463 | parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword |
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 | but all the following calls would be invalid:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 466 | |
| 467 | parrot() # required argument missing |
Ezio Melotti | 7b7e39a | 2011-12-13 15:49:22 +0200 | [diff] [blame] | 468 | parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument |
| 469 | parrot(110, voltage=220) # duplicate value for the same argument |
| 470 | parrot(actor='John Cleese') # unknown keyword argument |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 471 | |
Ezio Melotti | 7b7e39a | 2011-12-13 15:49:22 +0200 | [diff] [blame] | 472 | In a function call, keyword arguments must follow positional arguments. |
| 473 | All the keyword arguments passed must match one of the arguments |
| 474 | accepted by the function (e.g. ``actor`` is not a valid argument for the |
| 475 | ``parrot`` function), and their order is not important. This also includes |
| 476 | non-optional arguments (e.g. ``parrot(voltage=1000)`` is valid too). |
| 477 | No argument may receive a value more than once. |
| 478 | Here's an example that fails due to this restriction:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 479 | |
| 480 | >>> def function(a): |
| 481 | ... pass |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 482 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 483 | >>> function(0, a=0) |
| 484 | Traceback (most recent call last): |
UltimateCoder | 8856940 | 2017-05-03 22:16:45 +0530 | [diff] [blame] | 485 | File "<stdin>", line 1, in <module> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 486 | TypeError: function() got multiple values for keyword argument 'a' |
| 487 | |
| 488 | When a final formal parameter of the form ``**name`` is present, it receives a |
| 489 | dictionary (see :ref:`typesmapping`) containing all keyword arguments except for |
| 490 | those corresponding to a formal parameter. This may be combined with a formal |
| 491 | parameter of the form ``*name`` (described in the next subsection) which |
Julien Palard | 51ddab8 | 2019-05-28 15:10:23 +0200 | [diff] [blame] | 492 | receives a :ref:`tuple <tut-tuples>` containing the positional |
| 493 | arguments beyond the formal parameter list. (``*name`` must occur |
| 494 | before ``**name``.) For example, if we define a function like this:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 495 | |
| 496 | def cheeseshop(kind, *arguments, **keywords): |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 497 | print("-- Do you have any", kind, "?") |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 498 | print("-- I'm sorry, we're all out of", kind) |
Georg Brandl | 70543ac | 2010-10-15 15:32:05 +0000 | [diff] [blame] | 499 | for arg in arguments: |
| 500 | print(arg) |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 501 | print("-" * 40) |
Jim Fasarakis-Hilliard | 32e8f9b | 2017-02-21 08:20:23 +0200 | [diff] [blame] | 502 | for kw in keywords: |
Georg Brandl | 70543ac | 2010-10-15 15:32:05 +0000 | [diff] [blame] | 503 | print(kw, ":", keywords[kw]) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 504 | |
| 505 | It could be called like this:: |
| 506 | |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 507 | cheeseshop("Limburger", "It's very runny, sir.", |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 508 | "It's really very, VERY runny, sir.", |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 509 | shopkeeper="Michael Palin", |
| 510 | client="John Cleese", |
| 511 | sketch="Cheese Shop Sketch") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 512 | |
Martin Panter | 1050d2d | 2016-07-26 11:18:21 +0200 | [diff] [blame] | 513 | and of course it would print: |
| 514 | |
| 515 | .. code-block:: none |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 516 | |
| 517 | -- Do you have any Limburger ? |
| 518 | -- I'm sorry, we're all out of Limburger |
| 519 | It's very runny, sir. |
| 520 | It's really very, VERY runny, sir. |
| 521 | ---------------------------------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 522 | shopkeeper : Michael Palin |
Jim Fasarakis-Hilliard | 32e8f9b | 2017-02-21 08:20:23 +0200 | [diff] [blame] | 523 | client : John Cleese |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 524 | sketch : Cheese Shop Sketch |
| 525 | |
Jim Fasarakis-Hilliard | 32e8f9b | 2017-02-21 08:20:23 +0200 | [diff] [blame] | 526 | Note that the order in which the keyword arguments are printed is guaranteed |
| 527 | to match the order in which they were provided in the function call. |
| 528 | |
Pablo Galindo | b76302d | 2019-05-29 00:45:32 +0100 | [diff] [blame] | 529 | Special parameters |
| 530 | ------------------ |
| 531 | |
| 532 | By default, arguments may be passed to a Python function either by position |
| 533 | or explicitly by keyword. For readability and performance, it makes sense to |
| 534 | restrict the way arguments can be passed so that a developer need only look |
| 535 | at the function definition to determine if items are passed by position, by |
| 536 | position or keyword, or by keyword. |
| 537 | |
| 538 | A function definition may look like: |
| 539 | |
| 540 | .. code-block:: none |
| 541 | |
| 542 | def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2): |
| 543 | ----------- ---------- ---------- |
| 544 | | | | |
| 545 | | Positional or keyword | |
| 546 | | - Keyword only |
| 547 | -- Positional only |
| 548 | |
| 549 | where ``/`` and ``*`` are optional. If used, these symbols indicate the kind of |
| 550 | parameter by how the arguments may be passed to the function: |
| 551 | positional-only, positional-or-keyword, and keyword-only. Keyword parameters |
| 552 | are also referred to as named parameters. |
| 553 | |
| 554 | ------------------------------- |
| 555 | Positional-or-Keyword Arguments |
| 556 | ------------------------------- |
| 557 | |
| 558 | If ``/`` and ``*`` are not present in the function definition, arguments may |
| 559 | be passed to a function by position or by keyword. |
| 560 | |
| 561 | -------------------------- |
| 562 | Positional-Only Parameters |
| 563 | -------------------------- |
| 564 | |
| 565 | Looking at this in a bit more detail, it is possible to mark certain parameters |
| 566 | as *positional-only*. If *positional-only*, the parameters' order matters, and |
| 567 | the parameters cannot be passed by keyword. Positional-only parameters are |
| 568 | placed before a ``/`` (forward-slash). The ``/`` is used to logically |
| 569 | separate the positional-only parameters from the rest of the parameters. |
| 570 | If there is no ``/`` in the function definition, there are no positional-only |
| 571 | parameters. |
| 572 | |
| 573 | Parameters following the ``/`` may be *positional-or-keyword* or *keyword-only*. |
| 574 | |
| 575 | ---------------------- |
| 576 | Keyword-Only Arguments |
| 577 | ---------------------- |
| 578 | |
| 579 | To mark parameters as *keyword-only*, indicating the parameters must be passed |
| 580 | by keyword argument, place an ``*`` in the arguments list just before the first |
| 581 | *keyword-only* parameter. |
| 582 | |
| 583 | ----------------- |
| 584 | Function Examples |
| 585 | ----------------- |
| 586 | |
| 587 | Consider the following example function definitions paying close attention to the |
| 588 | markers ``/`` and ``*``:: |
| 589 | |
| 590 | >>> def standard_arg(arg): |
| 591 | ... print(arg) |
| 592 | ... |
| 593 | >>> def pos_only_arg(arg, /): |
| 594 | ... print(arg) |
| 595 | ... |
| 596 | >>> def kwd_only_arg(*, arg): |
| 597 | ... print(arg) |
| 598 | ... |
| 599 | >>> def combined_example(pos_only, /, standard, *, kwd_only): |
| 600 | ... print(pos_only, standard, kwd_only) |
| 601 | |
| 602 | |
| 603 | The first function definition, ``standard_arg``, the most familiar form, |
| 604 | places no restrictions on the calling convention and arguments may be |
| 605 | passed by position or keyword:: |
| 606 | |
| 607 | >>> standard_arg(2) |
| 608 | 2 |
| 609 | |
| 610 | >>> standard_arg(arg=2) |
| 611 | 2 |
| 612 | |
| 613 | The second function ``pos_only_arg`` is restricted to only use positional |
| 614 | parameters as there is a ``/`` in the function definition:: |
| 615 | |
| 616 | >>> pos_only_arg(1) |
| 617 | 1 |
| 618 | |
| 619 | >>> pos_only_arg(arg=1) |
| 620 | Traceback (most recent call last): |
| 621 | File "<stdin>", line 1, in <module> |
| 622 | TypeError: pos_only_arg() got an unexpected keyword argument 'arg' |
| 623 | |
| 624 | The third function ``kwd_only_args`` only allows keyword arguments as indicated |
| 625 | by a ``*`` in the function definition:: |
| 626 | |
| 627 | >>> kwd_only_arg(3) |
| 628 | Traceback (most recent call last): |
| 629 | File "<stdin>", line 1, in <module> |
| 630 | TypeError: kwd_only_arg() takes 0 positional arguments but 1 was given |
| 631 | |
| 632 | >>> kwd_only_arg(arg=3) |
| 633 | 3 |
| 634 | |
| 635 | And the last uses all three calling conventions in the same function |
| 636 | definition:: |
| 637 | |
| 638 | >>> combined_example(1, 2, 3) |
| 639 | Traceback (most recent call last): |
| 640 | File "<stdin>", line 1, in <module> |
| 641 | TypeError: combined_example() takes 2 positional arguments but 3 were given |
| 642 | |
| 643 | >>> combined_example(1, 2, kwd_only=3) |
| 644 | 1 2 3 |
| 645 | |
| 646 | >>> combined_example(1, standard=2, kwd_only=3) |
| 647 | 1 2 3 |
| 648 | |
| 649 | >>> combined_example(pos_only=1, standard=2, kwd_only=3) |
| 650 | Traceback (most recent call last): |
| 651 | File "<stdin>", line 1, in <module> |
| 652 | TypeError: combined_example() got an unexpected keyword argument 'pos_only' |
| 653 | |
| 654 | |
| 655 | Finally, consider this function definition which has a potential collision between the positional argument ``name`` and ``**kwds`` which has ``name`` as a key:: |
| 656 | |
| 657 | def foo(name, **kwds): |
| 658 | return 'name' in kwds |
| 659 | |
| 660 | There is no possible call that will make it return ``True`` as the keyword ``'name'`` |
Miss Islington (bot) | 72d5ddb | 2020-08-22 02:08:02 -0700 | [diff] [blame] | 661 | will always bind to the first parameter. For example:: |
Pablo Galindo | b76302d | 2019-05-29 00:45:32 +0100 | [diff] [blame] | 662 | |
| 663 | >>> foo(1, **{'name': 2}) |
| 664 | Traceback (most recent call last): |
| 665 | File "<stdin>", line 1, in <module> |
| 666 | TypeError: foo() got multiple values for argument 'name' |
| 667 | >>> |
| 668 | |
| 669 | But using ``/`` (positional only arguments), it is possible since it allows ``name`` as a positional argument and ``'name'`` as a key in the keyword arguments:: |
| 670 | |
| 671 | def foo(name, /, **kwds): |
| 672 | return 'name' in kwds |
| 673 | >>> foo(1, **{'name': 2}) |
| 674 | True |
| 675 | |
| 676 | In other words, the names of positional-only parameters can be used in |
| 677 | ``**kwds`` without ambiguity. |
| 678 | |
| 679 | ----- |
| 680 | Recap |
| 681 | ----- |
| 682 | |
| 683 | The use case will determine which parameters to use in the function definition:: |
| 684 | |
| 685 | def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2): |
| 686 | |
| 687 | As guidance: |
| 688 | |
| 689 | * Use positional-only if you want the name of the parameters to not be |
| 690 | available to the user. This is useful when parameter names have no real |
| 691 | meaning, if you want to enforce the order of the arguments when the function |
| 692 | is called or if you need to take some positional parameters and arbitrary |
| 693 | keywords. |
| 694 | * Use keyword-only when names have meaning and the function definition is |
| 695 | more understandable by being explicit with names or you want to prevent |
| 696 | users relying on the position of the argument being passed. |
Adorilson Bezerra | b7af4e7 | 2019-09-16 04:04:58 -0300 | [diff] [blame] | 697 | * For an API, use positional-only to prevent breaking API changes |
Pablo Galindo | b76302d | 2019-05-29 00:45:32 +0100 | [diff] [blame] | 698 | if the parameter's name is modified in the future. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 699 | |
| 700 | .. _tut-arbitraryargs: |
| 701 | |
| 702 | Arbitrary Argument Lists |
| 703 | ------------------------ |
| 704 | |
Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 705 | .. index:: |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 706 | single: * (asterisk); in function calls |
Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 707 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 708 | Finally, the least frequently used option is to specify that a function can be |
| 709 | called with an arbitrary number of arguments. These arguments will be wrapped |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 710 | up in a tuple (see :ref:`tut-tuples`). Before the variable number of arguments, |
| 711 | zero or more normal arguments may occur. :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 712 | |
Georg Brandl | f08a9dd | 2008-06-10 16:57:31 +0000 | [diff] [blame] | 713 | def write_multiple_items(file, separator, *args): |
| 714 | file.write(separator.join(args)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 715 | |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 716 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 717 | Normally, these ``variadic`` arguments will be last in the list of formal |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 718 | parameters, because they scoop up all remaining input arguments that are |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 719 | passed to the function. Any formal parameters which occur after the ``*args`` |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 720 | 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] | 721 | keywords rather than positional arguments. :: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 722 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 723 | >>> def concat(*args, sep="/"): |
Serhiy Storchaka | dba9039 | 2016-05-10 12:01:23 +0300 | [diff] [blame] | 724 | ... return sep.join(args) |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 725 | ... |
| 726 | >>> concat("earth", "mars", "venus") |
| 727 | 'earth/mars/venus' |
| 728 | >>> concat("earth", "mars", "venus", sep=".") |
| 729 | 'earth.mars.venus' |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 730 | |
| 731 | .. _tut-unpacking-arguments: |
| 732 | |
| 733 | Unpacking Argument Lists |
| 734 | ------------------------ |
| 735 | |
| 736 | The reverse situation occurs when the arguments are already in a list or tuple |
| 737 | but need to be unpacked for a function call requiring separate positional |
| 738 | arguments. For instance, the built-in :func:`range` function expects separate |
| 739 | *start* and *stop* arguments. If they are not available separately, write the |
Raymond Hettinger | fb28fcc | 2019-03-27 21:03:02 -0700 | [diff] [blame] | 740 | function call with the ``*``\ -operator to unpack the arguments out of a list |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 741 | or tuple:: |
| 742 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 743 | >>> list(range(3, 6)) # normal call with separate arguments |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 744 | [3, 4, 5] |
| 745 | >>> args = [3, 6] |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 746 | >>> list(range(*args)) # call with arguments unpacked from a list |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 747 | [3, 4, 5] |
| 748 | |
Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 749 | .. index:: |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 750 | single: **; in function calls |
Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 751 | |
Serhiy Storchaka | 3f819ca | 2018-10-31 02:26:06 +0200 | [diff] [blame] | 752 | In the same fashion, dictionaries can deliver keyword arguments with the |
Raymond Hettinger | fb28fcc | 2019-03-27 21:03:02 -0700 | [diff] [blame] | 753 | ``**``\ -operator:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 754 | |
| 755 | >>> def parrot(voltage, state='a stiff', action='voom'): |
Georg Brandl | e4ac750 | 2007-09-03 07:10:24 +0000 | [diff] [blame] | 756 | ... print("-- This parrot wouldn't", action, end=' ') |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 757 | ... print("if you put", voltage, "volts through it.", end=' ') |
| 758 | ... print("E's", state, "!") |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 759 | ... |
| 760 | >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"} |
| 761 | >>> parrot(**d) |
| 762 | -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised ! |
| 763 | |
| 764 | |
| 765 | .. _tut-lambda: |
| 766 | |
Georg Brandl | de5aff1 | 2013-10-06 10:22:45 +0200 | [diff] [blame] | 767 | Lambda Expressions |
| 768 | ------------------ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 769 | |
Georg Brandl | de5aff1 | 2013-10-06 10:22:45 +0200 | [diff] [blame] | 770 | Small anonymous functions can be created with the :keyword:`lambda` keyword. |
| 771 | 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] | 772 | Lambda functions can be used wherever function objects are required. They are |
Georg Brandl | de5aff1 | 2013-10-06 10:22:45 +0200 | [diff] [blame] | 773 | syntactically restricted to a single expression. Semantically, they are just |
| 774 | syntactic sugar for a normal function definition. Like nested function |
| 775 | definitions, lambda functions can reference variables from the containing |
| 776 | scope:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 777 | |
| 778 | >>> def make_incrementor(n): |
| 779 | ... return lambda x: x + n |
| 780 | ... |
| 781 | >>> f = make_incrementor(42) |
| 782 | >>> f(0) |
| 783 | 42 |
| 784 | >>> f(1) |
| 785 | 43 |
| 786 | |
Georg Brandl | de5aff1 | 2013-10-06 10:22:45 +0200 | [diff] [blame] | 787 | The above example uses a lambda expression to return a function. Another use |
| 788 | is to pass a small function as an argument:: |
| 789 | |
| 790 | >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')] |
| 791 | >>> pairs.sort(key=lambda pair: pair[1]) |
| 792 | >>> pairs |
| 793 | [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')] |
| 794 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 795 | |
| 796 | .. _tut-docstrings: |
| 797 | |
| 798 | Documentation Strings |
| 799 | --------------------- |
| 800 | |
| 801 | .. index:: |
| 802 | single: docstrings |
| 803 | single: documentation strings |
| 804 | single: strings, documentation |
| 805 | |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 806 | Here are some conventions about the content and formatting of documentation |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 807 | strings. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 808 | |
| 809 | The first line should always be a short, concise summary of the object's |
| 810 | purpose. For brevity, it should not explicitly state the object's name or type, |
| 811 | since these are available by other means (except if the name happens to be a |
| 812 | verb describing a function's operation). This line should begin with a capital |
| 813 | letter and end with a period. |
| 814 | |
| 815 | If there are more lines in the documentation string, the second line should be |
| 816 | blank, visually separating the summary from the rest of the description. The |
| 817 | following lines should be one or more paragraphs describing the object's calling |
| 818 | conventions, its side effects, etc. |
| 819 | |
| 820 | The Python parser does not strip indentation from multi-line string literals in |
| 821 | Python, so tools that process documentation have to strip indentation if |
| 822 | desired. This is done using the following convention. The first non-blank line |
| 823 | *after* the first line of the string determines the amount of indentation for |
| 824 | the entire documentation string. (We can't use the first line since it is |
| 825 | generally adjacent to the string's opening quotes so its indentation is not |
| 826 | apparent in the string literal.) Whitespace "equivalent" to this indentation is |
| 827 | then stripped from the start of all lines of the string. Lines that are |
| 828 | indented less should not occur, but if they occur all their leading whitespace |
| 829 | should be stripped. Equivalence of whitespace should be tested after expansion |
| 830 | of tabs (to 8 spaces, normally). |
| 831 | |
| 832 | Here is an example of a multi-line docstring:: |
| 833 | |
| 834 | >>> def my_function(): |
| 835 | ... """Do nothing, but document it. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 836 | ... |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 837 | ... No, really, it doesn't do anything. |
| 838 | ... """ |
| 839 | ... pass |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 840 | ... |
Guido van Rossum | 0616b79 | 2007-08-31 03:25:11 +0000 | [diff] [blame] | 841 | >>> print(my_function.__doc__) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 842 | Do nothing, but document it. |
| 843 | |
| 844 | No, really, it doesn't do anything. |
| 845 | |
| 846 | |
Andrew Svetlov | 1491cbd | 2012-11-01 21:26:55 +0200 | [diff] [blame] | 847 | .. _tut-annotations: |
| 848 | |
| 849 | Function Annotations |
| 850 | -------------------- |
| 851 | |
| 852 | .. sectionauthor:: Zachary Ware <zachary.ware@gmail.com> |
| 853 | .. index:: |
| 854 | pair: function; annotations |
Serhiy Storchaka | ddb961d | 2018-10-26 09:00:49 +0300 | [diff] [blame] | 855 | single: ->; function annotations |
Serhiy Storchaka | 913876d | 2018-10-28 13:41:26 +0200 | [diff] [blame] | 856 | single: : (colon); function annotations |
Andrew Svetlov | 1491cbd | 2012-11-01 21:26:55 +0200 | [diff] [blame] | 857 | |
Zachary Ware | f3b990e | 2015-04-13 11:30:47 -0500 | [diff] [blame] | 858 | :ref:`Function annotations <function>` are completely optional metadata |
Neeraj Badlani | 643ff71 | 2018-04-25 10:52:13 -0700 | [diff] [blame] | 859 | information about the types used by user-defined functions (see :pep:`3107` and |
| 860 | :pep:`484` for more information). |
Andrew Svetlov | 1491cbd | 2012-11-01 21:26:55 +0200 | [diff] [blame] | 861 | |
Cheryl Sabella | b7105c9 | 2018-12-24 00:09:09 -0500 | [diff] [blame] | 862 | :term:`Annotations <function annotation>` are stored in the :attr:`__annotations__` |
| 863 | attribute of the function as a dictionary and have no effect on any other part of the |
| 864 | function. Parameter annotations are defined by a colon after the parameter name, followed |
| 865 | by an expression evaluating to the value of the annotation. Return annotations are |
Andrew Svetlov | 1491cbd | 2012-11-01 21:26:55 +0200 | [diff] [blame] | 866 | defined by a literal ``->``, followed by an expression, between the parameter |
| 867 | list and the colon denoting the end of the :keyword:`def` statement. The |
| 868 | following example has a positional argument, a keyword argument, and the return |
Zachary Ware | f3b990e | 2015-04-13 11:30:47 -0500 | [diff] [blame] | 869 | value annotated:: |
Andrew Svetlov | 1491cbd | 2012-11-01 21:26:55 +0200 | [diff] [blame] | 870 | |
Zachary Ware | f3b990e | 2015-04-13 11:30:47 -0500 | [diff] [blame] | 871 | >>> def f(ham: str, eggs: str = 'eggs') -> str: |
Andrew Svetlov | 1491cbd | 2012-11-01 21:26:55 +0200 | [diff] [blame] | 872 | ... print("Annotations:", f.__annotations__) |
| 873 | ... print("Arguments:", ham, eggs) |
Zachary Ware | f3b990e | 2015-04-13 11:30:47 -0500 | [diff] [blame] | 874 | ... return ham + ' and ' + eggs |
Andrew Svetlov | 1491cbd | 2012-11-01 21:26:55 +0200 | [diff] [blame] | 875 | ... |
Zachary Ware | f3b990e | 2015-04-13 11:30:47 -0500 | [diff] [blame] | 876 | >>> f('spam') |
| 877 | Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>} |
| 878 | Arguments: spam eggs |
| 879 | 'spam and eggs' |
Andrew Svetlov | 1491cbd | 2012-11-01 21:26:55 +0200 | [diff] [blame] | 880 | |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 881 | .. _tut-codingstyle: |
| 882 | |
| 883 | Intermezzo: Coding Style |
| 884 | ======================== |
| 885 | |
| 886 | .. sectionauthor:: Georg Brandl <georg@python.org> |
| 887 | .. index:: pair: coding; style |
| 888 | |
| 889 | Now that you are about to write longer, more complex pieces of Python, it is a |
| 890 | good time to talk about *coding style*. Most languages can be written (or more |
| 891 | concise, *formatted*) in different styles; some are more readable than others. |
| 892 | Making it easy for others to read your code is always a good idea, and adopting |
| 893 | a nice coding style helps tremendously for that. |
| 894 | |
Christian Heimes | dae2a89 | 2008-04-19 00:55:37 +0000 | [diff] [blame] | 895 | 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] | 896 | it promotes a very readable and eye-pleasing coding style. Every Python |
| 897 | developer should read it at some point; here are the most important points |
| 898 | extracted for you: |
| 899 | |
| 900 | * Use 4-space indentation, and no tabs. |
| 901 | |
| 902 | 4 spaces are a good compromise between small indentation (allows greater |
| 903 | nesting depth) and large indentation (easier to read). Tabs introduce |
| 904 | confusion, and are best left out. |
| 905 | |
| 906 | * Wrap lines so that they don't exceed 79 characters. |
| 907 | |
| 908 | This helps users with small displays and makes it possible to have several |
| 909 | code files side-by-side on larger displays. |
| 910 | |
| 911 | * Use blank lines to separate functions and classes, and larger blocks of |
| 912 | code inside functions. |
| 913 | |
| 914 | * When possible, put comments on a line of their own. |
| 915 | |
| 916 | * Use docstrings. |
| 917 | |
| 918 | * Use spaces around operators and after commas, but not directly inside |
| 919 | bracketing constructs: ``a = f(1, 2) + g(3, 4)``. |
| 920 | |
| 921 | * Name your classes and functions consistently; the convention is to use |
Julien Palard | 2da622f | 2019-07-08 23:06:32 +0200 | [diff] [blame] | 922 | ``UpperCamelCase`` for classes and ``lowercase_with_underscores`` for functions |
Georg Brandl | 5d955ed | 2008-09-13 17:18:21 +0000 | [diff] [blame] | 923 | and methods. Always use ``self`` as the name for the first method argument |
| 924 | (see :ref:`tut-firstclasses` for more on classes and methods). |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 925 | |
| 926 | * 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] | 927 | environments. Python's default, UTF-8, or even plain ASCII work best in any |
| 928 | case. |
| 929 | |
| 930 | * Likewise, don't use non-ASCII characters in identifiers if there is only the |
| 931 | slightest chance people speaking a different language will read or maintain |
| 932 | the code. |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 933 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 934 | |
| 935 | .. rubric:: Footnotes |
| 936 | |
Christian Heimes | 043d6f6 | 2008-01-07 17:19:16 +0000 | [diff] [blame] | 937 | .. [#] Actually, *call by object reference* would be a better description, |
| 938 | since if a mutable object is passed, the caller will see any changes the |
| 939 | callee makes to it (items inserted into a list). |