blob: c3ce1205e52e41767b2bd1c3a038beb61ddaef59 [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
Serhiy Storchaka1e47fbc2018-12-19 09:28:12 +020013:keyword:`!if` Statements
14=========================
Georg Brandl116aa622007-08-15 14:28:22 +000015
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:
Ezio Melottie65cb192013-11-17 22:07:48 +020022 ... x = 0
23 ... print('Negative changed to zero')
Georg Brandl116aa622007-08-15 14:28:22 +000024 ... elif x == 0:
Ezio Melottie65cb192013-11-17 22:07:48 +020025 ... print('Zero')
Georg Brandl116aa622007-08-15 14:28:22 +000026 ... elif x == 1:
Ezio Melottie65cb192013-11-17 22:07:48 +020027 ... print('Single')
Georg Brandl116aa622007-08-15 14:28:22 +000028 ... else:
Ezio Melottie65cb192013-11-17 22:07:48 +020029 ... 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
Serhiy Storchaka1e47fbc2018-12-19 09:28:12 +020034optional. 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
Christian Heimes5b5e81c2007-12-31 16:14:33 +000037``case`` statements found in other languages.
Georg Brandl116aa622007-08-15 14:28:22 +000038
39
40.. _tut-for:
41
Serhiy Storchaka1e47fbc2018-12-19 09:28:12 +020042:keyword:`!for` Statements
43==========================
Georg Brandl116aa622007-08-15 14:28:22 +000044
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
Serhiy Storchaka1e47fbc2018-12-19 09:28:12 +020051iteration step and halting condition (as C), Python's :keyword:`!for` statement
Georg Brandl116aa622007-08-15 14:28:22 +000052iterates 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:
Chris Jerdonek4fab8f02012-10-15 19:44:47 -070061 ... words = ['cat', 'window', 'defenestrate']
62 >>> for w in words:
63 ... print(w, len(w))
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
Chris Jerdonek4fab8f02012-10-15 19:44:47 -070069If you need to modify the sequence you are iterating over while inside the loop
70(for example to duplicate selected items), it is recommended that you first
71make a copy. Iterating over a sequence does not implicitly make a copy. The
72slice notation makes this especially convenient::
Georg Brandl116aa622007-08-15 14:28:22 +000073
Chris Jerdonek4fab8f02012-10-15 19:44:47 -070074 >>> for w in words[:]: # Loop over a slice copy of the entire list.
75 ... if len(w) > 6:
76 ... words.insert(0, w)
Georg Brandl48310cd2009-01-03 21:18:54 +000077 ...
Chris Jerdonek4fab8f02012-10-15 19:44:47 -070078 >>> words
Georg Brandl116aa622007-08-15 14:28:22 +000079 ['defenestrate', 'cat', 'window', 'defenestrate']
80
Georg Brandl40383c82016-02-15 17:50:33 +010081With ``for w in words:``, the example would attempt to create an infinite list,
82inserting ``defenestrate`` over and over again.
83
Georg Brandl116aa622007-08-15 14:28:22 +000084
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
Guido van Rossum0616b792007-08-31 03:25:11 +000091:func:`range` comes in handy. It generates arithmetic progressions::
Georg Brandl116aa622007-08-15 14:28:22 +000092
Guido van Rossum0616b792007-08-31 03:25:11 +000093 >>> for i in range(5):
94 ... print(i)
95 ...
96 0
97 1
98 2
99 3
100 4
Georg Brandl48310cd2009-01-03 21:18:54 +0000101
Georg Brandl7d821062010-06-27 10:59:19 +0000102The given end point is never part of the generated sequence; ``range(10)`` generates
Guido van Rossum0616b792007-08-31 03:25:11 +000010310 values, the legal indices for items of a sequence of length 10. It
Georg Brandl116aa622007-08-15 14:28:22 +0000104is possible to let the range start at another number, or to specify a different
105increment (even negative; sometimes this is called the 'step')::
106
Georg Brandl48310cd2009-01-03 21:18:54 +0000107 range(5, 10)
Miss Islington (bot)3ca5efc2018-03-10 15:25:14 -0800108 5, 6, 7, 8, 9
Guido van Rossum0616b792007-08-31 03:25:11 +0000109
Georg Brandl48310cd2009-01-03 21:18:54 +0000110 range(0, 10, 3)
Guido van Rossum0616b792007-08-31 03:25:11 +0000111 0, 3, 6, 9
112
Georg Brandl48310cd2009-01-03 21:18:54 +0000113 range(-10, -100, -30)
Guido van Rossum0616b792007-08-31 03:25:11 +0000114 -10, -40, -70
Georg Brandl116aa622007-08-15 14:28:22 +0000115
Georg Brandlaf265f42008-12-07 15:06:20 +0000116To iterate over the indices of a sequence, you can combine :func:`range` and
117:func:`len` as follows::
Georg Brandl116aa622007-08-15 14:28:22 +0000118
119 >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
120 >>> for i in range(len(a)):
Guido van Rossum0616b792007-08-31 03:25:11 +0000121 ... print(i, a[i])
Georg Brandl48310cd2009-01-03 21:18:54 +0000122 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000123 0 Mary
124 1 had
125 2 a
126 3 little
127 4 lamb
128
Georg Brandlaf265f42008-12-07 15:06:20 +0000129In most such cases, however, it is convenient to use the :func:`enumerate`
130function, see :ref:`tut-loopidioms`.
131
Guido van Rossum0616b792007-08-31 03:25:11 +0000132A 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,
Georg Brandl48310cd2009-01-03 21:18:54 +0000138but 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.
Guido van Rossum0616b792007-08-31 03:25:11 +0000141
Georg Brandl48310cd2009-01-03 21:18:54 +0000142We say such an object is *iterable*, that is, suitable as a target for
143functions and constructs that expect something from which they can
Guido van Rossum0616b792007-08-31 03:25:11 +0000144obtain successive items until the supply is exhausted. We have seen that
145the :keyword:`for` statement is such an *iterator*. The function :func:`list`
146is another; it creates lists from iterables::
147
148
149 >>> list(range(5))
150 [0, 1, 2, 3, 4]
151
152Later we will see more functions that return iterables and take iterables as argument.
Georg Brandl116aa622007-08-15 14:28:22 +0000153
Georg Brandlaf265f42008-12-07 15:06:20 +0000154
Georg Brandl116aa622007-08-15 14:28:22 +0000155.. _tut-break:
156
Serhiy Storchaka1e47fbc2018-12-19 09:28:12 +0200157:keyword:`!break` and :keyword:`!continue` Statements, and :keyword:`!else` Clauses on Loops
158============================================================================================
Georg Brandl116aa622007-08-15 14:28:22 +0000159
regexaurus36fc8962017-06-27 18:40:41 -0400160The :keyword:`break` statement, like in C, breaks out of the innermost enclosing
Georg Brandl116aa622007-08-15 14:28:22 +0000161:keyword:`for` or :keyword:`while` loop.
162
Serhiy Storchaka1e47fbc2018-12-19 09:28:12 +0200163Loop statements may have an :keyword:`!else` clause; it is executed when the loop
Georg Brandl116aa622007-08-15 14:28:22 +0000164terminates 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
Nick Coghlana3a164a2012-06-07 22:41:34 +1000190When used with a loop, the ``else`` clause has more in common with the
191``else`` clause of a :keyword:`try` statement than it does that of
Serhiy Storchaka1e47fbc2018-12-19 09:28:12 +0200192:keyword:`if` statements: a :keyword:`!try` statement's ``else`` clause runs
Nick Coghlana3a164a2012-06-07 22:41:34 +1000193when no exception occurs, and a loop's ``else`` clause runs when no ``break``
Serhiy Storchaka1e47fbc2018-12-19 09:28:12 +0200194occurs. For more on the :keyword:`!try` statement and exceptions, see
Nick Coghlana3a164a2012-06-07 22:41:34 +1000195:ref:`tut-handling`.
196
Senthil Kumaran1ef9caa2012-08-12 12:01:47 -0700197The :keyword:`continue` statement, also borrowed from C, continues with the next
198iteration of the loop::
199
200 >>> for num in range(2, 10):
Eli Bendersky31a11902012-08-18 09:50:09 +0300201 ... if num % 2 == 0:
Senthil Kumaran1ef9caa2012-08-12 12:01:47 -0700202 ... print("Found an even number", num)
203 ... continue
204 ... print("Found a number", num)
205 Found an even number 2
206 Found a number 3
207 Found an even number 4
208 Found a number 5
209 Found an even number 6
210 Found a number 7
211 Found an even number 8
212 Found a number 9
Georg Brandl116aa622007-08-15 14:28:22 +0000213
214.. _tut-pass:
215
Serhiy Storchaka1e47fbc2018-12-19 09:28:12 +0200216:keyword:`!pass` Statements
217===========================
Georg Brandl116aa622007-08-15 14:28:22 +0000218
219The :keyword:`pass` statement does nothing. It can be used when a statement is
220required syntactically but the program requires no action. For example::
221
222 >>> while True:
Georg Brandl5d955ed2008-09-13 17:18:21 +0000223 ... pass # Busy-wait for keyboard interrupt (Ctrl+C)
Georg Brandl48310cd2009-01-03 21:18:54 +0000224 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000225
Benjamin Peterson92035012008-12-27 16:00:54 +0000226This is commonly used for creating minimal classes::
Georg Brandla971c652008-11-07 09:39:56 +0000227
Benjamin Peterson92035012008-12-27 16:00:54 +0000228 >>> class MyEmptyClass:
Georg Brandla971c652008-11-07 09:39:56 +0000229 ... pass
Benjamin Peterson92035012008-12-27 16:00:54 +0000230 ...
Georg Brandla971c652008-11-07 09:39:56 +0000231
232Another place :keyword:`pass` can be used is as a place-holder for a function or
Benjamin Peterson92035012008-12-27 16:00:54 +0000233conditional body when you are working on new code, allowing you to keep thinking
Serhiy Storchaka1e47fbc2018-12-19 09:28:12 +0200234at a more abstract level. The :keyword:`!pass` is silently ignored::
Georg Brandla971c652008-11-07 09:39:56 +0000235
236 >>> def initlog(*args):
Benjamin Peterson92035012008-12-27 16:00:54 +0000237 ... pass # Remember to implement this!
Georg Brandl48310cd2009-01-03 21:18:54 +0000238 ...
Georg Brandla971c652008-11-07 09:39:56 +0000239
Georg Brandl116aa622007-08-15 14:28:22 +0000240.. _tut-functions:
241
242Defining Functions
243==================
244
245We can create a function that writes the Fibonacci series to an arbitrary
246boundary::
247
248 >>> def fib(n): # write Fibonacci series up to n
249 ... """Print a Fibonacci series up to n."""
250 ... a, b = 0, 1
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000251 ... while a < n:
252 ... print(a, end=' ')
Georg Brandl116aa622007-08-15 14:28:22 +0000253 ... a, b = b, a+b
Guido van Rossum0616b792007-08-31 03:25:11 +0000254 ... print()
Georg Brandl48310cd2009-01-03 21:18:54 +0000255 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000256 >>> # Now call the function we just defined:
257 ... fib(2000)
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000258 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 +0000259
260.. index::
261 single: documentation strings
262 single: docstrings
263 single: strings, documentation
264
265The keyword :keyword:`def` introduces a function *definition*. It must be
266followed by the function name and the parenthesized list of formal parameters.
267The statements that form the body of the function start at the next line, and
Georg Brandl5d955ed2008-09-13 17:18:21 +0000268must be indented.
Georg Brandl116aa622007-08-15 14:28:22 +0000269
Georg Brandl5d955ed2008-09-13 17:18:21 +0000270The first statement of the function body can optionally be a string literal;
271this string literal is the function's documentation string, or :dfn:`docstring`.
272(More about docstrings can be found in the section :ref:`tut-docstrings`.)
Georg Brandl116aa622007-08-15 14:28:22 +0000273There are tools which use docstrings to automatically produce online or printed
274documentation, or to let the user interactively browse through code; it's good
Georg Brandl5d955ed2008-09-13 17:18:21 +0000275practice to include docstrings in code that you write, so make a habit of it.
Georg Brandl116aa622007-08-15 14:28:22 +0000276
277The *execution* of a function introduces a new symbol table used for the local
278variables of the function. More precisely, all variable assignments in a
279function store the value in the local symbol table; whereas variable references
Georg Brandl86def6c2008-01-21 20:36:10 +0000280first look in the local symbol table, then in the local symbol tables of
281enclosing functions, then in the global symbol table, and finally in the table
Miss Islington (bot)cee95fe2019-05-28 20:48:12 -0700282of built-in names. Thus, global variables and variables of enclosing functions
283cannot be directly assigned a value within a function (unless, for global
284variables, named in a :keyword:`global` statement, or, for variables of enclosing
285functions, named in a :keyword:`nonlocal` statement), although they may be
286referenced.
Georg Brandl116aa622007-08-15 14:28:22 +0000287
288The actual parameters (arguments) to a function call are introduced in the local
289symbol table of the called function when it is called; thus, arguments are
290passed using *call by value* (where the *value* is always an object *reference*,
291not the value of the object). [#]_ When a function calls another function, a new
292local symbol table is created for that call.
293
294A function definition introduces the function name in the current symbol table.
295The value of the function name has a type that is recognized by the interpreter
296as a user-defined function. This value can be assigned to another name which
297can then also be used as a function. This serves as a general renaming
298mechanism::
299
300 >>> fib
301 <function fib at 10042ed0>
302 >>> f = fib
303 >>> f(100)
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000304 0 1 1 2 3 5 8 13 21 34 55 89
Georg Brandl116aa622007-08-15 14:28:22 +0000305
Georg Brandl5d955ed2008-09-13 17:18:21 +0000306Coming from other languages, you might object that ``fib`` is not a function but
307a procedure since it doesn't return a value. In fact, even functions without a
308:keyword:`return` statement do return a value, albeit a rather boring one. This
309value is called ``None`` (it's a built-in name). Writing the value ``None`` is
310normally suppressed by the interpreter if it would be the only value written.
311You can see it if you really want to using :func:`print`::
Georg Brandl116aa622007-08-15 14:28:22 +0000312
Georg Brandl9afde1c2007-11-01 20:32:30 +0000313 >>> fib(0)
Guido van Rossum0616b792007-08-31 03:25:11 +0000314 >>> print(fib(0))
Georg Brandl116aa622007-08-15 14:28:22 +0000315 None
316
317It is simple to write a function that returns a list of the numbers of the
318Fibonacci series, instead of printing it::
319
Serhiy Storchakadba90392016-05-10 12:01:23 +0300320 >>> def fib2(n): # return Fibonacci series up to n
Georg Brandl116aa622007-08-15 14:28:22 +0000321 ... """Return a list containing the Fibonacci series up to n."""
322 ... result = []
323 ... a, b = 0, 1
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000324 ... while a < n:
325 ... result.append(a) # see below
Georg Brandl116aa622007-08-15 14:28:22 +0000326 ... a, b = b, a+b
327 ... return result
Georg Brandl48310cd2009-01-03 21:18:54 +0000328 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000329 >>> f100 = fib2(100) # call it
330 >>> f100 # write the result
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000331 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Georg Brandl116aa622007-08-15 14:28:22 +0000332
333This example, as usual, demonstrates some new Python features:
334
335* The :keyword:`return` statement returns with a value from a function.
Serhiy Storchaka1e47fbc2018-12-19 09:28:12 +0200336 :keyword:`!return` without an expression argument returns ``None``. Falling off
Georg Brandl5d955ed2008-09-13 17:18:21 +0000337 the end of a function also returns ``None``.
Georg Brandl116aa622007-08-15 14:28:22 +0000338
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000339* The statement ``result.append(a)`` calls a *method* of the list object
Georg Brandl116aa622007-08-15 14:28:22 +0000340 ``result``. A method is a function that 'belongs' to an object and is named
341 ``obj.methodname``, where ``obj`` is some object (this may be an expression),
342 and ``methodname`` is the name of a method that is defined by the object's type.
343 Different types define different methods. Methods of different types may have
344 the same name without causing ambiguity. (It is possible to define your own
Georg Brandlc6c31782009-06-08 13:41:29 +0000345 object types and methods, using *classes*, see :ref:`tut-classes`)
Georg Brandl116aa622007-08-15 14:28:22 +0000346 The method :meth:`append` shown in the example is defined for list objects; it
347 adds a new element at the end of the list. In this example it is equivalent to
Mark Dickinsonc099ee22009-11-23 16:41:41 +0000348 ``result = result + [a]``, but more efficient.
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350
351.. _tut-defining:
352
353More on Defining Functions
354==========================
355
356It is also possible to define functions with a variable number of arguments.
357There are three forms, which can be combined.
358
359
360.. _tut-defaultargs:
361
362Default Argument Values
363-----------------------
364
365The most useful form is to specify a default value for one or more arguments.
366This creates a function that can be called with fewer arguments than it is
367defined to allow. For example::
368
Berker Peksag0a5120e2016-06-02 11:31:19 -0700369 def ask_ok(prompt, retries=4, reminder='Please try again!'):
Georg Brandl116aa622007-08-15 14:28:22 +0000370 while True:
Georg Brandle9af2842007-08-17 05:54:09 +0000371 ok = input(prompt)
Georg Brandlc6c31782009-06-08 13:41:29 +0000372 if ok in ('y', 'ye', 'yes'):
373 return True
374 if ok in ('n', 'no', 'nop', 'nope'):
375 return False
Georg Brandl116aa622007-08-15 14:28:22 +0000376 retries = retries - 1
Collin Winter58721bc2007-09-10 00:39:52 +0000377 if retries < 0:
Berker Peksag0a5120e2016-06-02 11:31:19 -0700378 raise ValueError('invalid user response')
379 print(reminder)
Georg Brandl116aa622007-08-15 14:28:22 +0000380
Georg Brandlc6c31782009-06-08 13:41:29 +0000381This function can be called in several ways:
382
383* giving only the mandatory argument:
384 ``ask_ok('Do you really want to quit?')``
385* giving one of the optional arguments:
386 ``ask_ok('OK to overwrite the file?', 2)``
387* or even giving all arguments:
388 ``ask_ok('OK to overwrite the file?', 2, 'Come on, only yes or no!')``
Georg Brandl116aa622007-08-15 14:28:22 +0000389
390This example also introduces the :keyword:`in` keyword. This tests whether or
391not a sequence contains a certain value.
392
393The default values are evaluated at the point of function definition in the
394*defining* scope, so that ::
395
396 i = 5
397
398 def f(arg=i):
Guido van Rossum0616b792007-08-31 03:25:11 +0000399 print(arg)
Georg Brandl116aa622007-08-15 14:28:22 +0000400
401 i = 6
402 f()
403
404will print ``5``.
405
406**Important warning:** The default value is evaluated only once. This makes a
407difference when the default is a mutable object such as a list, dictionary, or
408instances of most classes. For example, the following function accumulates the
409arguments passed to it on subsequent calls::
410
411 def f(a, L=[]):
412 L.append(a)
413 return L
414
Guido van Rossum0616b792007-08-31 03:25:11 +0000415 print(f(1))
416 print(f(2))
417 print(f(3))
Georg Brandl116aa622007-08-15 14:28:22 +0000418
419This will print ::
420
421 [1]
422 [1, 2]
423 [1, 2, 3]
424
425If you don't want the default to be shared between subsequent calls, you can
426write the function like this instead::
427
428 def f(a, L=None):
429 if L is None:
430 L = []
431 L.append(a)
432 return L
433
434
435.. _tut-keywordargs:
436
437Keyword Arguments
438-----------------
439
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200440Functions can also be called using :term:`keyword arguments <keyword argument>`
441of the form ``kwarg=value``. For instance, the following function::
Georg Brandl116aa622007-08-15 14:28:22 +0000442
443 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000444 print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000445 print("if you put", voltage, "volts through it.")
446 print("-- Lovely plumage, the", type)
447 print("-- It's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000448
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200449accepts one required argument (``voltage``) and three optional arguments
450(``state``, ``action``, and ``type``). This function can be called in any
451of the following ways::
Georg Brandl116aa622007-08-15 14:28:22 +0000452
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200453 parrot(1000) # 1 positional argument
454 parrot(voltage=1000) # 1 keyword argument
455 parrot(voltage=1000000, action='VOOOOOM') # 2 keyword arguments
456 parrot(action='VOOOOOM', voltage=1000000) # 2 keyword arguments
457 parrot('a million', 'bereft of life', 'jump') # 3 positional arguments
458 parrot('a thousand', state='pushing up the daisies') # 1 positional, 1 keyword
Georg Brandl116aa622007-08-15 14:28:22 +0000459
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200460but all the following calls would be invalid::
Georg Brandl116aa622007-08-15 14:28:22 +0000461
462 parrot() # required argument missing
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200463 parrot(voltage=5.0, 'dead') # non-keyword argument after a keyword argument
464 parrot(110, voltage=220) # duplicate value for the same argument
465 parrot(actor='John Cleese') # unknown keyword argument
Georg Brandl116aa622007-08-15 14:28:22 +0000466
Ezio Melotti7b7e39a2011-12-13 15:49:22 +0200467In a function call, keyword arguments must follow positional arguments.
468All the keyword arguments passed must match one of the arguments
469accepted by the function (e.g. ``actor`` is not a valid argument for the
470``parrot`` function), and their order is not important. This also includes
471non-optional arguments (e.g. ``parrot(voltage=1000)`` is valid too).
472No argument may receive a value more than once.
473Here's an example that fails due to this restriction::
Georg Brandl116aa622007-08-15 14:28:22 +0000474
475 >>> def function(a):
476 ... pass
Georg Brandl48310cd2009-01-03 21:18:54 +0000477 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000478 >>> function(0, a=0)
479 Traceback (most recent call last):
UltimateCoder88569402017-05-03 22:16:45 +0530480 File "<stdin>", line 1, in <module>
Georg Brandl116aa622007-08-15 14:28:22 +0000481 TypeError: function() got multiple values for keyword argument 'a'
482
483When a final formal parameter of the form ``**name`` is present, it receives a
484dictionary (see :ref:`typesmapping`) containing all keyword arguments except for
485those corresponding to a formal parameter. This may be combined with a formal
486parameter of the form ``*name`` (described in the next subsection) which
Miss Islington (bot)95b77062019-05-28 06:20:58 -0700487receives a :ref:`tuple <tut-tuples>` containing the positional
488arguments beyond the formal parameter list. (``*name`` must occur
489before ``**name``.) For example, if we define a function like this::
Georg Brandl116aa622007-08-15 14:28:22 +0000490
491 def cheeseshop(kind, *arguments, **keywords):
Georg Brandl5d955ed2008-09-13 17:18:21 +0000492 print("-- Do you have any", kind, "?")
Guido van Rossum0616b792007-08-31 03:25:11 +0000493 print("-- I'm sorry, we're all out of", kind)
Georg Brandl70543ac2010-10-15 15:32:05 +0000494 for arg in arguments:
495 print(arg)
Georg Brandl5d955ed2008-09-13 17:18:21 +0000496 print("-" * 40)
Jim Fasarakis-Hilliard32e8f9b2017-02-21 08:20:23 +0200497 for kw in keywords:
Georg Brandl70543ac2010-10-15 15:32:05 +0000498 print(kw, ":", keywords[kw])
Georg Brandl116aa622007-08-15 14:28:22 +0000499
500It could be called like this::
501
Georg Brandl5d955ed2008-09-13 17:18:21 +0000502 cheeseshop("Limburger", "It's very runny, sir.",
Georg Brandl116aa622007-08-15 14:28:22 +0000503 "It's really very, VERY runny, sir.",
Georg Brandl5d955ed2008-09-13 17:18:21 +0000504 shopkeeper="Michael Palin",
505 client="John Cleese",
506 sketch="Cheese Shop Sketch")
Georg Brandl116aa622007-08-15 14:28:22 +0000507
Martin Panter1050d2d2016-07-26 11:18:21 +0200508and of course it would print:
509
510.. code-block:: none
Georg Brandl116aa622007-08-15 14:28:22 +0000511
512 -- Do you have any Limburger ?
513 -- I'm sorry, we're all out of Limburger
514 It's very runny, sir.
515 It's really very, VERY runny, sir.
516 ----------------------------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000517 shopkeeper : Michael Palin
Jim Fasarakis-Hilliard32e8f9b2017-02-21 08:20:23 +0200518 client : John Cleese
Georg Brandl116aa622007-08-15 14:28:22 +0000519 sketch : Cheese Shop Sketch
520
Jim Fasarakis-Hilliard32e8f9b2017-02-21 08:20:23 +0200521Note that the order in which the keyword arguments are printed is guaranteed
522to match the order in which they were provided in the function call.
523
Georg Brandl116aa622007-08-15 14:28:22 +0000524
525.. _tut-arbitraryargs:
526
527Arbitrary Argument Lists
528------------------------
529
Christian Heimesdae2a892008-04-19 00:55:37 +0000530.. index::
Miss Islington (bot)fdf48b62018-10-28 09:43:32 -0700531 single: * (asterisk); in function calls
Christian Heimesdae2a892008-04-19 00:55:37 +0000532
Georg Brandl116aa622007-08-15 14:28:22 +0000533Finally, the least frequently used option is to specify that a function can be
534called with an arbitrary number of arguments. These arguments will be wrapped
Georg Brandl5d955ed2008-09-13 17:18:21 +0000535up in a tuple (see :ref:`tut-tuples`). Before the variable number of arguments,
536zero or more normal arguments may occur. ::
Georg Brandl116aa622007-08-15 14:28:22 +0000537
Georg Brandlf08a9dd2008-06-10 16:57:31 +0000538 def write_multiple_items(file, separator, *args):
539 file.write(separator.join(args))
Georg Brandl116aa622007-08-15 14:28:22 +0000540
Georg Brandl48310cd2009-01-03 21:18:54 +0000541
Guido van Rossum0616b792007-08-31 03:25:11 +0000542Normally, these ``variadic`` arguments will be last in the list of formal
Georg Brandl48310cd2009-01-03 21:18:54 +0000543parameters, because they scoop up all remaining input arguments that are
Guido van Rossum0616b792007-08-31 03:25:11 +0000544passed to the function. Any formal parameters which occur after the ``*args``
Georg Brandl48310cd2009-01-03 21:18:54 +0000545parameter are 'keyword-only' arguments, meaning that they can only be used as
Georg Brandle4ac7502007-09-03 07:10:24 +0000546keywords rather than positional arguments. ::
Georg Brandl48310cd2009-01-03 21:18:54 +0000547
Guido van Rossum0616b792007-08-31 03:25:11 +0000548 >>> def concat(*args, sep="/"):
Serhiy Storchakadba90392016-05-10 12:01:23 +0300549 ... return sep.join(args)
Guido van Rossum0616b792007-08-31 03:25:11 +0000550 ...
551 >>> concat("earth", "mars", "venus")
552 'earth/mars/venus'
553 >>> concat("earth", "mars", "venus", sep=".")
554 'earth.mars.venus'
Georg Brandl116aa622007-08-15 14:28:22 +0000555
556.. _tut-unpacking-arguments:
557
558Unpacking Argument Lists
559------------------------
560
561The reverse situation occurs when the arguments are already in a list or tuple
562but need to be unpacked for a function call requiring separate positional
563arguments. For instance, the built-in :func:`range` function expects separate
564*start* and *stop* arguments. If they are not available separately, write the
Miss Islington (bot)e16599c2019-03-26 18:23:54 -0700565function call with the ``*`` operator to unpack the arguments out of a list
Georg Brandl116aa622007-08-15 14:28:22 +0000566or tuple::
567
Guido van Rossum0616b792007-08-31 03:25:11 +0000568 >>> list(range(3, 6)) # normal call with separate arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000569 [3, 4, 5]
570 >>> args = [3, 6]
Guido van Rossum0616b792007-08-31 03:25:11 +0000571 >>> list(range(*args)) # call with arguments unpacked from a list
Georg Brandl116aa622007-08-15 14:28:22 +0000572 [3, 4, 5]
573
Christian Heimesdae2a892008-04-19 00:55:37 +0000574.. index::
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300575 single: **; in function calls
Christian Heimesdae2a892008-04-19 00:55:37 +0000576
Serhiy Storchakab1837502018-10-31 11:00:24 +0200577In the same fashion, dictionaries can deliver keyword arguments with the
Miss Islington (bot)e16599c2019-03-26 18:23:54 -0700578``**`` operator::
Georg Brandl116aa622007-08-15 14:28:22 +0000579
580 >>> def parrot(voltage, state='a stiff', action='voom'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000581 ... print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000582 ... print("if you put", voltage, "volts through it.", end=' ')
583 ... print("E's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000584 ...
585 >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
586 >>> parrot(**d)
587 -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
588
589
590.. _tut-lambda:
591
Georg Brandlde5aff12013-10-06 10:22:45 +0200592Lambda Expressions
593------------------
Georg Brandl116aa622007-08-15 14:28:22 +0000594
Georg Brandlde5aff12013-10-06 10:22:45 +0200595Small anonymous functions can be created with the :keyword:`lambda` keyword.
596This function returns the sum of its two arguments: ``lambda a, b: a+b``.
Georg Brandl242e6a02013-10-06 10:28:39 +0200597Lambda functions can be used wherever function objects are required. They are
Georg Brandlde5aff12013-10-06 10:22:45 +0200598syntactically restricted to a single expression. Semantically, they are just
599syntactic sugar for a normal function definition. Like nested function
600definitions, lambda functions can reference variables from the containing
601scope::
Georg Brandl116aa622007-08-15 14:28:22 +0000602
603 >>> def make_incrementor(n):
604 ... return lambda x: x + n
605 ...
606 >>> f = make_incrementor(42)
607 >>> f(0)
608 42
609 >>> f(1)
610 43
611
Georg Brandlde5aff12013-10-06 10:22:45 +0200612The above example uses a lambda expression to return a function. Another use
613is to pass a small function as an argument::
614
615 >>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
616 >>> pairs.sort(key=lambda pair: pair[1])
617 >>> pairs
618 [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
619
Georg Brandl116aa622007-08-15 14:28:22 +0000620
621.. _tut-docstrings:
622
623Documentation Strings
624---------------------
625
626.. index::
627 single: docstrings
628 single: documentation strings
629 single: strings, documentation
630
Guido van Rossum0616b792007-08-31 03:25:11 +0000631Here are some conventions about the content and formatting of documentation
Georg Brandl48310cd2009-01-03 21:18:54 +0000632strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000633
634The first line should always be a short, concise summary of the object's
635purpose. For brevity, it should not explicitly state the object's name or type,
636since these are available by other means (except if the name happens to be a
637verb describing a function's operation). This line should begin with a capital
638letter and end with a period.
639
640If there are more lines in the documentation string, the second line should be
641blank, visually separating the summary from the rest of the description. The
642following lines should be one or more paragraphs describing the object's calling
643conventions, its side effects, etc.
644
645The Python parser does not strip indentation from multi-line string literals in
646Python, so tools that process documentation have to strip indentation if
647desired. This is done using the following convention. The first non-blank line
648*after* the first line of the string determines the amount of indentation for
649the entire documentation string. (We can't use the first line since it is
650generally adjacent to the string's opening quotes so its indentation is not
651apparent in the string literal.) Whitespace "equivalent" to this indentation is
652then stripped from the start of all lines of the string. Lines that are
653indented less should not occur, but if they occur all their leading whitespace
654should be stripped. Equivalence of whitespace should be tested after expansion
655of tabs (to 8 spaces, normally).
656
657Here is an example of a multi-line docstring::
658
659 >>> def my_function():
660 ... """Do nothing, but document it.
Georg Brandl48310cd2009-01-03 21:18:54 +0000661 ...
Georg Brandl116aa622007-08-15 14:28:22 +0000662 ... No, really, it doesn't do anything.
663 ... """
664 ... pass
Georg Brandl48310cd2009-01-03 21:18:54 +0000665 ...
Guido van Rossum0616b792007-08-31 03:25:11 +0000666 >>> print(my_function.__doc__)
Georg Brandl116aa622007-08-15 14:28:22 +0000667 Do nothing, but document it.
668
669 No, really, it doesn't do anything.
670
671
Andrew Svetlov1491cbd2012-11-01 21:26:55 +0200672.. _tut-annotations:
673
674Function Annotations
675--------------------
676
677.. sectionauthor:: Zachary Ware <zachary.ware@gmail.com>
678.. index::
679 pair: function; annotations
Serhiy Storchaka9a75b842018-10-26 11:18:42 +0300680 single: ->; function annotations
Miss Islington (bot)fdf48b62018-10-28 09:43:32 -0700681 single: : (colon); function annotations
Andrew Svetlov1491cbd2012-11-01 21:26:55 +0200682
Zachary Waref3b990e2015-04-13 11:30:47 -0500683:ref:`Function annotations <function>` are completely optional metadata
Miss Islington (bot)19858492018-04-25 11:04:49 -0700684information about the types used by user-defined functions (see :pep:`3107` and
685:pep:`484` for more information).
Andrew Svetlov1491cbd2012-11-01 21:26:55 +0200686
Miss Islington (bot)bc641232018-12-23 21:18:39 -0800687:term:`Annotations <function annotation>` are stored in the :attr:`__annotations__`
688attribute of the function as a dictionary and have no effect on any other part of the
689function. Parameter annotations are defined by a colon after the parameter name, followed
690by an expression evaluating to the value of the annotation. Return annotations are
Andrew Svetlov1491cbd2012-11-01 21:26:55 +0200691defined by a literal ``->``, followed by an expression, between the parameter
692list and the colon denoting the end of the :keyword:`def` statement. The
693following example has a positional argument, a keyword argument, and the return
Zachary Waref3b990e2015-04-13 11:30:47 -0500694value annotated::
Andrew Svetlov1491cbd2012-11-01 21:26:55 +0200695
Zachary Waref3b990e2015-04-13 11:30:47 -0500696 >>> def f(ham: str, eggs: str = 'eggs') -> str:
Andrew Svetlov1491cbd2012-11-01 21:26:55 +0200697 ... print("Annotations:", f.__annotations__)
698 ... print("Arguments:", ham, eggs)
Zachary Waref3b990e2015-04-13 11:30:47 -0500699 ... return ham + ' and ' + eggs
Andrew Svetlov1491cbd2012-11-01 21:26:55 +0200700 ...
Zachary Waref3b990e2015-04-13 11:30:47 -0500701 >>> f('spam')
702 Annotations: {'ham': <class 'str'>, 'return': <class 'str'>, 'eggs': <class 'str'>}
703 Arguments: spam eggs
704 'spam and eggs'
Andrew Svetlov1491cbd2012-11-01 21:26:55 +0200705
Christian Heimes043d6f62008-01-07 17:19:16 +0000706.. _tut-codingstyle:
707
708Intermezzo: Coding Style
709========================
710
711.. sectionauthor:: Georg Brandl <georg@python.org>
712.. index:: pair: coding; style
713
714Now that you are about to write longer, more complex pieces of Python, it is a
715good time to talk about *coding style*. Most languages can be written (or more
716concise, *formatted*) in different styles; some are more readable than others.
717Making it easy for others to read your code is always a good idea, and adopting
718a nice coding style helps tremendously for that.
719
Christian Heimesdae2a892008-04-19 00:55:37 +0000720For Python, :pep:`8` has emerged as the style guide that most projects adhere to;
Christian Heimes043d6f62008-01-07 17:19:16 +0000721it promotes a very readable and eye-pleasing coding style. Every Python
722developer should read it at some point; here are the most important points
723extracted for you:
724
725* Use 4-space indentation, and no tabs.
726
727 4 spaces are a good compromise between small indentation (allows greater
728 nesting depth) and large indentation (easier to read). Tabs introduce
729 confusion, and are best left out.
730
731* Wrap lines so that they don't exceed 79 characters.
732
733 This helps users with small displays and makes it possible to have several
734 code files side-by-side on larger displays.
735
736* Use blank lines to separate functions and classes, and larger blocks of
737 code inside functions.
738
739* When possible, put comments on a line of their own.
740
741* Use docstrings.
742
743* Use spaces around operators and after commas, but not directly inside
744 bracketing constructs: ``a = f(1, 2) + g(3, 4)``.
745
746* Name your classes and functions consistently; the convention is to use
747 ``CamelCase`` for classes and ``lower_case_with_underscores`` for functions
Georg Brandl5d955ed2008-09-13 17:18:21 +0000748 and methods. Always use ``self`` as the name for the first method argument
749 (see :ref:`tut-firstclasses` for more on classes and methods).
Christian Heimes043d6f62008-01-07 17:19:16 +0000750
751* Don't use fancy encodings if your code is meant to be used in international
Georg Brandl7ae90dd2009-06-08 18:59:09 +0000752 environments. Python's default, UTF-8, or even plain ASCII work best in any
753 case.
754
755* Likewise, don't use non-ASCII characters in identifiers if there is only the
756 slightest chance people speaking a different language will read or maintain
757 the code.
Christian Heimes043d6f62008-01-07 17:19:16 +0000758
Georg Brandl116aa622007-08-15 14:28:22 +0000759
760.. rubric:: Footnotes
761
Christian Heimes043d6f62008-01-07 17:19:16 +0000762.. [#] Actually, *call by object reference* would be a better description,
763 since if a mutable object is passed, the caller will see any changes the
764 callee makes to it (items inserted into a list).