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