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