blob: 5a182a91a7854374e5c45df11880f2ebacb07d56 [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:
Georg Brandle4ac7502007-09-03 07:10:24 +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
Collin Winter58721bc2007-09-10 00:39:52 +0000332 if retries < 0:
333 raise IOError('refusenik user')
Guido van Rossum0616b792007-08-31 03:25:11 +0000334 print(complaint)
Georg Brandl116aa622007-08-15 14:28:22 +0000335
336This function can be called either like this: ``ask_ok('Do you really want to
337quit?')`` or like this: ``ask_ok('OK to overwrite the file?', 2)``.
338
339This example also introduces the :keyword:`in` keyword. This tests whether or
340not a sequence contains a certain value.
341
342The default values are evaluated at the point of function definition in the
343*defining* scope, so that ::
344
345 i = 5
346
347 def f(arg=i):
Guido van Rossum0616b792007-08-31 03:25:11 +0000348 print(arg)
Georg Brandl116aa622007-08-15 14:28:22 +0000349
350 i = 6
351 f()
352
353will print ``5``.
354
355**Important warning:** The default value is evaluated only once. This makes a
356difference when the default is a mutable object such as a list, dictionary, or
357instances of most classes. For example, the following function accumulates the
358arguments passed to it on subsequent calls::
359
360 def f(a, L=[]):
361 L.append(a)
362 return L
363
Guido van Rossum0616b792007-08-31 03:25:11 +0000364 print(f(1))
365 print(f(2))
366 print(f(3))
Georg Brandl116aa622007-08-15 14:28:22 +0000367
368This will print ::
369
370 [1]
371 [1, 2]
372 [1, 2, 3]
373
374If you don't want the default to be shared between subsequent calls, you can
375write the function like this instead::
376
377 def f(a, L=None):
378 if L is None:
379 L = []
380 L.append(a)
381 return L
382
383
384.. _tut-keywordargs:
385
386Keyword Arguments
387-----------------
388
389Functions can also be called using keyword arguments of the form ``keyword =
390value``. For instance, the following function::
391
392 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000393 print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000394 print("if you put", voltage, "volts through it.")
395 print("-- Lovely plumage, the", type)
396 print("-- It's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000397
398could be called in any of the following ways::
399
400 parrot(1000)
401 parrot(action = 'VOOOOOM', voltage = 1000000)
402 parrot('a thousand', state = 'pushing up the daisies')
403 parrot('a million', 'bereft of life', 'jump')
404
405but the following calls would all be invalid::
406
407 parrot() # required argument missing
408 parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
409 parrot(110, voltage=220) # duplicate value for argument
410 parrot(actor='John Cleese') # unknown keyword
411
412In general, an argument list must have any positional arguments followed by any
413keyword arguments, where the keywords must be chosen from the formal parameter
414names. It's not important whether a formal parameter has a default value or
415not. No argument may receive a value more than once --- formal parameter names
416corresponding to positional arguments cannot be used as keywords in the same
417calls. Here's an example that fails due to this restriction::
418
419 >>> def function(a):
420 ... pass
421 ...
422 >>> function(0, a=0)
423 Traceback (most recent call last):
424 File "<stdin>", line 1, in ?
425 TypeError: function() got multiple values for keyword argument 'a'
426
427When a final formal parameter of the form ``**name`` is present, it receives a
428dictionary (see :ref:`typesmapping`) containing all keyword arguments except for
429those corresponding to a formal parameter. This may be combined with a formal
430parameter of the form ``*name`` (described in the next subsection) which
431receives a tuple containing the positional arguments beyond the formal parameter
432list. (``*name`` must occur before ``**name``.) For example, if we define a
433function like this::
434
435 def cheeseshop(kind, *arguments, **keywords):
Guido van Rossum0616b792007-08-31 03:25:11 +0000436 print("-- Do you have any", kind, '?')
437 print("-- I'm sorry, we're all out of", kind)
Georg Brandl116aa622007-08-15 14:28:22 +0000438 for arg in arguments: print arg
Guido van Rossum0616b792007-08-31 03:25:11 +0000439 print('-'*40)
Neal Norwitze0906d12007-08-31 03:46:28 +0000440 keys = sorted(keywords.keys())
Guido van Rossum0616b792007-08-31 03:25:11 +0000441 for kw in keys: print(kw, ':', keywords[kw])
Georg Brandl116aa622007-08-15 14:28:22 +0000442
443It could be called like this::
444
445 cheeseshop('Limburger', "It's very runny, sir.",
446 "It's really very, VERY runny, sir.",
447 client='John Cleese',
448 shopkeeper='Michael Palin',
449 sketch='Cheese Shop Sketch')
450
451and of course it would print::
452
453 -- Do you have any Limburger ?
454 -- I'm sorry, we're all out of Limburger
455 It's very runny, sir.
456 It's really very, VERY runny, sir.
457 ----------------------------------------
458 client : John Cleese
459 shopkeeper : Michael Palin
460 sketch : Cheese Shop Sketch
461
462Note that the :meth:`sort` method of the list of keyword argument names is
463called before printing the contents of the ``keywords`` dictionary; if this is
464not done, the order in which the arguments are printed is undefined.
465
466
467.. _tut-arbitraryargs:
468
469Arbitrary Argument Lists
470------------------------
471
472Finally, the least frequently used option is to specify that a function can be
473called with an arbitrary number of arguments. These arguments will be wrapped
474up in a tuple. Before the variable number of arguments, zero or more normal
475arguments may occur. ::
476
477 def fprintf(file, format, *args):
478 file.write(format % args)
479
Guido van Rossum0616b792007-08-31 03:25:11 +0000480
481Normally, these ``variadic`` arguments will be last in the list of formal
482parameters, because they scoop up all remaining input arguments that are
483passed to the function. Any formal parameters which occur after the ``*args``
484parameter are 'keyword-only' arguments, meaning that they can only be used as
Georg Brandle4ac7502007-09-03 07:10:24 +0000485keywords rather than positional arguments. ::
Guido van Rossum0616b792007-08-31 03:25:11 +0000486
487 >>> def concat(*args, sep="/"):
488 ... return sep.join(args)
489 ...
490 >>> concat("earth", "mars", "venus")
491 'earth/mars/venus'
492 >>> concat("earth", "mars", "venus", sep=".")
493 'earth.mars.venus'
Georg Brandl116aa622007-08-15 14:28:22 +0000494
495.. _tut-unpacking-arguments:
496
497Unpacking Argument Lists
498------------------------
499
500The reverse situation occurs when the arguments are already in a list or tuple
501but need to be unpacked for a function call requiring separate positional
502arguments. For instance, the built-in :func:`range` function expects separate
503*start* and *stop* arguments. If they are not available separately, write the
504function call with the ``*``\ -operator to unpack the arguments out of a list
505or tuple::
506
Guido van Rossum0616b792007-08-31 03:25:11 +0000507 >>> list(range(3, 6)) # normal call with separate arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000508 [3, 4, 5]
509 >>> args = [3, 6]
Guido van Rossum0616b792007-08-31 03:25:11 +0000510 >>> list(range(*args)) # call with arguments unpacked from a list
Georg Brandl116aa622007-08-15 14:28:22 +0000511 [3, 4, 5]
512
513In the same fashion, dictionaries can deliver keyword arguments with the ``**``\
514-operator::
515
516 >>> def parrot(voltage, state='a stiff', action='voom'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000517 ... print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000518 ... print("if you put", voltage, "volts through it.", end=' ')
519 ... print("E's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000520 ...
521 >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
522 >>> parrot(**d)
523 -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
524
525
526.. _tut-lambda:
527
528Lambda Forms
529------------
530
531By popular demand, a few features commonly found in functional programming
532languages like Lisp have been added to Python. With the :keyword:`lambda`
533keyword, small anonymous functions can be created. Here's a function that
534returns the sum of its two arguments: ``lambda a, b: a+b``. Lambda forms can be
535used wherever function objects are required. They are syntactically restricted
536to a single expression. Semantically, they are just syntactic sugar for a
537normal function definition. Like nested function definitions, lambda forms can
538reference variables from the containing scope::
539
540 >>> def make_incrementor(n):
541 ... return lambda x: x + n
542 ...
543 >>> f = make_incrementor(42)
544 >>> f(0)
545 42
546 >>> f(1)
547 43
548
549
550.. _tut-docstrings:
551
552Documentation Strings
553---------------------
554
555.. index::
556 single: docstrings
557 single: documentation strings
558 single: strings, documentation
559
Guido van Rossum0616b792007-08-31 03:25:11 +0000560Here are some conventions about the content and formatting of documentation
561strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000562
563The first line should always be a short, concise summary of the object's
564purpose. For brevity, it should not explicitly state the object's name or type,
565since these are available by other means (except if the name happens to be a
566verb describing a function's operation). This line should begin with a capital
567letter and end with a period.
568
569If there are more lines in the documentation string, the second line should be
570blank, visually separating the summary from the rest of the description. The
571following lines should be one or more paragraphs describing the object's calling
572conventions, its side effects, etc.
573
574The Python parser does not strip indentation from multi-line string literals in
575Python, so tools that process documentation have to strip indentation if
576desired. This is done using the following convention. The first non-blank line
577*after* the first line of the string determines the amount of indentation for
578the entire documentation string. (We can't use the first line since it is
579generally adjacent to the string's opening quotes so its indentation is not
580apparent in the string literal.) Whitespace "equivalent" to this indentation is
581then stripped from the start of all lines of the string. Lines that are
582indented less should not occur, but if they occur all their leading whitespace
583should be stripped. Equivalence of whitespace should be tested after expansion
584of tabs (to 8 spaces, normally).
585
586Here is an example of a multi-line docstring::
587
588 >>> def my_function():
589 ... """Do nothing, but document it.
590 ...
591 ... No, really, it doesn't do anything.
592 ... """
593 ... pass
594 ...
Guido van Rossum0616b792007-08-31 03:25:11 +0000595 >>> print(my_function.__doc__)
Georg Brandl116aa622007-08-15 14:28:22 +0000596 Do nothing, but document it.
597
598 No, really, it doesn't do anything.
599
600
601
602.. rubric:: Footnotes
603
604.. [#] Actually, *call by object reference* would be a better description, since if a
605 mutable object is passed, the caller will see any changes the callee makes to it
606 (items inserted into a list).
607