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