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