Contents
- Chapter 3.1 class average program with counter-controled repetition
- Chapter 3.2 Class average program with sentinel-controlled repetition
- Chapter 3.3 Analysis of examination results
- Chapter 4.1 Recursive factorial function
- Chapter 4.2 Recursive fibonacci function 0,1,1,2,3,5,8,13,21
- Chapter 5.1 Unpacking sequences
- Chapter 7.1 simple definition of class Time
- Chapter 7.2 Class Time with accessor methods
- Chapter 7.3 Class Time with default constructor
- Chapter 7.4 Class Employee with class attribute count
- Chapter 8.1 Representation of phone number in USA format: (xxx) xxx-xxxx
- Chapter 8.2 Class Time with customized attribute access
- Chapter 9.1 derived class inheriting from a base class
- Chapter 9.2 Overriding base-class methods
- Chapter 9.3 Creating a class hierarchy with an abstract base class
- Chapter 9.4 Class Employee with a static method
- Chapter 9.5 Class that defines method __getattribute__
- Chapter 9.6 simple class with slots
- Chapter 9.7 Class Time with properties
- Chapter 10.1 Label demonstration
- Chapter 10.2 Entry components and event binding demostration
- Chapter 10.3 Button demonstration
- Chapter 10.4 Checkbuttons demostration
- Chapter 10.5 Radiobuttons demonstration
- Chapter 10.6 Mouse events example
- Chapter 10.7 Binding keys to keyboard events
- Chapter 10.8 pack layout manager demonstration
- Chapter 10.9 Grid layout manager demonstration
- Chapter 10.10 Card shuffling and dealing program
- Chapter 11.1 ScrolledListBox used to select image
- Chapter 11.2 Copying selected text from one text area to another
- Chapter 11.3 MenuBars with Balloons demonstration
- Chapter 11.4 Popup menu demonstration
- Chapter 11.5 Canvas paint program
- Chapter 11.6 Scale used to control the size of a circle
- Chapter 12.1 Simple exception handling example
- Chapter 12.2 Demonstrating a programer-defined exception class
- Chapter 13.1 Searching string for a substring
- Chapter 13.2 Simple regular-expression example
- Chapter 13.3 Compiled regular-expression and match objects
- Chapter 13.4 Regular-expression string manipulation
- Chapter 13.5 Program that demonstrates grouping and greedy operations
- Chapter 14.1 Opening and writing to a file
- Chapter 14.2 Reading and printing a file
- Chapter 14.3 Credit inquiry program
- Chapter 14.4 Writing to shelve file
- Chapter 14.5 Reading shelve file
- Chapter 14.6 file operation
- Chapter 14.7 Opening and writing pickled object to file
- Chapter 14.8 Reading and printing pickled object in a file
- Chapter 16.1 making up a text file's data as XML
- Chapter 16.2 using 4DOM to traverse an XML Document
- Chapter 16.3 Using 4DOMto manipulate an XML Document
- Chapter 16.4 Demonstrating SAX-based parsing
- Chapter 17.1 Displays contents of the Authors table,ordered by a specified field
- Chapter 17.2 diaplay results returned by a query on a database
- Chapter 18.1 Using fork to create child processes
- Chapter 18.2 Demostrates the os.wait function
- Chapter 18.3 demostrates the waitpid function
- Chapter 18.4 Uses the system function to clear the screen
- Chapter 18.5 Opens a Web page in a system-specific editor
- Chapter 18.6 Demonstrating popen and popen2
- Chapter 18.7 Using os.pipe to communicate with a child process
- Chapter 18.8 Defining our own signal handler
- Chapter 18.9 Sending signals to child processes using kill
- Chapter 19.1 Multiple threads printing at different intervals
- Chapter 19.2 Multiple threads modifying shared object
- Chapter 19.3 Integer-producing class
- Chapter 19.4 Integer-consuming queue
- Chapter 19.5 Unsynchronized access to an integer
- Chapter 19.6 Multiple threads modifying shared object
- Chapter 19.7 Synchronized access to an integer with condition variable
- Chapter 20.1 Display the contents of a file from a Web server in a browse
- Chapter 20.2 server side socket program
- Chapter 20.3 client side socket program
- Chapter 20.4 receive packets from a client and send packets to a client
- Chapter 20.5 send packets to a server and receive packets from a server
- Chapter 21.1 Demostrating crypto system
- Chapter 22.1 Classes List and Node definitions
Chapter 3.1 class average program with counter-controled repetition
1 #chapter 3.1
2 #class average program with counter-controled repetition
3
4 #initialization phase
5 total = 0 #sum of grades
6 gradeCounter = 1 #number of grades entered
7
8 #processing phase
9 while gradeCounter <= 10:
10 grade = raw_input("Enter grade:")
11 grade = int(grade)
12 total = total + grade
13 gradeCounter = gradeCounter + 1
14
15 #termination phase
16 average = float(total) / 10 #covert integer to float
17 print "Class average is", average
Chapter 3.2 Class average program with sentinel-controlled repetition
1 #chapter3.2
2 #Class average program with sentinel-controlled repetition
3
4 #initialization phase
5 total = 0 #sum of grade
6 gradeCounter = 0 #number of grades entered
7
8 #processing phase
9 grade = raw_input("Enter grade,-1 to end:") #get one grade
10 grade = int(grade)
11
12 while grade !=-1:
13 total = total + grade
14 gradeCounter = gradeCounter + 1
15 grade = raw_input("Enter grade,-1 to end:")
16 grade = int(grade)
17
18 #termination phase
19 if gradeCounter != 0:
20 average = float(total) / gradeCounter
21 print "Class average is", average
22 else:
23 print "No grade were entered"
Chapter 3.3 Analysis of examination results
1 #chapter 3.3
2 #Analysis of examination results
3
4 #initialize variables
5 passes = 0
6 failures = 0
7 studentCounter = 1
8
9 #process 10 students
10 while studentCounter <= 10:
11 result = raw_input("Enter result(1=pass,2=fail):")
12 result = int(result)
13
14 if result == 1:
15 passes = passes + 1
16 else:
17 failures = failures + 1
18
19 studentCounter = studentCounter + 1
20
21 #termination phase
22 print "Passed", passes
23 print "Failed", failures
24
25 if passes > 8:
26 print "Raise tuition"
Chapter 4.1 Recursive factorial function
1 #chapter 4.1
2 #Recursive factorial function.
3
4 def factorial(number):
5 if number <=1:
6 return 1
7 else:
8 return number * factorial(number - 1) #recursive call
9
10 for i in range(11):
11 print "%2d! = %d" % (i, factorial(i))
Chapter 4.2 Recursive fibonacci function 0,1,1,2,3,5,8,13,21
1 #chapter4.2
2 #Recursive fibonacci function 0,1,1,2,3,5,8,13,21
3
4 def fibonacci(n):
5 if n == 0 or n == 1:
6 return n
7 else:
8 return fibonacci(n - 1) + fibonacci(n - 2)
9
10 number = int(raw_input("Enter the integer:"))
11
12 if number > 0:
13 result = fibonacci(number)
14 print "Fibonacci(%d) = %d" % (number, result)
15 else:
16 print "Cannot find the fibonacci of a negative number"
Chapter 5.1 Unpacking sequences
1 #chapter 5.1
2 #Unpacking sequences
3
4 #create sequences
5 aString = "abc"
6 aList = [1,2,3]
7 aTuple = ("a","b",1)
8
9 #unpacking sequences
10 print "unpacking string..."
11 first,second,third = aString
12 print "String values:", first,second,third
13
14 print "\nunpacking list..."
15 first,second,third = aList
16 print "List values:",first,second,third
17
18 print "\nunpacking tuple..."
19 first,second,third = aTuple
20 print "Tuple values:",first,second,third
21
22 #swapping two values
23 x = 3
24 y = 4
25
26 print "\nBefore swapping:x = %d,y = %d" % (x,y)
27 x,y = y,x #swapping variables
28 print "After swapping:x = %d, y = %d" % (x,y)
Chapter 7.1 simple definition of class Time
1 #chapter 7.1
2 #Simple definition of class Time.
3
4 class Time:
5 """Time abstract data type definition"""
6 def __init__(self):
7 """Initializes hour,minute and second to zero"""
8 self.hour = 0
9 self.minute = 0
10 self.second = 0
11
12 def printMilitray(self):
13 """Prints object of class Time in military format"""
14 print "%.2d:%.2d:%.2d" % (self.hour,self.minute,self.second)
15
16 def printStandard(self):
17 """Prints object of class Time in standard format"""
18
19 standardTime = ""
20
21 if self.hour == 0 or self.hour == 12:
22 standardTime += "12:"
23 else:
24 standardTime += "%d:" % (self.hour % 12)
25
26 standardTime += "%.2d:%.2d" % (self.minute,self.second)
27
28 if self.hour < 12:
29 standardTime += "AM"
30 else:
31 standardTime += "PM"
32
33 print standardTime
Chapter 7.2 Class Time with accessor methods
1 #chapter 7.2
2 #Class Time with accessor methods.
3
4 class Time:
5 """Class Time with accessor methods"""
6
7 def __init__(self):
8 """Time constructor initializes each data member to zero"""
9
10 self.__hour = 0 #private value,change to _Time__hour.
11 self._minute = 0 #public value
12 self._second = 0
13
14 def setTime(self,hour,minute,second):
15 """Set values of hour,minute,and second"""
16
17 self.setHour( hour )
18 self.setMinute( minute )
19 self.setSecond( second )
20
21 def setHour( self,hour):
22 """Set hour value"""
23
24 if 0 <= hour < 24:
25 self._hour = hour
26 else:
27 raise ValueError,"Invalid hour value: %d" % hour
28
29 def setMinute( self,minute ):
30 """Set minute value"""
31
32 if 0 <= minute < 60:
33 self._minute = minute
34 else:
35 raise ValueError,"Invalid minute value: %d" % minute
36
37 def setSecond ( self,second ):
38 """Set second value"""
39
40 if 0 <= senond <60:
41 self._second = second
42 else:
43 raise ValueError,"Invalid second value: %d" % second
44
45 def getHour( self ):
46 """Get hour value"""
47
48 return self._hour
49
50 def getMinute( self ):
51 """Get minute value"""
52
53 return self._minute
54
55 def getSecond( self ):
56 """Get second value"""
57
58 return self._second
59
60 def printMilitray(self):
61 """Prints object of class Time in military format"""
62 print "%.2d:%.2d:%.2d" % (self._hour,self._minute,self._second)
63
64 def printStandard(self):
65 """Prints object of class Time in standard format"""
66
67 standardTime = ""
68
69 if self._hour == 0 or self._hour == 12:
70 standardTime += "12:"
71 else:
72 standardTime += "%d:" % (self._hour % 12)
73
74 standardTime += "%.2d:%.2d" % (self._minute,self._second)
75
76 if self._hour < 12:
77 standardTime += "AM"
78 else:
79 standardTime += "PM"
80
81 print standardTime
Chapter 7.3 Class Time with default constructor
1 #chapter 7.3
2 #Class Time with default constructor.
3 #use private value
4
5 class Time:
6 """Class Time with accessor methods"""
7
8 def __init__(self, hour = 0, minute = 0, second = 0):
9 """Time constructor initializes each data member to zero"""
10
11 self.setTime( hour, minute, second )
12
13 def setTime(self, hour, minute, second):
14 """Set values of hour,minute,and second"""
15
16 self.setHour( hour )
17 self.setMinute( minute )
18 self.setSecond( second )
19
20 def setHour( self,hour):
21 """Set hour value"""
22
23 if 0 <= hour < 24:
24 self.__hour = hour
25 else:
26 raise ValueError,"Invalid hour value: %d" % hour
27
28 def setMinute( self,minute ):
29 """Set minute value"""
30
31 if 0 <= minute < 60:
32 self.__minute = minute
33 else:
34 raise ValueError,"Invalid minute value: %d" % minute
35
36 def setSecond ( self,second ):
37 """Set second value"""
38
39 if 0 <= senond <60:
40 self.__second = second
41 else:
42 raise ValueError,"Invalid second value: %d" % second
43
44 def getHour( self ):
45 """Get hour value"""
46
47 return self.__hour
48
49 def getMinute( self ):
50 """Get minute value"""
51
52 return self.__minute
53
54 def getSecond( self ):
55 """Get second value"""
56
57 return self.__second
58
59 def printMilitray(self):
60 """Prints object of class Time in military format"""
61 print "%.2d:%.2d:%.2d" % (self.__hour,self.__minute,self.__second)
62
63 def printStandard(self):
64 """Prints object of class Time in standard format"""
65
66 standardTime = ""
67
68 if self.__hour == 0 or self.__hour == 12:
69 standardTime += "12:"
70 else:
71 standardTime += "%d:" % (self.__hour % 12)
72
73 standardTime += "%.2d:%.2d" % (self.__minute,self.__second)
74
75 if self.__hour < 12:
76 standardTime += "AM"
77 else:
78 standardTime += "PM"
79
80 print standardTime
Chapter 7.4 Class Employee with class attribute count
1 #chapter 7.4
2 #Class Employee with class attribute count
3
4 class Employee:
5 """Represents an employee"""
6
7 count = 0 #class attribute
8
9 def __init__( self,first,last ):
10 """Initializes firstName,lastName and increments count"""
11
12 self.firstName = first
13 self.lastNmae = last
14
15 Employee.count += 1 #increment class attribute
16
17 print "Employee constructor for %s ,%s" % (self.lastNmae,self.firstName)
18
19 def __del__( self ):
20 """Decrements count and prints message"""
21
22 Employee.count -= 1 #decrement class attribute
23
24 print "Eemployee destructor for %s, %s" % ( self.lastNmae, self.firstName )
Chapter 8.1 Representation of phone number in USA format: (xxx) xxx-xxxx
1 #chapter 8.1
2 #Representation of phone number in USA format: (xxx) xxx-xxxx.
3
4 class PhoneNumber:
5 """Simple class to represent phone number in USA format"""
6
7 def __init__( self, number ):
8 """Accepts string in form (xxx) xxx-xxxx"""
9
10 self.areaCode = number[ 1:4 ] #3-digit area code
11 self.exchange = number[ 6:9 ] #3-digit exchange
12 self.line = number[ 10:14 ] #4-digit line
13
14 def __str__( self ):
15 """Informal string representation"""
16
17 return "(%s) %s-%s" % (self.areaCode, self.exchange, self.line)
18
19 def test():
20 newNumber = raw_input("Enter phone in the form(123) 456-7890:")
21 phone = PhoneNumber ( newNumber )
22 print "the phone number is:"
23 print phone #invokes phone.__str__()
24
25 if __name__ == "__main__":
26 test()
Chapter 8.2 Class Time with customized attribute access
1 #chapter8.2
2 #Class Time with customized attribute access.
3
4 class Time:
5 """Class Time with customized attribute access"""
6
7 def __init__( self, hour = 0, minute = 0, second = 0 ):
8 """Time constructor initializes each data member to zero"""
9
10 self.hour = hour #each statement invokes __setattr__
11 self.minute = minute
12 self.second = second
13
14 def __setattr__( self, name, value ):
15 """Assigns a value to an attribute"""
16
17 if name == "hour":
18 if 0 <= value < 24:
19 self.__dict__[ "_hour" ] = value
20 else:
21 raise ValueError, "Invalid hour value: %d" % value
22 elif name == "minute" or name == "second":
23 if 0 <= value < 60:
24 self.__dict__[ "_" + name ] = value
25 else:
26 raise ValueError, "Invalid %s value: %d" % ( name, value )
27 else:
28 self.__dict__[ name ] = value
29
30 def __getattr__( self, name ):
31 """Performs lookup for unrecognized attribute name"""
32
33 if name == "hour":
34 return self._hour
35 elif name == "minute":
36 return self._minute
37 elif name == "second":
38 return self._second
39 else:
40 raise AttributeError, name
41
42 def __str__( self ):
43 """Returns Time object string in military format"""
44
45 return "%.2d:%.2d:%.2d" % ( self._hour, self._minute,self._second )
Chapter 9.1 derived class inheriting from a base class
1 #chapter 9.1
2 #derived class inheriting from a base class.
3
4 import math
5
6 class Point:
7 """Class that represents geometric point"""
8
9 def __init__( self, xValue = 0, yValue = 0 ):
10 """Point constructor takes x and y coordinates"""
11
12 self.x = xValue
13 self.y = yValue
14
15 class Circle(Point):
16 """Class that repesents a circle"""
17
18 def __init__( self, x = 0, y = 0, radiusValue = 0.0 ):
19 """Circle constructor takes x and y coordinates of center point and radius"""
20
21 Point.__init__( self, x, y ) #call base-class constructor
22 self.radius = float( radiusValue )
23
24 def area ( self ):
25 """Computes area of a Circle"""
26
27 return math.pi * self.radius ** 2
28
29 #main program
30
31 #examine classes Point and Circle
32 print "Point bases:",Point.__bases__
33 print "Circle bases:",Circle.__bases__
34
35 #demonstrate class relationships with built-in function issubclass
36 print "\nCircle is a subclass of Point:", issubclass(Circle, Point)
37 print "Point is a subclass of Circle:", issubclass(Point, Circle)
38
39 point = Point(30,50) #create Point object
40 circle = Circle(120,89,2.7) #create Ci