Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0616b79

Browse files
committed
Tutorial update for 3.0 by Paul Dubois.
I had to fix a few markup issues in controlflow.rst and modules.rst. There's a unicode issue on line 448 in introduction.rst that someone else needs to fix.
1 parent 8b2af27 commit 0616b79

12 files changed

Lines changed: 378 additions & 352 deletions

Doc/tutorial/classes.rst

Lines changed: 14 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,8 @@ multiple base classes, a derived class can override any methods of its base
1414
class or classes, and a method can call the method of a base class with the same
1515
name. Objects can contain an arbitrary amount of private data.
1616

17-
In C++ terminology, all class members (including the data members) are *public*,
17+
In C++ terminology, normally class members (including the data members) are
18+
*public* (except see below :ref:`tut-private`),
1819
and all member functions are *virtual*. There are no special constructors or
1920
destructors. As in Modula-3, there are no shorthands for referencing the
2021
object's members from its methods: the method function is declared with an
@@ -273,7 +274,7 @@ code will print the value ``16``, without leaving a trace::
273274
x.counter = 1
274275
while x.counter < 10:
275276
x.counter = x.counter * 2
276-
print x.counter
277+
print(x.counter)
277278
del x.counter
278279

279280
The other kind of instance attribute reference is a *method*. A method is a
@@ -308,7 +309,7 @@ object, and can be stored away and called at a later time. For example::
308309

309310
xf = x.f
310311
while True:
311-
print xf()
312+
print(xf())
312313

313314
will continue to print ``hello world`` until the end of time.
314315

@@ -621,11 +622,11 @@ following code will print B, C, D in that order::
621622
try:
622623
raise c()
623624
except D:
624-
print "D"
625+
print("D")
625626
except C:
626-
print "C"
627+
print("C")
627628
except B:
628-
print "B"
629+
print("B")
629630

630631
Note that if the except clauses were reversed (with ``except B`` first), it
631632
would have printed B, B, B --- the first matching except clause is triggered.
@@ -644,15 +645,15 @@ By now you have probably noticed that most container objects can be looped over
644645
using a :keyword:`for` statement::
645646

646647
for element in [1, 2, 3]:
647-
print element
648+
print(element)
648649
for element in (1, 2, 3):
649-
print element
650+
print(element)
650651
for key in {'one':1, 'two':2}:
651-
print key
652+
print(key)
652653
for char in "123":
653-
print char
654+
print(char)
654655
for line in open("myfile.txt"):
655-
print line
656+
print(line)
656657

657658
This style of access is clear, concise, and convenient. The use of iterators
658659
pervades and unifies Python. Behind the scenes, the :keyword:`for` statement
@@ -699,7 +700,7 @@ returns an object with a :meth:`__next__` method. If the class defines
699700
return self.data[self.index]
700701

701702
>>> for char in Reverse('spam'):
702-
... print char
703+
... print(char)
703704
...
704705
m
705706
a
@@ -724,7 +725,7 @@ create::
724725
yield data[index]
725726

726727
>>> for char in reverse('golf'):
727-
... print char
728+
... print(char)
728729
...
729730
f
730731
l

Doc/tutorial/controlflow.rst

Lines changed: 88 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -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

3131
There 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

5049
The :keyword:`for` statement in Python differs a bit from what you may be used
5150
to 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

8988
If 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

96103
The 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
98105
is possible to let the range start at another number, or to specify a different
99106
increment (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

108117
To iterate over the indices of a sequence, combine :func:`range` and :func:`len`
109118
as 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
238269
written. You can see it if you really want to::
239270

240-
>>> print fib(0)
271+
>>> print(fib(0))
241272
None
242273

243274
It 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

304335
This function can be called either like this: ``ask_ok('Do you really want to
305336
quit?')`` 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

336367
This will print ::
337368

@@ -358,10 +389,10 @@ Functions can also be called using keyword arguments of the form ``keyword =
358389
value``. 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

366397
could 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
401432
function 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

412443
It 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
459504
function call with the ``*``\ -operator to unpack the arguments out of a list
460505
or 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

468513
In 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

518563
The first line should always be a short, concise summary of the object's
519564
purpose. 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

Comments
 (0)