@@ -19,13 +19,13 @@ example::
1919 >>> x = int(input("Please enter an integer: "))
2020 >>> if x < 0:
2121 ... x = 0
22- ... print 'Negative changed to zero'
22+ ... print( 'Negative changed to zero')
2323 ... elif x == 0:
24- ... print 'Zero'
24+ ... print( 'Zero')
2525 ... elif x == 1:
26- ... print 'Single'
26+ ... print( 'Single')
2727 ... else:
28- ... print 'More'
28+ ... print( 'More')
2929 ...
3030
3131There can be zero or more :keyword: `elif ` parts, and the :keyword: `else ` part is
@@ -45,7 +45,6 @@ to avoid excessive indentation. An :keyword:`if` ... :keyword:`elif` ...
4545
4646.. index ::
4747 statement: for
48- statement: for
4948
5049The :keyword: `for ` statement in Python differs a bit from what you may be used
5150to in C or Pascal. Rather than always iterating over an arithmetic progression
@@ -62,7 +61,7 @@ they appear in the sequence. For example (no pun intended):
6261 >>> # Measure some strings:
6362 ... a = ['cat', 'window', 'defenestrate']
6463 >>> for x in a:
65- ... print x, len(x)
64+ ... print( x, len(x) )
6665 ...
6766 cat 3
6867 window 6
@@ -87,37 +86,68 @@ The :func:`range` Function
8786==========================
8887
8988If you do need to iterate over a sequence of numbers, the built-in function
90- :func: `range ` comes in handy. It generates lists containing arithmetic
91- progressions::
89+ :func: `range ` comes in handy. It generates arithmetic progressions::
90+
91+
92+ >>> for i in range(5):
93+ ... print(i)
94+ ...
95+ 0
96+ 1
97+ 2
98+ 3
99+ 4
100+
92101
93- >>> range(10)
94- [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
95102
96103The given end point is never part of the generated list; ``range(10) `` generates
97- a list of 10 values, the legal indices for items of a sequence of length 10. It
104+ 10 values, the legal indices for items of a sequence of length 10. It
98105is possible to let the range start at another number, or to specify a different
99106increment (even negative; sometimes this is called the 'step')::
100107
101- >>> range(5, 10)
102- [5, 6, 7, 8, 9]
103- >>> range(0, 10, 3)
104- [0, 3, 6, 9]
105- >>> range(-10, -100, -30)
106- [-10, -40, -70]
108+ 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
107116
108117To iterate over the indices of a sequence, combine :func: `range ` and :func: `len `
109118as follows::
110119
111120 >>> a = ['Mary', 'had', 'a', 'little', 'lamb']
112121 >>> for i in range(len(a)):
113- ... print i, a[i]
122+ ... print( i, a[i])
114123 ...
115124 0 Mary
116125 1 had
117126 2 a
118127 3 little
119128 4 lamb
120129
130+ A strange thing happens if you just print a range::
131+
132+ >>> print(range(10))
133+ range(0, 10)
134+
135+ In many ways the object returned by :func: `range ` behaves as if it is a list,
136+ but in fact it isn't. It is an object which returns the successive items of
137+ the desired sequence when you iterate over it, but it doesn't really make
138+ the list, thus saving space.
139+
140+ We say such an object is *iterable *, that is, suitable as a target for
141+ functions and constructs that expect something from which they can
142+ obtain successive items until the supply is exhausted. We have seen that
143+ the :keyword: `for ` statement is such an *iterator *. The function :func: `list `
144+ is another; it creates lists from iterables::
145+
146+
147+ >>> list(range(5))
148+ [0, 1, 2, 3, 4]
149+
150+ Later we will see more functions that return iterables and take iterables as argument.
121151
122152.. _tut-break :
123153
@@ -139,11 +169,11 @@ following loop, which searches for prime numbers::
139169 >>> for n in range(2, 10):
140170 ... for x in range(2, n):
141171 ... if n % x == 0:
142- ... print n, 'equals', x, '*', n/x
172+ ... print( n, 'equals', x, '*', n/x)
143173 ... break
144174 ... else:
145175 ... # loop fell through without finding a factor
146- ... print n, 'is a prime number'
176+ ... print( n, 'is a prime number')
147177 ...
148178 2 is a prime number
149179 3 is a prime number
@@ -180,8 +210,9 @@ boundary::
180210 ... """Print a Fibonacci series up to n."""
181211 ... a, b = 0, 1
182212 ... while b < n:
183- ... print b,
213+ ... print(b,end=' ')
184214 ... a, b = b, a+b
215+ ... print()
185216 ...
186217 >>> # Now call the function we just defined:
187218 ... fib(2000)
@@ -237,7 +268,7 @@ This value is called ``None`` (it's a built-in name). Writing the value
237268``None `` is normally suppressed by the interpreter if it would be the only value
238269written. You can see it if you really want to::
239270
240- >>> print fib(0)
271+ >>> print( fib(0) )
241272 None
242273
243274It is simple to write a function that returns a list of the numbers of the
@@ -299,7 +330,7 @@ defined to allow. For example::
299330 if ok in ('n', 'no', 'nop', 'nope'): return False
300331 retries = retries - 1
301332 if retries < 0: raise IOError, 'refusenik user'
302- print complaint
333+ print( complaint)
303334
304335This function can be called either like this: ``ask_ok('Do you really want to
305336quit?') `` or like this: ``ask_ok('OK to overwrite the file?', 2) ``.
@@ -313,7 +344,7 @@ The default values are evaluated at the point of function definition in the
313344 i = 5
314345
315346 def f(arg=i):
316- print arg
347+ print( arg)
317348
318349 i = 6
319350 f()
@@ -329,9 +360,9 @@ arguments passed to it on subsequent calls::
329360 L.append(a)
330361 return L
331362
332- print f(1)
333- print f(2)
334- print f(3)
363+ print( f(1) )
364+ print( f(2) )
365+ print( f(3) )
335366
336367This will print ::
337368
@@ -358,10 +389,10 @@ Functions can also be called using keyword arguments of the form ``keyword =
358389value ``. For instance, the following function::
359390
360391 def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
361- print "-- This parrot wouldn't", action,
362- print "if you put", voltage, "volts through it."
363- print "-- Lovely plumage, the", type
364- print "-- It's", state, "!"
392+ 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, "!")
365396
366397could be called in any of the following ways::
367398
@@ -401,13 +432,13 @@ list. (``*name`` must occur before ``**name``.) For example, if we define a
401432function like this::
402433
403434 def cheeseshop(kind, *arguments, **keywords):
404- print "-- Do you have any", kind, '?'
405- print "-- I'm sorry, we're all out of", kind
435+ print( "-- Do you have any", kind, '?')
436+ print( "-- I'm sorry, we're all out of", kind)
406437 for arg in arguments: print arg
407- print '-'*40
438+ print( '-'*40)
408439 keys = keywords.keys()
409440 keys.sort()
410- for kw in keys: print kw, ':', keywords[kw]
441+ for kw in keys: print( kw, ':', keywords[kw])
411442
412443It could be called like this::
413444
@@ -446,6 +477,20 @@ arguments may occur. ::
446477 def fprintf(file, format, *args):
447478 file.write(format % args)
448479
480+
481+ Normally, these ``variadic `` arguments will be last in the list of formal
482+ parameters, because they scoop up all remaining input arguments that are
483+ passed to the function. Any formal parameters which occur after the ``*args ``
484+ parameter are 'keyword-only' arguments, meaning that they can only be used as
485+ keywords rather than positional arguments.::
486+
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'
449494
450495.. _tut-unpacking-arguments :
451496
@@ -459,19 +504,19 @@ arguments. For instance, the built-in :func:`range` function expects separate
459504function call with the ``* ``\ -operator to unpack the arguments out of a list
460505or tuple::
461506
462- >>> range(3, 6) # normal call with separate arguments
507+ >>> list( range(3, 6)) # normal call with separate arguments
463508 [3, 4, 5]
464509 >>> args = [3, 6]
465- >>> range(*args) # call with arguments unpacked from a list
510+ >>> list( range(*args) ) # call with arguments unpacked from a list
466511 [3, 4, 5]
467512
468513In the same fashion, dictionaries can deliver keyword arguments with the ``** ``\
469514-operator::
470515
471516 >>> def parrot(voltage, state='a stiff', action='voom'):
472- ... print "-- This parrot wouldn't", action,
473- ... print "if you put", voltage, "volts through it.",
474- ... print "E's", state, "!"
517+ ... print( "-- This parrot wouldn't", action,end=' ')
518+ ... print( "if you put", voltage, "volts through it.", end=' ')
519+ ... print( "E's", state, "!")
475520 ...
476521 >>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
477522 >>> parrot(**d)
@@ -512,8 +557,8 @@ Documentation Strings
512557 single: documentation strings
513558 single: strings, documentation
514559
515- There are emerging conventions about the content and formatting of documentation
516- strings.
560+ Here are some conventions about the content and formatting of documentation
561+ strings.
517562
518563The first line should always be a short, concise summary of the object's
519564purpose. For brevity, it should not explicitly state the object's name or type,
@@ -547,7 +592,7 @@ Here is an example of a multi-line docstring::
547592 ... """
548593 ... pass
549594 ...
550- >>> print my_function.__doc__
595+ >>> print( my_function.__doc__)
551596 Do nothing, but document it.
552597
553598 No, really, it doesn't do anything.
0 commit comments