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