blob: 5d815d6004b7b2cd4d0796abcc705c04b8b07ce1 [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
Georg Brandl9afde1c2007-11-01 20:32:30 +0000269written. You can see it if you really want to using :keyword:`print`::
Georg Brandl116aa622007-08-15 14:28:22 +0000270
Georg Brandl9afde1c2007-11-01 20:32:30 +0000271 >>> fib(0)
Guido van Rossum0616b792007-08-31 03:25:11 +0000272 >>> print(fib(0))
Georg Brandl116aa622007-08-15 14:28:22 +0000273 None
274
275It is simple to write a function that returns a list of the numbers of the
276Fibonacci series, instead of printing it::
277
278 >>> def fib2(n): # return Fibonacci series up to n
279 ... """Return a list containing the Fibonacci series up to n."""
280 ... result = []
281 ... a, b = 0, 1
282 ... while b < n:
283 ... result.append(b) # see below
284 ... a, b = b, a+b
285 ... return result
286 ...
287 >>> f100 = fib2(100) # call it
288 >>> f100 # write the result
289 [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
290
291This example, as usual, demonstrates some new Python features:
292
293* The :keyword:`return` statement returns with a value from a function.
294 :keyword:`return` without an expression argument returns ``None``. Falling off
295 the end of a procedure also returns ``None``.
296
297* The statement ``result.append(b)`` calls a *method* of the list object
298 ``result``. A method is a function that 'belongs' to an object and is named
299 ``obj.methodname``, where ``obj`` is some object (this may be an expression),
300 and ``methodname`` is the name of a method that is defined by the object's type.
301 Different types define different methods. Methods of different types may have
302 the same name without causing ambiguity. (It is possible to define your own
303 object types and methods, using *classes*, as discussed later in this tutorial.)
304 The method :meth:`append` shown in the example is defined for list objects; it
305 adds a new element at the end of the list. In this example it is equivalent to
306 ``result = result + [b]``, but more efficient.
307
308
309.. _tut-defining:
310
311More on Defining Functions
312==========================
313
314It is also possible to define functions with a variable number of arguments.
315There are three forms, which can be combined.
316
317
318.. _tut-defaultargs:
319
320Default Argument Values
321-----------------------
322
323The most useful form is to specify a default value for one or more arguments.
324This creates a function that can be called with fewer arguments than it is
325defined to allow. For example::
326
Georg Brandl116aa622007-08-15 14:28:22 +0000327 def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
328 while True:
Georg Brandle9af2842007-08-17 05:54:09 +0000329 ok = input(prompt)
Georg Brandl116aa622007-08-15 14:28:22 +0000330 if ok in ('y', 'ye', 'yes'): return True
331 if ok in ('n', 'no', 'nop', 'nope'): return False
332 retries = retries - 1
Collin Winter58721bc2007-09-10 00:39:52 +0000333 if retries < 0:
334 raise IOError('refusenik user')
Guido van Rossum0616b792007-08-31 03:25:11 +0000335 print(complaint)
Georg Brandl116aa622007-08-15 14:28:22 +0000336
337This function can be called either like this: ``ask_ok('Do you really want to
338quit?')`` or like this: ``ask_ok('OK to overwrite the file?', 2)``.
339
340This example also introduces the :keyword:`in` keyword. This tests whether or
341not a sequence contains a certain value.
342
343The default values are evaluated at the point of function definition in the
344*defining* scope, so that ::
345
346 i = 5
347
348 def f(arg=i):
Guido van Rossum0616b792007-08-31 03:25:11 +0000349 print(arg)
Georg Brandl116aa622007-08-15 14:28:22 +0000350
351 i = 6
352 f()
353
354will print ``5``.
355
356**Important warning:** The default value is evaluated only once. This makes a
357difference when the default is a mutable object such as a list, dictionary, or
358instances of most classes. For example, the following function accumulates the
359arguments passed to it on subsequent calls::
360
361 def f(a, L=[]):
362 L.append(a)
363 return L
364
Guido van Rossum0616b792007-08-31 03:25:11 +0000365 print(f(1))
366 print(f(2))
367 print(f(3))
Georg Brandl116aa622007-08-15 14:28:22 +0000368
369This will print ::
370
371 [1]
372 [1, 2]
373 [1, 2, 3]
374
375If you don't want the default to be shared between subsequent calls, you can
376write the function like this instead::
377
378 def f(a, L=None):
379 if L is None:
380 L = []
381 L.append(a)
382 return L
383
384
385.. _tut-keywordargs:
386
387Keyword Arguments
388-----------------
389
390Functions can also be called using keyword arguments of the form ``keyword =
391value``. For instance, the following function::
392
393 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000394 print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000395 print("if you put", voltage, "volts through it.")
396 print("-- Lovely plumage, the", type)
397 print("-- It's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000398
399could be called in any of the following ways::
400
401 parrot(1000)
402 parrot(action = 'VOOOOOM', voltage = 1000000)
403 parrot('a thousand', state = 'pushing up the daisies')
404 parrot('a million', 'bereft of life', 'jump')
405
406but the following calls would all be invalid::
407
408 parrot() # required argument missing
409 parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
410 parrot(110, voltage=220) # duplicate value for argument
411 parrot(actor='John Cleese') # unknown keyword
412
413In general, an argument list must have any positional arguments followed by any
414keyword arguments, where the keywords must be chosen from the formal parameter
415names. It's not important whether a formal parameter has a default value or
416not. No argument may receive a value more than once --- formal parameter names
417corresponding to positional arguments cannot be used as keywords in the same
418calls. Here's an example that fails due to this restriction::
419
420 >>> def function(a):
421 ... pass
422 ...
423 >>> function(0, a=0)
424 Traceback (most recent call last):
425 File "<stdin>", line 1, in ?
426 TypeError: function() got multiple values for keyword argument 'a'
427
428When a final formal parameter of the form ``**name`` is present, it receives a
429dictionary (see :ref:`typesmapping`) containing all keyword arguments except for
430those corresponding to a formal parameter. This may be combined with a formal
431parameter of the form ``*name`` (described in the next subsection) which
432receives a tuple containing the positional arguments beyond the formal parameter
433list. (``*name`` must occur before ``**name``.) For example, if we define a
434function like this::
435
436 def cheeseshop(kind, *arguments, **keywords):
Guido van Rossum0616b792007-08-31 03:25:11 +0000437 print("-- Do you have any", kind, '?')
438 print("-- I'm sorry, we're all out of", kind)
Georg Brandl116aa622007-08-15 14:28:22 +0000439 for arg in arguments: print arg
Guido van Rossum0616b792007-08-31 03:25:11 +0000440 print('-'*40)
Neal Norwitze0906d12007-08-31 03:46:28 +0000441 keys = sorted(keywords.keys())
Guido van Rossum0616b792007-08-31 03:25:11 +0000442 for kw in keys: print(kw, ':', keywords[kw])
Georg Brandl116aa622007-08-15 14:28:22 +0000443
444It could be called like this::
445
446 cheeseshop('Limburger', "It's very runny, sir.",
447 "It's really very, VERY runny, sir.",
448 client='John Cleese',
449 shopkeeper='Michael Palin',
450 sketch='Cheese Shop Sketch')
451
452and of course it would print::
453
454 -- Do you have any Limburger ?
455 -- I'm sorry, we're all out of Limburger
456 It's very runny, sir.
457 It's really very, VERY runny, sir.
458 ----------------------------------------
459 client : John Cleese
460 shopkeeper : Michael Palin
461 sketch : Cheese Shop Sketch
462
463Note that the :meth:`sort` method of the list of keyword argument names is
464called before printing the contents of the ``keywords`` dictionary; if this is
465not done, the order in which the arguments are printed is undefined.
466
467
468.. _tut-arbitraryargs:
469
470Arbitrary Argument Lists
471------------------------
472
473Finally, the least frequently used option is to specify that a function can be
474called with an arbitrary number of arguments. These arguments will be wrapped
475up in a tuple. Before the variable number of arguments, zero or more normal
476arguments may occur. ::
477
478 def fprintf(file, format, *args):
479 file.write(format % args)
480
Guido van Rossum0616b792007-08-31 03:25:11 +0000481
482Normally, these ``variadic`` arguments will be last in the list of formal
483parameters, because they scoop up all remaining input arguments that are
484passed to the function. Any formal parameters which occur after the ``*args``
485parameter are 'keyword-only' arguments, meaning that they can only be used as
Georg Brandle4ac7502007-09-03 07:10:24 +0000486keywords rather than positional arguments. ::
Guido van Rossum0616b792007-08-31 03:25:11 +0000487
488 >>> def concat(*args, sep="/"):
489 ... return sep.join(args)
490 ...
491 >>> concat("earth", "mars", "venus")
492 'earth/mars/venus'
493 >>> concat("earth", "mars", "venus", sep=".")
494 'earth.mars.venus'
Georg Brandl116aa622007-08-15 14:28:22 +0000495
496.. _tut-unpacking-arguments:
497
498Unpacking Argument Lists
499------------------------
500
501The reverse situation occurs when the arguments are already in a list or tuple
502but need to be unpacked for a function call requiring separate positional
503arguments. For instance, the built-in :func:`range` function expects separate
504*start* and *stop* arguments. If they are not available separately, write the
505function call with the ``*``\ -operator to unpack the arguments out of a list
506or tuple::
507
Guido van Rossum0616b792007-08-31 03:25:11 +0000508 >>> list(range(3, 6)) # normal call with separate arguments
Georg Brandl116aa622007-08-15 14:28:22 +0000509 [3, 4, 5]
510 >>> args = [3, 6]
Guido van Rossum0616b792007-08-31 03:25:11 +0000511 >>> list(range(*args)) # call with arguments unpacked from a list
Georg Brandl116aa622007-08-15 14:28:22 +0000512 [3, 4, 5]
513
514In the same fashion, dictionaries can deliver keyword arguments with the ``**``\
515-operator::
516
517 >>> def parrot(voltage, state='a stiff', action='voom'):
Georg Brandle4ac7502007-09-03 07:10:24 +0000518 ... print("-- This parrot wouldn't", action, end=' ')
Guido van Rossum0616b792007-08-31 03:25:11 +0000519 ... print("if you put", voltage, "volts through it.", end=' ')
520 ... print("E's", state, "!")
Georg Brandl116aa622007-08-15 14:28:22 +0000521 ...
522 >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
523 >>> parrot(**d)
524 -- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
525
526
527.. _tut-lambda:
528
529Lambda Forms
530------------
531
532By popular demand, a few features commonly found in functional programming
533languages like Lisp have been added to Python. With the :keyword:`lambda`
534keyword, small anonymous functions can be created. Here's a function that
535returns the sum of its two arguments: ``lambda a, b: a+b``. Lambda forms can be
536used wherever function objects are required. They are syntactically restricted
537to a single expression. Semantically, they are just syntactic sugar for a
538normal function definition. Like nested function definitions, lambda forms can
539reference variables from the containing scope::
540
541 >>> def make_incrementor(n):
542 ... return lambda x: x + n
543 ...
544 >>> f = make_incrementor(42)
545 >>> f(0)
546 42
547 >>> f(1)
548 43
549
550
551.. _tut-docstrings:
552
553Documentation Strings
554---------------------
555
556.. index::
557 single: docstrings
558 single: documentation strings
559 single: strings, documentation
560
Guido van Rossum0616b792007-08-31 03:25:11 +0000561Here are some conventions about the content and formatting of documentation
562strings.
Georg Brandl116aa622007-08-15 14:28:22 +0000563
564The first line should always be a short, concise summary of the object's
565purpose. For brevity, it should not explicitly state the object's name or type,
566since these are available by other means (except if the name happens to be a
567verb describing a function's operation). This line should begin with a capital
568letter and end with a period.
569
570If there are more lines in the documentation string, the second line should be
571blank, visually separating the summary from the rest of the description. The
572following lines should be one or more paragraphs describing the object's calling
573conventions, its side effects, etc.
574
575The Python parser does not strip indentation from multi-line string literals in
576Python, so tools that process documentation have to strip indentation if
577desired. This is done using the following convention. The first non-blank line
578*after* the first line of the string determines the amount of indentation for
579the entire documentation string. (We can't use the first line since it is
580generally adjacent to the string's opening quotes so its indentation is not
581apparent in the string literal.) Whitespace "equivalent" to this indentation is
582then stripped from the start of all lines of the string. Lines that are
583indented less should not occur, but if they occur all their leading whitespace
584should be stripped. Equivalence of whitespace should be tested after expansion
585of tabs (to 8 spaces, normally).
586
587Here is an example of a multi-line docstring::
588
589 >>> def my_function():
590 ... """Do nothing, but document it.
591 ...
592 ... No, really, it doesn't do anything.
593 ... """
594 ... pass
595 ...
Guido van Rossum0616b792007-08-31 03:25:11 +0000596 >>> print(my_function.__doc__)
Georg Brandl116aa622007-08-15 14:28:22 +0000597 Do nothing, but document it.
598
599 No, really, it doesn't do anything.
600
601
602
603.. rubric:: Footnotes
604
605.. [#] Actually, *call by object reference* would be a better description, since if a
606 mutable object is passed, the caller will see any changes the callee makes to it
607 (items inserted into a list).
608