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