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