blob: 5ed5aea44498e3147f5b8342a46d6f9aac30046c [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +00001.. _tut-morecontrol:
2
3***********************
4More Control Flow Tools
5***********************
6
7Besides the :keyword:`while` statement just introduced, Python knows the usual
8control flow statements known from other languages, with some twists.
9
10
11.. _tut-if:
12
13:keyword:`if` Statements
14========================
15
16Perhaps the most well-known statement type is the :keyword:`if` statement. For
17example::
18
Georg Brandle9af2842007-08-17 05:54:09 +000019 >>> x = int(input("Please enter an integer: "))
Georg Brandl5d955ed2008-09-13 17:18:21 +000020 Please enter an integer: 42
Georg Brandl116aa622007-08-15 14:28:22 +000021 >>> if x < 0:
22 ... x = 0
Guido van Rossum0616b792007-08-31 03:25:11 +000023 ... print('Negative changed to zero')
Georg Brandl116aa622007-08-15 14:28:22 +000024 ... elif x == 0:
Guido van Rossum0616b792007-08-31 03:25:11 +000025 ... print('Zero')
Georg Brandl116aa622007-08-15 14:28:22 +000026 ... elif x == 1:
Guido van Rossum0616b792007-08-31 03:25:11 +000027 ... print('Single')
Georg Brandl116aa622007-08-15 14:28:22 +000028 ... else:
Guido van Rossum0616b792007-08-31 03:25:11 +000029 ... print('More')
Georg Brandl5d955ed2008-09-13 17:18:21 +000030 ...
31 More
Georg Brandl116aa622007-08-15 14:28:22 +000032
33There can be zero or more :keyword:`elif` parts, and the :keyword:`else` part is
34optional. The keyword ':keyword:`elif`' is short for 'else if', and is useful
35to avoid excessive indentation. An :keyword:`if` ... :keyword:`elif` ...
Christian Heimes5b5e81c2007-12-31 16:14:33 +000036:keyword:`elif` ... sequence is a substitute for the ``switch`` or
37``case`` statements found in other languages.
Georg Brandl116aa622007-08-15 14:28:22 +000038
39
40.. _tut-for:
41
42:keyword:`for` Statements
43=========================
44
45.. index::
46 statement: for
Georg Brandl116aa622007-08-15 14:28:22 +000047
48The :keyword:`for` statement in Python differs a bit from what you may be used
49to in C or Pascal. Rather than always iterating over an arithmetic progression
50of numbers (like in Pascal), or giving the user the ability to define both the
51iteration step and halting condition (as C), Python's :keyword:`for` statement
52iterates over the items of any sequence (a list or a string), in the order that
53they appear in the sequence. For example (no pun intended):
54
Christian Heimes5b5e81c2007-12-31 16:14:33 +000055.. One suggestion was to give a real C example here, but that may only serve to
56 confuse non-C programmers.
Georg Brandl116aa622007-08-15 14:28:22 +000057
58::
59
60 >>> # Measure some strings:
61 ... a = ['cat', 'window', 'defenestrate']
62 >>> for x in a:
Guido van Rossum0616b792007-08-31 03:25:11 +000063 ... print(x, len(x))
Georg Brandl48310cd2009-01-03 21:18:54 +000064 ...
Georg Brandl116aa622007-08-15 14:28:22 +000065 cat 3
66 window 6
67 defenestrate 12
68
69It is not safe to modify the sequence being iterated over in the loop (this can
70only happen for mutable sequence types, such as lists). If you need to modify
71the list you are iterating over (for example, to duplicate selected items) you
72must iterate over a copy. The slice notation makes this particularly
73convenient::
74
75 >>> for x in a[:]: # make a slice copy of the entire list
76 ... if len(x) > 6: a.insert(0, x)
Georg Brandl48310cd2009-01-03 21:18:54 +000077 ...
Georg Brandl116aa622007-08-15 14:28:22 +000078 >>> a
79 ['defenestrate', 'cat', 'window', 'defenestrate']
80
81
82.. _tut-range:
83
84The :func:`range` Function
85==========================
86
87If you do need to iterate over a sequence of numbers, the built-in function
Guido van Rossum0616b792007-08-31 03:25:11 +000088:func:`range` comes in handy. It generates arithmetic progressions::
Georg Brandl116aa622007-08-15 14:28:22 +000089
Guido van Rossum0616b792007-08-31 03:25:11 +000090 >>> for i in range(5):
91 ... print(i)
92 ...
93 0
94 1
95 2
96 3
97 4
Georg Brandl48310cd2009-01-03 21:18:54 +000098
Georg Brandl7d821062010-06-27 10:59:19 +000099The given end point is never part of the generated sequence; ``range(10)`` generates
Guido van Rossum0616b792007-08-31 03:25:11 +000010010 values, the legal indices for items of a sequence of length 10. It
Georg Brandl116aa622007-08-15 14:28:22 +0000101is possible to let the range start at another number, or to specify a different
102increment (even negative; sometimes this is called the 'step')::
103
Georg Brandl48310cd2009-01-03 21:18:54 +0000104 range(5, 10)
Guido van Rossum0616b792007-08-31 03:25:11 +0000105 5 through 9
106
Georg Brandl48310cd2009-01-03 21:18:54 +0000107 range(0, 10, 3)
Guido van Rossum0616b792007-08-31 03:25:11 +0000108 0, 3, 6, 9
109
Georg Brandl48310cd2009-01-03 21:18:54 +0000110 range(-10, -100, -30)
Guido van Rossum0616b792007-08-31 03:25:11 +0000111 -10, -40, -70
Georg Brandl116aa622007-08-15 14:28:22 +0000112
Georg Brandlaf265f42008-12-07 15:06:20 +0000113To iterate over the indices of a sequence, you can combine :func:`range` and
114:func:`len` as follows::
Georg Brandl116aa622007-08-15 14:28:22 +0000115
116 >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
117 >>> for i in range(len(a)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000118 ... print(i, a[i])
Georg Brandl48310cd2009-01-03 21:18:54 +0000119 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000120 0 Mary
121 1 had
122 2 a
123 3 little
124 4 lamb
125
Georg Brandlaf265f42008-12-07 15:06:20 +0000126In most such cases, however, it is convenient to use the :func:`enumerate`
127function, see :ref:`tut-loopidioms`.
128
Guido van Rossum0616b792007-08-31 03:25:11 +0000129A strange thing happens if you just print a range::
130
131 >>> print(range(10))
132 range(0, 10)
133
134In many ways the object returned by :func:`range` behaves as if it is a list,
Georg Brandl48310cd2009-01-03 21:18:54 +0000135but in fact it isn't. It is an object which returns the successive items of
136the desired sequence when you iterate over it, but it doesn't really make
137the list, thus saving space.
Guido van Rossum0616b792007-08-31 03:25:11 +0000138
Georg Brandl48310cd2009-01-03 21:18:54 +0000139We say such an object is *iterable*, that is, suitable as a target for
140functions and constructs that expect something from which they can
Guido van Rossum0616b792007-08-31 03:25:11 +0000141obtain successive items until the supply is exhausted. We have seen that
142the :keyword:`for` statement is such an *iterator*. The function :func:`list`
143is another; it creates lists from iterables::
144
145
146 >>> list(range(5))
147 [0, 1, 2, 3, 4]
148
149Later we will see more functions that return iterables and take iterables as argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000150
Georg Brandlaf265f42008-12-07 15:06:20 +0000151
Georg Brandl116aa622007-08-15 14:28:22 +0000152.. _tut-break:
153
154:keyword:`break` and :keyword:`continue` Statements, and :keyword:`else` Clauses on Loops
155=========================================================================================
156
157The :keyword:`break` statement, like in C, breaks out of the smallest enclosing
158:keyword:`for` or :keyword:`while` loop.
159
160The :keyword:`continue` statement, also borrowed from C, continues with the next
161iteration of the loop.
162
163Loop statements may have an ``else`` clause; it is executed when the loop
164terminates through exhaustion of the list (with :keyword:`for`) or when the
165condition becomes false (with :keyword:`while`), but not when the loop is
166terminated by a :keyword:`break` statement. This is exemplified by the
167following loop, which searches for prime numbers::
168
169 >>> for n in range(2, 10):
170 ... for x in range(2, n):
171 ... if n % x == 0:
Georg Brandlb03c1d92008-05-01 18:06:50 +0000172 ... print(n, 'equals', x, '*', n//x)
Georg Brandl116aa622007-08-15 14:28:22 +0000173 ... break
174 ... else:
175 ... # loop fell through without finding a factor
Guido van Rossum0616b792007-08-31 03:25:11 +0000176 ... print(n, 'is a prime number')
Georg Brandl48310cd2009-01-03 21:18:54 +0000177 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000178 2 is a prime number
179 3 is a prime number
180 4 equals 2 * 2
181 5 is a prime number
182 6 equals 2 * 3
183 7 is a prime number
184 8 equals 2 * 4
185 9 equals 3 * 3
186
Georg Brandlbdbdfb12011-08-08 21:45:13 +0200187(Yes, this is the correct code. Look closely: the ``else`` clause belongs to
188the :keyword:`for` loop, **not** the :keyword:`if` statement.)
189
Georg Brandl116aa622007-08-15 14:28:22 +0000190
191.. _tut-pass:
192
193:keyword:`pass` Statements
194==========================
195
196The :keyword:`pass` statement does nothing. It can be used when a statement is
197required syntactically but the program requires no action. For example::
198
199 >>> while True:
Georg Brandl5d955ed2008-09-13 17:18:21 +0000200 ... pass # Busy-wait for keyboard interrupt (Ctrl+C)
Georg Brandl48310cd2009-01-03 21:18:54 +0000201 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000202
Benjamin Peterson92035012008-12-27 16:00:54 +0000203This is commonly used for creating minimal classes::
Georg Brandla971c652008-11-07 09:39:56 +0000204
Benjamin Peterson92035012008-12-27 16:00:54 +0000205 >>> class MyEmptyClass:
Georg Brandla971c652008-11-07 09:39:56 +0000206 ... pass
Benjamin Peterson92035012008-12-27 16:00:54 +0000207 ...
Georg Brandla971c652008-11-07 09:39:56 +0000208
209Another place :keyword:`pass` can be used is as a place-holder for a function or
Benjamin Peterson92035012008-12-27 16:00:54 +0000210conditional body when you are working on new code, allowing you to keep thinking
211at a more abstract level. The :keyword:`pass` is silently ignored::
Georg Brandla971c652008-11-07 09:39:56 +0000212
213 >>> def initlog(*args):
Benjamin Peterson92035012008-12-27 16:00:54 +0000214 ... pass # Remember to implement this!
Georg Brandl48310cd2009-01-03 21:18:54 +0000215 ...
Georg Brandla971c652008-11-07 09:39:56 +0000216
Georg Brandl116aa622007-08-15 14:28:22 +0000217.. _tut-functions:
218
219Defining Functions
220==================
221
222We can create a function that writes the Fibonacci series to an arbitrary
223boundary::
224
225 >>> def fib(n): # write Fibonacci series up to n
226 ... """Print a Fibonacci series up to n."""
227 ... a, b = 0, 1
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000228 ... while a < n:
229 ... print(a, end=' ')
Georg Brandl116aa622007-08-15 14:28:22 +0000230 ... a, b = b, a+b
Guido van Rossum0616b792007-08-31 03:25:11 +0000231 ... print()
Georg Brandl48310cd2009-01-03 21:18:54 +0000232 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000233 >>> # Now call the function we just defined:
234 ... fib(2000)
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000235 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Georg Brandl116aa622007-08-15 14:28:22 +0000236
237.. index::
238 single: documentation strings
239 single: docstrings
240 single: strings, documentation
241
242The keyword :keyword:`def` introduces a function *definition*. It must be
243followed by the function name and the parenthesized list of formal parameters.
244The statements that form the body of the function start at the next line, and
Georg Brandl5d955ed2008-09-13 17:18:21 +0000245must be indented.
Georg Brandl116aa622007-08-15 14:28:22 +0000246
Georg Brandl5d955ed2008-09-13 17:18:21 +0000247The first statement of the function body can optionally be a string literal;
248this string literal is the function's documentation string, or :dfn:`docstring`.
249(More about docstrings can be found in the section :ref:`tut-docstrings`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000250There are tools which use docstrings to automatically produce online or printed
251documentation, or to let the user interactively browse through code; it's good
Georg Brandl5d955ed2008-09-13 17:18:21 +0000252practice to include docstrings in code that you write, so make a habit of it.
Georg Brandl116aa622007-08-15 14:28:22 +0000253
254The *execution* of a function introduces a new symbol table used for the local
255variables of the function. More precisely, all variable assignments in a
256function store the value in the local symbol table; whereas variable references
Georg Brandl86def6c2008-01-21 20:36:10 +0000257first look in the local symbol table, then in the local symbol tables of
258enclosing functions, then in the global symbol table, and finally in the table
259of built-in names. Thus, global variables cannot be directly assigned a value
260within a function (unless named in a :keyword:`global` statement), although they
261may be referenced.
Georg Brandl116aa622007-08-15 14:28:22 +0000262
263The actual parameters (arguments) to a function call are introduced in the local
264symbol table of the called function when it is called; thus, arguments are
265passed using *call by value* (where the *value* is always an object *reference*,
266not the value of the object). [#]_ When a function calls another function, a new
267local symbol table is created for that call.
268
269A function definition introduces the function name in the current symbol table.
270The value of the function name has a type that is recognized by the interpreter
271as a user-defined function. This value can be assigned to another name which
272can then also be used as a function. This serves as a general renaming
273mechanism::
274
275 >>> fib
276 <function fib at 10042ed0>
277 >>> f = fib
278 >>> f(100)
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000279 0 1 1 2 3 5 8 13 21 34 55 89
Georg Brandl116aa622007-08-15 14:28:22 +0000280
Georg Brandl5d955ed2008-09-13 17:18:21 +0000281Coming from other languages, you might object that ``fib`` is not a function but
282a procedure since it doesn't return a value. In fact, even functions without a
283:keyword:`return` statement do return a value, albeit a rather boring one. This
284value is called ``None`` (it's a built-in name). Writing the value ``None`` is
285normally suppressed by the interpreter if it would be the only value written.
286You can see it if you really want to using :func:`print`::
Georg Brandl116aa622007-08-15 14:28:22 +0000287
Georg Brandl9afde1c2007-11-01 20:32:30 +0000288 >>> fib(0)
Guido van Rossum0616b792007-08-31 03:25:11 +0000289 >>> print(fib(0))
Georg Brandl116aa622007-08-15 14:28:22 +0000290 None
291
292It is simple to write a function that returns a list of the numbers of the
293Fibonacci series, instead of printing it::
294
295 >>> def fib2(n): # return Fibonacci series up to n
296 ... """Return a list containing the Fibonacci series up to n."""
297 ... result = []
298 ... a, b = 0, 1
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000299 ... while a < n:
300 ... result.append(a) # see below
Georg Brandl116aa622007-08-15 14:28:22 +0000301 ... a, b = b, a+b
302 ... return result
Georg Brandl48310cd2009-01-03 21:18:54 +0000303 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000304 >>> f100 = fib2(100) # call it
305 >>> f100 # write the result
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000306 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Georg Brandl116aa622007-08-15 14:28:22 +0000307
308This example, as usual, demonstrates some new Python features:
309
310* The :keyword:`return` statement returns with a value from a function.
311 :keyword:`return` without an expression argument returns ``None``. Falling off
Georg Brandl5d955ed2008-09-13 17:18:21 +0000312 the end of a function also returns ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000313
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000314* The statement ``result.append(a)`` calls a *method* of the list object
Georg Brandl116aa622007-08-15 14:28:22 +0000315 ``result``. A method is a function that 'belongs' to an object and is named
316 ``obj.methodname``, where ``obj`` is some object (this may be an expression),
317 and ``methodname`` is the name of a method that is defined by the object's type.
318 Different types define different methods. Methods of different types may have
319 the same name without causing ambiguity. (It is possible to define your own
Georg Brandlc6c31782009-06-08 13:41:29 +0000320 object types and methods, using *classes*, see :ref:`tut-classes`)
Georg Brandl116aa622007-08-15 14:28:22 +0000321 The method :meth:`append` shown in the example is defined for list objects; it
322 adds a new element at the end of the list. In this example it is equivalent to
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000323 ``result = result + [a]``, but more efficient.
Georg Brandl116aa622007-08-15 14:28:22 +0000324
325
326.. _tut-defining:
327
328More on Defining Functions
329==========================
330
331It is also possible to define functions with a variable number of arguments.
332There are three forms, which can be combined.
333
334
335.. _tut-defaultargs:
336
337Default Argument Values
338-----------------------
339
340The most useful form is to specify a default value for one or more arguments.
341This creates a function that can be called with fewer arguments than it is
342defined to allow. For example::
343
Georg Brandl116aa622007-08-15 14:28:22 +0000344 def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
345 while True:
Georg Brandle9af2842007-08-17 05:54:09 +0000346 ok = input(prompt)
Georg Brandlc6c31782009-06-08 13:41:29 +0000347 if ok in ('y', 'ye', 'yes'):
348 return True
349 if ok in ('n', 'no', 'nop', 'nope'):
350 return False
Georg Brandl116aa622007-08-15 14:28:22 +0000351 retries = retries - 1
Collin Winter58721bc2007-09-10 00:39:52 +0000352 if retries < 0:
353 raise IOError('refusenik user')
Guido van Rossum0616b792007-08-31 03:25:11 +0000354 print(complaint)
Georg Brandl116aa622007-08-15 14:28:22 +0000355
Georg Brandlc6c31782009-06-08 13:41:29 +0000356This function can be called in several ways:
357
358* giving only the mandatory argument:
359 ``ask_ok('Do you really want to quit?')``
360* giving one of the optional arguments:
361 ``ask_ok('OK to overwrite the file?', 2)``
362* or even giving all arguments:
363 ``ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')``
Georg Brandl116aa622007-08-15 14:28:22 +0000364
365This example also introduces the :keyword:`in` keyword. This tests whether or
366not a sequence contains a certain value.
367
368The default values are evaluated at the point of function definition in the
369*defining* scope, so that ::
370
371 i = 5
372
373 def f(arg=i):
Guido van Rossum0616b792007-08-31 03:25:11 +0000374 print(arg)
Georg Brandl116aa622007-08-15 14:28:22 +0000375
376 i = 6
377 f()
378
379will print ``5``.
380
381**Important warning:** The default value is evaluated only once. This makes a
382difference when the default is a mutable object such as a list, dictionary, or
383instances of most classes. For example, the following function accumulates the
384arguments passed to it on subsequent calls::
385
386 def f(a, L=[]):
387 L.append(a)
388 return L
389
Guido van Rossum0616b792007-08-31 03:25:11 +0000390 print(f(1))
391 print(f(2))
392 print(f(3))
Georg Brandl116aa622007-08-15 14:28:22 +0000393
394This will print ::
395
396 [1]
397 [1, 2]
398 [1, 2, 3]
399
400If you don't want the default to be shared between subsequent calls, you can
401write the function like this instead::
402
403 def f(a, L=None):
404 if L is None:
405 L = []
406 L.append(a)
407 return L
408
409
410.. _tut-keywordargs:
411
412Keyword Arguments
413-----------------
414
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200415Functions can also be called using :term:`keyword arguments <keyword argument>`
416of the form ``kwarg=value``. For instance, the following function::
Georg Brandl116aa622007-08-15 14:28:22 +0000417
418 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000419 print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000420 print("if you put", voltage, "volts through it.")
421 print("-- Lovely plumage, the", type)
422 print("-- It's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000423
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200424accepts one required argument (``voltage``) and three optional arguments
425(``state``, ``action``, and ``type``). This function can be called in any
426of the following ways::
Georg Brandl116aa622007-08-15 14:28:22 +0000427
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200428 parrot(1000) # 1 positional argument
429 parrot(voltage=1000) # 1 keyword argument
430 parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
431 parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
432 parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
433 parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
Georg Brandl116aa622007-08-15 14:28:22 +0000434
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200435but all the following calls would be invalid::
Georg Brandl116aa622007-08-15 14:28:22 +0000436
437 parrot() # required argument missing
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200438 parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument
439 parrot(110, voltage=220) # duplicate value for the same argument
440 parrot(actor='John Cleese') # unknown keyword argument
Georg Brandl116aa622007-08-15 14:28:22 +0000441
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200442In a function call, keyword arguments must follow positional arguments.
443All the keyword arguments passed must match one of the arguments
444accepted by the function (e.g. ``actor`` is not a valid argument for the
445``parrot`` function), and their order is not important. This also includes
446non-optional arguments (e.g. ``parrot(voltage=1000)`` is valid too).
447No argument may receive a value more than once.
448Here's an example that fails due to this restriction::
Georg Brandl116aa622007-08-15 14:28:22 +0000449
450 >>> def function(a):
451 ... pass
Georg Brandl48310cd2009-01-03 21:18:54 +0000452 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000453 >>> function(0, a=0)
454 Traceback (most recent call last):
455 File "<stdin>", line 1, in ?
456 TypeError: function() got multiple values for keyword argument 'a'
457
458When a final formal parameter of the form ``**name`` is present, it receives a
459dictionary (see :ref:`typesmapping`) containing all keyword arguments except for
460those corresponding to a formal parameter. This may be combined with a formal
461parameter of the form ``*name`` (described in the next subsection) which
462receives a tuple containing the positional arguments beyond the formal parameter
463list. (``*name`` must occur before ``**name``.) For example, if we define a
464function like this::
465
466 def cheeseshop(kind, *arguments, **keywords):
Georg Brandl5d955ed2008-09-13 17:18:21 +0000467 print("-- Do you have any", kind, "?")
Guido van Rossum0616b792007-08-31 03:25:11 +0000468 print("-- I'm sorry, we're all out of", kind)
Georg Brandl70543ac2010-10-15 15:32:05 +0000469 for arg in arguments:
470 print(arg)
Georg Brandl5d955ed2008-09-13 17:18:21 +0000471 print("-" * 40)
Neal Norwitze0906d12007-08-31 03:46:28 +0000472 keys = sorted(keywords.keys())
Georg Brandl70543ac2010-10-15 15:32:05 +0000473 for kw in keys:
474 print(kw, ":", keywords[kw])
Georg Brandl116aa622007-08-15 14:28:22 +0000475
476It could be called like this::
477
Georg Brandl5d955ed2008-09-13 17:18:21 +0000478 cheeseshop("Limburger", "It's very runny, sir.",
Georg Brandl116aa622007-08-15 14:28:22 +0000479 "It's really very, VERY runny, sir.",
Georg Brandl5d955ed2008-09-13 17:18:21 +0000480 shopkeeper="Michael Palin",
481 client="John Cleese",
482 sketch="Cheese Shop Sketch")
Georg Brandl116aa622007-08-15 14:28:22 +0000483
484and of course it would print::
485
486 -- Do you have any Limburger ?
487 -- I'm sorry, we're all out of Limburger
488 It's very runny, sir.
489 It's really very, VERY runny, sir.
490 ----------------------------------------
491 client : John Cleese
492 shopkeeper : Michael Palin
493 sketch : Cheese Shop Sketch
494
Georg Brandla6fa2722008-01-06 17:25:36 +0000495Note that the list of keyword argument names is created by sorting the result
496of the keywords dictionary's ``keys()`` method before printing its contents;
497if this is not done, the order in which the arguments are printed is undefined.
Georg Brandl116aa622007-08-15 14:28:22 +0000498
499.. _tut-arbitraryargs:
500
501Arbitrary Argument Lists
502------------------------
503
Christian Heimesdae2a892008-04-19 00:55:37 +0000504.. index::
Georg Brandl48310cd2009-01-03 21:18:54 +0000505 statement: *
Christian Heimesdae2a892008-04-19 00:55:37 +0000506
Georg Brandl116aa622007-08-15 14:28:22 +0000507Finally, the least frequently used option is to specify that a function can be
508called with an arbitrary number of arguments. These arguments will be wrapped
Georg Brandl5d955ed2008-09-13 17:18:21 +0000509up in a tuple (see :ref:`tut-tuples`). Before the variable number of arguments,
510zero or more normal arguments may occur. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000511
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000512 def write_multiple_items(file, separator, *args):
513 file.write(separator.join(args))
Georg Brandl116aa622007-08-15 14:28:22 +0000514
Georg Brandl48310cd2009-01-03 21:18:54 +0000515
Guido van Rossum0616b792007-08-31 03:25:11 +0000516Normally, these ``variadic`` arguments will be last in the list of formal
Georg Brandl48310cd2009-01-03 21:18:54 +0000517parameters, because they scoop up all remaining input arguments that are
Guido van Rossum0616b792007-08-31 03:25:11 +0000518passed to the function. Any formal parameters which occur after the ``*args``
Georg Brandl48310cd2009-01-03 21:18:54 +0000519parameter are 'keyword-only' arguments, meaning that they can only be used as
Georg Brandle4ac7502007-09-03 07:10:24 +0000520keywords rather than positional arguments. ::
Georg Brandl48310cd2009-01-03 21:18:54 +0000521
Guido van Rossum0616b792007-08-31 03:25:11 +0000522 >>> def concat(*args, sep="/"):
523 ... return sep.join(args)
524 ...
525 >>> concat("earth", "mars", "venus")
526 'earth/mars/venus'
527 >>> concat("earth", "mars", "venus", sep=".")
528 'earth.mars.venus'
Georg Brandl116aa622007-08-15 14:28:22 +0000529
530.. _tut-unpacking-arguments:
531
532Unpacking Argument Lists
533------------------------
534
535The reverse situation occurs when the arguments are already in a list or tuple
536but need to be unpacked for a function call requiring separate positional
537arguments. For instance, the built-in :func:`range` function expects separate
538*start* and *stop* arguments. If they are not available separately, write the
539function call with the ``*``\ -operator to unpack the arguments out of a list
540or tuple::
541
Guido van Rossum0616b792007-08-31 03:25:11 +0000542 >>> list(range(3, 6)) # normal call with separate arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000543 [3, 4, 5]
544 >>> args = [3, 6]
Guido van Rossum0616b792007-08-31 03:25:11 +0000545 >>> list(range(*args)) # call with arguments unpacked from a list
Georg Brandl116aa622007-08-15 14:28:22 +0000546 [3, 4, 5]
547
Christian Heimesdae2a892008-04-19 00:55:37 +0000548.. index::
549 statement: **
550
Georg Brandl116aa622007-08-15 14:28:22 +0000551In the same fashion, dictionaries can deliver keyword arguments with the ``**``\
552-operator::
553
554 >>> def parrot(voltage, state='a stiff', action='voom'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000555 ... print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000556 ... print("if you put", voltage, "volts through it.", end=' ')
557 ... print("E's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000558 ...
559 >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
560 >>> parrot(**d)
561 -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
562
563
564.. _tut-lambda:
565
566Lambda Forms
567------------
568
569By popular demand, a few features commonly found in functional programming
570languages like Lisp have been added to Python. With the :keyword:`lambda`
571keyword, small anonymous functions can be created. Here's a function that
572returns the sum of its two arguments: ``lambda a, b: a+b``. Lambda forms can be
573used wherever function objects are required. They are syntactically restricted
574to a single expression. Semantically, they are just syntactic sugar for a
575normal function definition. Like nested function definitions, lambda forms can
576reference variables from the containing scope::
577
578 >>> def make_incrementor(n):
579 ... return lambda x: x + n
580 ...
581 >>> f = make_incrementor(42)
582 >>> f(0)
583 42
584 >>> f(1)
585 43
586
587
588.. _tut-docstrings:
589
590Documentation Strings
591---------------------
592
593.. index::
594 single: docstrings
595 single: documentation strings
596 single: strings, documentation
597
Guido van Rossum0616b792007-08-31 03:25:11 +0000598Here are some conventions about the content and formatting of documentation
Georg Brandl48310cd2009-01-03 21:18:54 +0000599strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000600
601The first line should always be a short, concise summary of the object's
602purpose. For brevity, it should not explicitly state the object's name or type,
603since these are available by other means (except if the name happens to be a
604verb describing a function's operation). This line should begin with a capital
605letter and end with a period.
606
607If there are more lines in the documentation string, the second line should be
608blank, visually separating the summary from the rest of the description. The
609following lines should be one or more paragraphs describing the object's calling
610conventions, its side effects, etc.
611
612The Python parser does not strip indentation from multi-line string literals in
613Python, so tools that process documentation have to strip indentation if
614desired. This is done using the following convention. The first non-blank line
615*after* the first line of the string determines the amount of indentation for
616the entire documentation string. (We can't use the first line since it is
617generally adjacent to the string's opening quotes so its indentation is not
618apparent in the string literal.) Whitespace "equivalent" to this indentation is
619then stripped from the start of all lines of the string. Lines that are
620indented less should not occur, but if they occur all their leading whitespace
621should be stripped. Equivalence of whitespace should be tested after expansion
622of tabs (to 8 spaces, normally).
623
624Here is an example of a multi-line docstring::
625
626 >>> def my_function():
627 ... """Do nothing, but document it.
Georg Brandl48310cd2009-01-03 21:18:54 +0000628 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000629 ... No, really, it doesn't do anything.
630 ... """
631 ... pass
Georg Brandl48310cd2009-01-03 21:18:54 +0000632 ...
Guido van Rossum0616b792007-08-31 03:25:11 +0000633 >>> print(my_function.__doc__)
Georg Brandl116aa622007-08-15 14:28:22 +0000634 Do nothing, but document it.
635
636 No, really, it doesn't do anything.
637
638
Christian Heimes043d6f62008-01-07 17:19:16 +0000639.. _tut-codingstyle:
640
641Intermezzo: Coding Style
642========================
643
644.. sectionauthor:: Georg Brandl <georg@python.org>
645.. index:: pair: coding; style
646
647Now that you are about to write longer, more complex pieces of Python, it is a
648good time to talk about *coding style*. Most languages can be written (or more
649concise, *formatted*) in different styles; some are more readable than others.
650Making it easy for others to read your code is always a good idea, and adopting
651a nice coding style helps tremendously for that.
652
Christian Heimesdae2a892008-04-19 00:55:37 +0000653For Python, :pep:`8` has emerged as the style guide that most projects adhere to;
Christian Heimes043d6f62008-01-07 17:19:16 +0000654it promotes a very readable and eye-pleasing coding style. Every Python
655developer should read it at some point; here are the most important points
656extracted for you:
657
658* Use 4-space indentation, and no tabs.
659
660 4 spaces are a good compromise between small indentation (allows greater
661 nesting depth) and large indentation (easier to read). Tabs introduce
662 confusion, and are best left out.
663
664* Wrap lines so that they don't exceed 79 characters.
665
666 This helps users with small displays and makes it possible to have several
667 code files side-by-side on larger displays.
668
669* Use blank lines to separate functions and classes, and larger blocks of
670 code inside functions.
671
672* When possible, put comments on a line of their own.
673
674* Use docstrings.
675
676* Use spaces around operators and after commas, but not directly inside
677 bracketing constructs: ``a = f(1, 2) + g(3, 4)``.
678
679* Name your classes and functions consistently; the convention is to use
680 ``CamelCase`` for classes and ``lower_case_with_underscores`` for functions
Georg Brandl5d955ed2008-09-13 17:18:21 +0000681 and methods. Always use ``self`` as the name for the first method argument
682 (see :ref:`tut-firstclasses` for more on classes and methods).
Christian Heimes043d6f62008-01-07 17:19:16 +0000683
684* Don't use fancy encodings if your code is meant to be used in international
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000685 environments. Python's default, UTF-8, or even plain ASCII work best in any
686 case.
687
688* Likewise, don't use non-ASCII characters in identifiers if there is only the
689 slightest chance people speaking a different language will read or maintain
690 the code.
Christian Heimes043d6f62008-01-07 17:19:16 +0000691
Georg Brandl116aa622007-08-15 14:28:22 +0000692
693.. rubric:: Footnotes
694
Christian Heimes043d6f62008-01-07 17:19:16 +0000695.. [#] Actually, *call by object reference* would be a better description,
696 since if a mutable object is passed, the caller will see any changes the
697 callee makes to it (items inserted into a list).
Georg Brandl116aa622007-08-15 14:28:22 +0000698