Commit 681c5632 authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading
+22 −0
Changes for LP3E-examples/README.txt: 22 added lines, 0 removed lines.
Original line number Diff line number Diff line
This is the distribution package for source-code examples in the book 
Learning Python 3rd Edition (October, 2007).

Here, you will find one text file per book chapter, containing all the 
source code in that chapter.
  
Almost all the code in this book is short code snippets shown running 
at the interactive prompt, rather than named source files.  Because of 
that, all the code in a chapter is collected in a single file, whether
it is run interactively or not.  If a code section is listed as a file 
in the book, its name is given as a comment; cut and paste its code from
the chapter's file into a text editor to save as a separate file.

These files may work best when used sequentially, along with the book 
itself.  To find specific code at random, try a text search within the 
chapter's file. 

For more book details, see:

    http://www.rmi.net/~lutz/about-lp3e.html

--Mark Lutz, November 26, 2007
+1598 −0

File added.

Preview size limit exceeded, changes collapsed.

+4 −0
Changes for LP3E-examples/chapter02.txt: 4 added lines, 0 removed lines.
Original line number Diff line number Diff line
# script1.py

print 'hello world'
print 2 ** 100
+97 −0
Changes for LP3E-examples/chapter03.txt: 97 added lines, 0 removed lines.
Original line number Diff line number Diff line
% python
>>> print 'Hello world!'
Hello world!
>>> print 2 ** 8
256



>>> lumberjack = 'okay'   
>>> lumberjack
'okay'
>>> 2 ** 8
256
>>>                      use Ctrl-D or Ctrl-Z to exit
%



# spam.py
print 2 ** 8                              # Raise to a power.
print 'the bright side ' + 'of life'      # + means concatenation.



#!/usr/local/bin/python
print 'The Bright Side of Life...'         # filename: brian



# script4.py
# A comment
import sys
print sys.platform
print 2 ** 100



# script4.py, revised
# A comment
import sys
print sys.platform
print 2 ** 100
raw_input()             # ADDED



>>> import script4
win32
1267650600228229401496703205376
>>> import script4
>>> import script4
>>> reload(script4)
win32
65536
<module 'script4' from 'script4.py'>



# myfile.py
title = "The Meaning of Life"



% python                        # Start Python.
>>> import myfile               # Run file; load module as a whole.
>>> print myfile.title          # Use its attribute names: `.' to qualify.
The Meaning of Life

% python                        # Start Python.
>>> from myfile import title    # Run file; copy its names.
>>> print title                 # Use name directly: no need to qualify.
The Meaning of Life



# threenames.py 
a = 'dead'          # Define three attributes.
b = 'parrot'        # Exported to other files
c = 'sketch'
print a, b, c       # Also used in this file



% python
>>> import threenames                  # Grab the whole module.
dead parrot sketch
>>>
>>> threenames.b, threenames.c
('parrot', 'sketch')
>>>
>>> from threenames import a, b, c     # Copy multiple names.
>>> b, c
('parrot', 'sketch')

>>> dir(threenames)
['__builtins__', '__doc__', '__file__', '__name__', 'a', 'b', 'c']
+559 −0
Changes for LP3E-examples/chapter04.txt: 559 added lines, 0 removed lines.
Original line number Diff line number Diff line

>>> 123 + 222                            # integer addition
345
>>> 1.5 * 4                              # floating-point multiplication
6.0
>>> 2 ** 100                             # 2 to the power 100
1267650600228229401496703205376L



>>> 3.1415 * 2                           # repr: as code
6.2830000000000004
>>> print 3.1415 * 2                     # str: user-friendly
6.283



>>> import math
>>> math.pi
3.1415926535897931
>>> math.sqrt(85)
9.2195444572928871



>>> import random
>>> random.random()
0.59268735266273953
>>> random.choice([1, 2, 3, 4])
1



>>> S = 'Spam'
>>> len(S)                              # length
4
>>> S[0]                                # the first item in S, indexing by zero-based position
'S'
>>> S[1]                                # the second from the left
'p'



>>> S[-1]                               # the last item from the end in S
'm'
>>> S[-2]                               # the second last from the end
'a'



>>> S[-1]                               # the last item in S
'm'
>>> S[len(S)-1]                         # negative indexing, the hard way
'm'



>>> S                  # a 4-character string
'Spam'
>>> S[1:3]             # slice of S from offsets 1 through 2 (not 3)
'pa'



>>> S[1:]              # everything past the first (1:len(S))
'pam'
>>> S                  # S itself hasnt changed
'Spam'
>>> S[0:3]             # everything but the last 
'Spa'
>>> S[:3]              # same as S[0:3]
'Spa'
>>> S[:-1]             # everything but the last again, but simpler (0:-1)
'Spa'
>>> S[:]               # all of S as a top-level copy (0:len(S))
'Spam'



>>> S
'Spam'
>>> S + 'xyz'                                 # concatenation
'Spamxyz'
>>> S                                         # S is unchanged
'Spam'
>>> S * 8                                     # repitition
'SpamSpamSpamSpamSpamSpamSpamSpam'



>>> S
'Spam'
>>> S[0] = 'z'                             # immutable objects canot be changed
error text omittted
TypeError: 'str' object does not support item assignment

>>> S = 'z' + S[1:]                        # but we can run expression to make new objects
>>> S
'zpam'



>>> S.find('pa')                   # find the offset of a substring
1
>>> S
'Spam'
>>> S.replace('pa', 'XYZ')        # replace occurrences of a substring with another
'SXYZm'
>>> S
'Spam'



>>> line = 'aaa,bbb,ccccc,dd'
>>> line.split(',')                       # split on a delimiter into a list of substrings
['aaa', 'bbb', 'ccccc', 'dd']

>>> S = 'spam'
>>> S.upper()                             # upper and lower case conversions
'SPAM'

>>> S.isalpha()                           # content tests: isalpha, isdigit,
True

>>> line = 'aaa,bbb,ccccc,dd\n'
>>> line = line.rstrip()                  # remove whitespace characters on the right side
>>> line
'aaa,bbb,ccccc,dd'



>>> dir(S)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', 
'__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', 
'__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', 
'__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', 
'__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 
'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 
'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper',
'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex',
'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith',
'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']



>>> help(S.index)
Help on built-in function index:

index(...)
    S.index(sub [,start [,end]]) -> int
    
    Like S.find() but raise ValueError when the substring is not found.



>>> S = 'A\nB\tC'         # \n is end-of-line, \t is tab
>>> len(S)                # each stands for just one character 
5

>>> ord('\n')             # \n is a byte with binary value 10 in ASCII
10

>>> S = 'A\0B\0C'         # \0, the binary zero byte, does not terminate the string
>>> len(S)
5



>>> msg = """
aaaaaaaaaaaaa
bbb'''bbbbbbbbbb""bbbbbbb'bbbb
cccccccccccccc"""

>>> msg
'\naaaaaaaaaaaaa\nbbb\'\'\'bbbbbbbbbb""bbbbbbb\'bbbb\ncccccccccccccc'



>>> import re
>>> match = re.match('Hello[ \t]*(.*)world', 'Hello    Python world')
>>> match.group(1)
'Python '



>>> match = re.match('/(.*)/(.*)/(.*)', '/usr/home/lumberjack')
>>> match.groups()
('usr', 'home', 'lumberjack')



>>> L = [123, 'spam', 1.23]         # a list of 3 different type objects
>>> len(L)                          # number of items in the list
3



>>> L[0]                            # indexing by position
123

>>> L[:-1]                          # slicing a list returns a new list
[123, 'spam']

>>> L + [4, 5, 6]                   # concatenation makes a new list too
[123, 'spam', 1.23, 4, 5, 6]

>>> L                               # were not changing the original list
[123, 'spam', 1.23]



>>> L.append('NI')                     # growing: add object at end of list
>>> L
[123, 'spam', 1.23, 'NI']

>>> L.pop(2)                           # shrinking: delete an item in the middle        
1.23
>>> L                                  # "del L[2]" deletes from a list too
[123, 'spam', 'NI']



>>> M = ['bb', 'aa', 'cc']
>>> M.sort()
>>> M
['aa', 'bb', 'cc']

>>> M.reverse()
>>> M
['cc', 'bb', 'aa']



>>> L
[123, 'spam', 'NI']

>>> L[99]
error text omitted
IndexError: list index out of range

>>> L[99] = 1
error text omitted
IndexError: list assignment index out of range



>>> M = [[1, 2, 3],              # a 3 x 3 matrix, as nested lists
         [4, 5, 6],
         [7, 8, 9]]
>>> M
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]



>>> M[1]                         # get row 2
[4, 5, 6]

>>> M[1][2]                      # get row 2, then get item 3 within the row
6



>>> col2 = [row[1] for row in M]               # collect the items in column 2
>>> col2
[2, 5, 8]
 
>>> M                                           # the matrix is unchanged
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] 



>>> [row[1] + 1 for row in M]                   # add 1 to each item in column 2
[3, 6, 9]

>>> [row[1] for row in M if row[1] % 2 == 0]    # filter out odd items
[2, 8]



>>> diag = [M[i][i] for i in [0, 1, 2]]         # collect a diagonal from matrix
>>> diag
[1, 5, 9]

>>> doubles = [c * 2 for c in 'spam']           # repeat characters in a string
>>> doubles
['ss', 'pp', 'aa', 'mm']



>>> D = {'food': 'Spam', 'quantity': 4, 'color': 'pink'}



>>> D['food']                          # fetch value of key food
'Spam'

>>> D['quantity'] += 1                 # add 1 to quantity value
>>> D
{'food': 'Spam', 'color': 'pink', 'quantity': 5} 



>>> D = {}
>>> D['name'] = 'Bob'                  # create keys by assignment
>>> D['job']  = 'dev'
>>> D['age']  = 40

>>> D
{'age': 40, 'job': 'dev', 'name': 'Bob'}

>>> print D['name']
Bob



>>> rec = {'name': {'first': 'Bob', 'last': 'Smith'},
           'job':  ['dev', 'mgr'],
           'age':  40.5}



>>> rec['name']                         # name is a nested dictionary
{'last': 'Smith', 'first': 'Bob'}

>>> rec['name']['last']                 # index the nested dictionary
'Smith'

>>> rec['job']                          # job is a nested list
['dev', 'mgr']

>>> rec['job'][-1]                      # index the nested list
'mgr'

>>> rec['job'].append('janitor')        # expane Bobs job description in-place
>>> rec
{'age': 40.5, 'job': ['dev', 'mgr', 'janitor'], 'name': {'last': 'Smith', 'first': 'Bob'}}



>>> rec = 0                  # now the prior objects space is reclaimed



>>> D = {'a': 1, 'b': 2, 'c': 3}
>>> D
{'a': 1, 'c': 3, 'b': 2}



>>> Ks = D.keys()                   # unordered keys list
>>> Ks
['a', 'c', 'b']

>>> Ks.sort()                       # sorted keys list
>>> Ks
['a', 'b', 'c']
 
>>> for key in Ks:                  # iterate though sorted keys
	    print key, '=>', D[key]
	
a => 1
b => 2
c => 3



>>> D
{'a': 1, 'c': 3, 'b': 2}

>>> for key in sorted(D):
        print key, '=>', D[key]

	
a => 1
b => 2
c => 3



>>> for c in 'spam':
	    print c.upper()

S
P
A
M



>>> squares = [x ** 2 for x in [1, 2, 3, 4, 5]]
>>> squares
[1, 4, 9, 16, 25]



>>> squares = []
>>> for x in [1, 2, 3, 4, 5]:                 # this is what a list comp does
        squares.append(x ** 2)

>>> squares
[1, 4, 9, 16, 25]



>>> D
{'a': 1, 'c': 3, 'b': 2}

>>> D['e'] = 99                           # assign new keys grows dictionaries
>>> D
{'a': 1, 'c': 3, 'b': 2, 'e': 99}

>>> D['f']                                # referencing one is an error
error text omitted
KeyError: 'f'



>>> D.has_key('f')
False

>>> if not D.has_key('f'):
        print 'missing'
	
missing



>>> T = (1, 2, 3, 4)                 # a 4-item tuple
>>> len(T)                           # length
4

>> T + (5, 6)                        # concatenation
(1, 2, 3, 4, 5, 6)

>>> T[0]                             # indexing, slicing, and more
1



>>> T[0] = 2                          # they are immutable
error text omitted
TypeError: 'tuple' object does not support item assignment



>>> f = open('data.txt', 'w')          # make a new file in output mode
>>> f.write('Hello\n')                 # write strings of bytes to it
>>> f.write('world\n')
>>> f.close()                          # close to flush outout buffers to disk



>>> f = open('data.txt')               # 'r' is the default processing mode
>>> bytes = f.read()                   # read entire file into a string
>>> bytes
'Hello\nworld\n'

>>> print bytes                        # print interprets control characters
Hello
world

>>> bytes.split()                      # file content is always a string 
['Hello', 'world']



>>> dir(file)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__', 
'__getattribute__', '__hash__', '__init__', '__iter__', '__new__', 
'__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 
'close', 'closed', 'encoding', 'fileno', 'flush', 'isatty', 'mode', 
'name', 'newlines', 'next', 'read', 'readinto', 'readline', 'readlines', 
'seek', 'softspace', 'tell', 'truncate', 'write', 'writelines', 'xreadlines']

>>> help(file.seek)
try it and see



>>> X = set('spam')
>>> Y = set(['h', 'a', 'm'])                        # make 2 sets out of sequences
>>> X, Y
(set(['a', 'p', 's', 'm']), set(['a', 'h', 'm']))
 
>>> X & Y                                           # intersection
set(['a', 'm'])

>>> X | Y                                           # union 
set(['a', 'p', 's', 'h', 'm'])

>>> X  Y                                           # difference
set(['p', 's'])



>>> import decimal                              # decimals
>>> d = decimal.Decimal('3.141')
>>> d + 1
Decimal("4.141")

>>> 1 > 2, 1 < 2                                # Booleans
(False, True)
>>> bool('spam')
True

>>> X = None                                    # None placeholder
>>> print X
None
>>> L = [None] * 100                            # initialize a list of 100 Nones
>>> L
[None, None, None, None, None, None, None, None, None, None, None, None, None, 
a list of 100 Nones]

>>> type(L)                                     # types
<type 'list'>
>>> type(type(L))                               # even types are objects
<type 'type'>



>>> if type(L) == type([]):          # type testing, if you must
	    print 'yes'
	
yes
>>> if type(L) == list:              # using the type name
	    print 'yes'
	
yes
>>> if isinstance(L, list):          # object oriented tests
 	    print 'yes'
	
yes



>>> class Worker:
        def __init__(self, name, pay):                # initialize when created
            self.name = name                          # self is the new object 
            self.pay  = pay                           
        def lastName(self):
            return self.name.split()[-1]              # split string on blanks
        def giveRaise(self, percent):
            self.pay *= (1.0 + percent)               # update pay in-place



>>> bob = Worker('Bob Smith', 50000)                  # make two instances
>>> sue = Worker('Sue Jones', 60000)                  # each has name and pay
>>> bob.lastName()                                    # call method: bob is self
'Smith'
>>> sue.lastName()                                    # sue is the self subject
'Jones'
>>> sue.giveRaise(.10)                                # updates sues pay
>>> sue.pay
66000.0



Loading