Chapter 1 - Amazon S3

Python Essentials
Outline
1. Introduction.
2. Data Types and Expressions.
3. Control Statements.
4. Strings and Text Files.
5. Lists and Dictionaries.
6. Design With Functions.
7. Design with Classes.
Python Essentials
2
Python Essentials:
Chapter 1
Introduction
Objectives
After completing this chapter, you will be able to:
• Compose and run a simple Python program
Python Essentials
4
Getting Started with Python
Programming
• Guido van Rossum invented the Python
programming language in the early 1990s
• Python is a high-level, general-purpose
programming language for solving problems on
modern computer systems
• Useful resources at www.python.org
Python Essentials
5
Running Code in the Interactive Shell
• Python is an interpreted language
• Simple Python expressions and statements can be
run in the shell
– Easiest way to open a Python shell is to launch the
IDLE
– To quit, select the window’s close box or press
Control+D
– Shell is useful for:
• Experimenting with short expressions or statements to
learn new features of the language
• Consulting the documentation
Python Essentials
6
Running Code in the Interactive Shell
(continued)
Python Essentials
7
Input, Processing, and Output
• Programs usually accept inputs from a source,
process them, and output results to a destination
– In terminal-based interactive programs, these are
the keyboard and terminal display, respectively
Python Essentials
8
Input, Processing, and Output
(continued)
Python Essentials
9
Editing, Saving, and Running a Script
• We can then run Python program files or scripts
within IDLE or from the OS’s command prompt
– Run within IDLE using menu option, F5 (Windows),
or Control+F5 (Mac or Linux)
• Python program files use .py extension
• Running a script from IDLE allows you to construct
some complex programs, test them, and save them
in program libraries to reuse or share with others
Python Essentials
10
Editing, Saving, and Running a Script
(continued)
Python Essentials
11
Editing, Saving, and Running a Script
(continued)
Python Essentials
12
Behind the Scenes:
How Python Works
Python Essentials
13
Detecting and Correcting Syntax
Errors
• Programmers inevitably make typographical errors
when editing programs
– The Python interpreter will nearly always detect
these
– Such errors are called syntax errors
• Syntax: rules for forming sentences in a language
• When Python encounters a syntax error in a
program, it halts execution with an error message
Python Essentials
14
Detecting and Correcting Syntax
Errors (continued)
Python Essentials
15
Summary
• Fundamental ideas of computer science
– The algorithm
– Information processing
• Real computing agents can be constructed out of
hardware devices
– CPU, memory, and input and output devices
• Some real computers are specialized for a small
set of tasks, whereas a desktop or laptop computer
is a general-purpose problem-solving machine
Python Essentials
16
Summary (continued)
• Languages such as Python are high-level
• Interpreter translates a Python program to a lowerlevel form that can be executed on a real computer
• Python shell provides a command prompt for
evaluating and viewing the results of Python
expressions and statements
Python Essentials
17
Summary (continued)
• IDLE is an integrated development environment
that allows the programmer to save programs in
files and load them into a shell for testing
• Python scripts are programs that are saved in files
and run from a terminal command prompt
• When a Python program is executed, it is
translated into byte code
– Sent to PVM for further interpretation and execution
• Syntax: set of rules for forming correct expressions
and statements in a programming language
Python Essentials
18
Python Essentials:
Chapter 2
Software Development, Data Types, and
Expressions
Objectives
After completing this chapter, you will be able to:
• Describe the basic phases of software
development: analysis, design, coding, and testing
• Use strings for the terminal input and output of text
• Use integers and floating point numbers in
arithmetic operations
• Construct arithmetic expressions
• Initialize and use variables with appropriate names
Python Essentials
20
Objectives (continued)
• Import functions from library modules
• Call functions with arguments and use returned
values appropriately
• Construct a simple Python program that performs
inputs, calculations, and outputs
• Use docstrings to document Python programs
Python Essentials
21
The Software Development Process
• Software development: process of planning and
organizing a program
– Several approaches; one is the waterfall model
• Modern software development is usually
incremental and iterative
– Analysis and design may produce a prototype of a
system for coding, and then back up to earlier
phases to fill in more details after some testing
Python Essentials
22
The Software Development Process
(continued)
Python Essentials
23
The Software Development Process
(continued)
• Programs rarely work as hoped the first time they
are run
– Must perform extensive and careful testing
Python Essentials
24
The Software Development Process
(continued)
Python Essentials
25
The Software Development Process
(continued)
• The cost of developing software is not spread
equally over the phases
Python Essentials
26
The Software Development Process
(continued)
Python Essentials
27
Strings, Assignment, and Comments
• Text processing is by far the most common
application of computing
– E-mail, text messaging, Web pages, and word
processing all rely on and manipulate data
consisting of strings of characters
Python Essentials
28
Data Types
• A data type consists of a set of values and a set of
operations that can be performed on those values
• A literal is the way a value of a data type looks to a
programmer
• int, long, and float, are numeric data types
Python Essentials
29
Data Types (continued)
Python Essentials
30
String Literals
• In Python, a string literal is a sequence of characters
enclosed in single or double quotation marks
• '' and "" represent the empty string
• Use ''' and """ for multi-line paragraphs
Python Essentials
31
Escape Sequences
• The newline character \n is called an escape
sequence
Python Essentials
32
String Concatenation
• You can join two or more strings to form a new
string using the concatenation operator +
• The * operator allows you to build a string by
repeating another string a given number of times
Python Essentials
33
Variables and the Assignment
Statement
• A variable associates a name with a value
– Makes it easy to remember and use later in program
• Variable naming rules:
– Reserved words cannot be used as variable names
• Examples: if, def, and import
– Name must begin with a letter or _
– Name can contain any number of letters, digits, or _
– Names are case sensitive
• Example: WEIGHT is different from weight
– Tip: use “camel casing” (Example: interestRate)
Python Essentials
34
Variables and the Assignment
Statement (continued)
• Programmers use all uppercase letters for
symbolic constants
– Examples: TAX_RATE and STANDARD_DEDUCTION
• Variables receive initial values and can be reset to
new values with an assignment statement
<variable name> = <expression>
– Subsequent uses of the variable name in
expressions are known as variable references
Python Essentials
35
Program Comments and Docstrings
• Docstring example:
• End-of-line comment example:
Python Essentials
36
Numeric Data Types and Character
Sets
• The first applications of computers were to crunch
numbers
• The use of numbers in many applications is still
very important
Python Essentials
37
Integers and Long Integers
• In real life, the range of integers is infinite
• A computer’s memory places a limit on magnitude
of the largest positive and negative integers
– Python’s int typical range: –231 to 231 – 1
• Integer literals are written without commas
• When value of integer exceeds int limits, Python
automatically uses long data type to represent it
Python Essentials
38
Floating-Point Numbers
• Python uses floating-point numbers to represent
real numbers
• Python’s float typical range: –10308 to 10308 and
• Typical precision: 16 digits
Python Essentials
39
Floating-Point Numbers (continued)
Python Essentials
40
Character Sets
Python Essentials
41
Character Sets (continued)
• In Python, character literals look just like string
literals and are of the string type
– They belong to several different character sets,
among them the ASCII set and the Unicode set
• ASCII character set maps to set of integers
• ord and chr convert characters to and from ASCII
Python Essentials
42
Expressions
• A literal evaluates to itself
• A variable reference evaluates to the variable’s
current value
• Expressions provide easy way to perform
operations on data values to produce other values
• When entered at Python shell prompt, expression’s
operands are evaluated and its operator is then
applied to these values to compute the value of the
expression
Python Essentials
43
Arithmetic Expressions
• An arithmetic expression consists of operands
and operators combined in a manner that is
already familiar to you from learning algebra
Python Essentials
44
Arithmetic Expressions (continued)
• Precedence rules:
–
–
–
–
–
** has the highest precedence and is evaluated first
Unary negation is evaluated next
*, /, and % are evaluated before + and + and - are evaluated before =
With two exceptions, operations of equal
precedence are left associative, so they are
evaluated from left to right
• ** and = are right associative
– You can use () to change the order of evaluation
Python Essentials
45
Arithmetic Expressions (continued)
• 45%0 is a semantic error
Python Essentials
46
Arithmetic Expressions (continued)
• When both operands of an expression are of the
same numeric type, resulting value is of that type
– Unless combination of two ints is large enough to
produce a long
• When each operand is of a different type, the
resulting value is of the more general type
– Example: 3 / 4 is 0, whereas 3 / 4.0 is .75
• For multi-line expressions, use a \
Python Essentials
47
Mixed-Mode Arithmetic and Type
Conversions
• Mixed-mode arithmetic involves integers and
floating-point numbers:
3.14 * 3 ** 2
• Mixed-mode arithmetic can be problematic:
3 / 2 * 5.0 yields 1 * 5.0, which yields 5.0
3 / 2.0 * 5 yields 1.5 * 5, which yields 7.5
• Solution:
– Place a .0 after the relevant integer literals
– Use a type conversion function with variables:
3 / float(someInteger) * 5.0
Python Essentials
48
Mixed-Mode Arithmetic and Type
Conversions (continued)
Python Essentials
49
Mixed-Mode Arithmetic and Type
Conversions (continued)
• Note that the int function converts a float to an
int by truncation, not by rounding
Python Essentials
50
Mixed-Mode Arithmetic and Type
Conversions (continued)
• Type conversion also occurs in the construction of
strings from numbers and other strings
• Solution: use str function
• Python is a strongly typed programming language
Python Essentials
51
Using Functions and Modules
• Python includes many useful functions, which are
organized in libraries of code called modules
Python Essentials
52
Calling Functions: Arguments and
Return Values
• A function is chunk of code that can be called by
name to perform a task
• Functions often require arguments or parameters
– Arguments may be optional or required
• When function completes its task, it may return a
value back to the part of the program that called it
Python Essentials
53
The math Module
• To use a resource from a module, you write the
name of a module as a qualifier, followed by a dot
(.) and the name of the resource
– Example: math.pi
Python Essentials
54
The math Module (continued)
• You can avoid the use of the qualifier with each
reference by importing the individual resources
• You may import all of a module’s resources to use
without the qualifier
– Example: from math import *
Python Essentials
55
The Main Module
• In the case study, earlier in this chapter, we
showed how to write documentation for a Python
script
• To differentiate this script from the other modules in
a program, we call it the main module
– Like any module, the main module can be imported
Python Essentials
56
The Main Module (continued)
Python Essentials
57
Program Format and Structure
• Start with comment with author’s name, purpose of
program, and other relevant information
– In the form of a docstring
• Then, include statements that:
– Import any modules needed by program
– Initialize important variables, suitably commented
– Prompt the user for input data and save the input
data in variables
– Process the inputs to produce the results
– Display the results
Python Essentials
58
Running a Script from a Terminal
Command Prompt
Python Essentials
59
Running a Script from a Terminal
Command Prompt (continued)
Python Essentials
60
Running a Script from a Terminal
Command Prompt (continued)
• Python installations enable you to launch Python
scripts by double-clicking the files from the OS’s file
browser
– May require .py file type to be set
– Fly-by-window problem: Window will close
automatically
• Solution: Add an input statement at end of script that
pauses until the user presses the enter or return key
Python Essentials
61
Summary
• Waterfall model describes software development
process in terms of several phases
• Literals are data values that can appear in program
• The string data type is used to represent text for
input and output
• Escape characters begin with backslash and
represent special characters such as delete key
• A docstring is string enclosed by triple quotation
marks and provides program documentation
Python Essentials
62
Summary (continued)
• Comments are pieces of code not evaluated by the
interpreter but can be read by programmers to
obtain information about a program
• Variables are names that refer to values
• Some data types: int, long, and float
• Arithmetic operators are used to form arithmetic
expressions
– Operators are ranked in precedence
• Mixed-mode operations involve operands of
different numeric data types
Python Essentials
63
Summary (continued)
• A function call consists of a function’s name and its
arguments or parameters
– May return a result value to the caller
• Python is a strongly typed language
• A module is a set of resources
– Can be imported
• A semantic error occurs when the computer cannot
perform the requested operation
• A logic error produces incorrect results
Python Essentials
64
Python Essentials:
Chapter 3
Control Statements
Objectives
After completing this chapter, you will be able to:
• Write a loop to repeat a sequence of actions a fixed
number of times
• Write a loop to traverse the sequence of characters
in a string
• Write a loop that counts down and a loop that
counts up
• Write an entry-controlled loop that halts when a
condition becomes false
Python Essentials
66
Objectives (continued)
• Use selection statements to make choices in a
program
• Construct appropriate conditions for conditioncontrolled loops and selection statements
• Use logical operators to construct compound
Boolean expressions
• Use a selection statement and a break statement
to exit a loop that is not entry-controlled
Python Essentials
67
Definite Iteration: The for Loop
• Repetition statements (or loops) repeat an action
• Each repetition of action is known as pass or
iteration
• Two types of loops
– Those that repeat action a predefined number of
times (definite iteration)
– Those that perform action until program determines
it needs to stop (indefinite iteration)
Python Essentials
68
Executing a Statement a Given
Number of Times
• Python’s for loop is control statement that most
easily supports definite iteration
• The form of this type of loop is:
loop header
loop body
statements in body must be indented and aligned in the same column
Python Essentials
69
Executing a Statement a Given
Number of Times (continued)
• Example: Loop to compute an exponentiation for a
non-negative exponent
– If the exponent were 0, the loop body would not
execute and value of product would remain as 1
Python Essentials
70
Count-Controlled Loops
• Loops that count through a range of numbers
• To specify a explicit lower bound:
Python Essentials
71
Count-Controlled Loops (continued)
• Here is the form of this version of the for loop:
• Example: bound-delimited summation
Python Essentials
72
Augmented Assignment
• Augmented assignment operations:
• Format:
Equivalent to:
Python Essentials
73
Loop Errors: Off-by-One Error
• Example:
Loop actually counts from 1 through 3
• This is not a syntax error, but rather a logic error
Python Essentials
74
Traversing the Contents of a Data
Sequence
• range returns a list
• Strings are also sequences of characters
• Values in a sequence can be visited with a for loop:
• Example:
Python Essentials
75
Specifying the Steps in the Range
• xrange and range expect a third argument that
allows you specify a step value
• Example in a loop:
Python Essentials
76
Loops That Count Down
• Example:
Python Essentials
77
Formatting Text for Output
• Many data-processing applications require output
that has tabular format
• Field width: Total number of data characters and
additional spaces for a datum in a formatted string
Python Essentials
78
Formatting Text for Output (continued)
– This version contains format string, format
operator %, and single data value to be formatted
– To format integers, letter d is used instead of s
• To format sequence of data values:
Python Essentials
79
Formatting Text for Output (continued)
• To format data value of type float:
where .<precision> is optional
• Examples:
Python Essentials
80
Case Study: An Investment Report
• Request:
– Write a program that computes an investment report
Python Essentials
81
Case Study: An Investment Report
(continued)
• Analysis:
Python Essentials
82
Case Study: An Investment Report
(continued)
• Design:
–
–
–
–
Receive the user’s inputs and initialize data
Display the table’s header
Compute results for each year and display them
Display the totals
Python Essentials
83
Case Study: An Investment Report
(continued)
• Coding:
Python Essentials
84
Selection: if and if-else
Statements
• Selection statements allow a computer to make
choices
– Based on a condition
Python Essentials
85
The Boolean Type, Comparisons, and
Boolean Expressions
• Boolean data type consists of two values: true
and false (typically through standard True/False)
• Example: 4 != 4 evaluates to False
Python Essentials
86
if-else Statements
• Also called a two-way selection statement
• Often used to check inputs for errors:
• Syntax:
Python Essentials
87
if-else Statements (continued)
must be a Boolean expression
Better alternative:
Python Essentials
88
One-Way Selection Statements
• Simplest form of selection is the if statement
Python Essentials
89
Multi-way if Statements
• A program may be faced with testing conditions that
entail more than two alternative courses of action
• Can be described in code by a multi-way selection
statement
Python Essentials
90
Multi-way if Statements (continued)
• Syntax:
Python Essentials
91
Logical Operators and Compound
Boolean Expressions
• Often a course of action must be taken if either of
two conditions is true: Below are two approaches
– Could we use the and logical operator instead?
Python Essentials
92
Logical Operators and Compound
Boolean Expressions (continued)
Python Essentials
93
Logical Operators and Compound
Boolean Expressions (continued)
• Next example verifies some of the claims made in
the previous truth tables:
• The logical operators are evaluated after
comparisons but before the assignment operator
– not has higher precedence than and and or
Python Essentials
94
Logical Operators and Compound
Boolean Expressions (continued)
Python Essentials
95
Short-Circuit Evaluation
• In (A and B), if A is false, then so is the
expression, and there is no need to evaluate B
• In (A or B), if A is true, then so is the expression,
and there is no need to evaluate B
• Short-circuit evaluation: Evaluation stops as
soon as possible
Short-circuit evaluation can
be used to avoid division
by zero
Python Essentials
96
Testing Selection Statements
• Tips:
– Make sure that all of the possible branches or
alternatives in a selection statement are exercised
– After testing all of the actions, examine all of the
conditions
– Test conditions that contain compound Boolean
expressions using data that produce all of the
possible combinations of values of the operands
Python Essentials
97
Conditional Iteration: The while Loop
• The while loop can be used to describe
conditional iteration
– Example: A program’s input loop that accepts values
until user enters a sentinel that terminates the input
Python Essentials
98
The Structure and Behavior of a
while Loop
• Conditional iteration requires that condition be
tested within loop to determine if it should continue
– Called continuation condition
– Improper use may lead to infinite loop
• while loop is also called entry-control loop
– Condition is tested at top of loop
– Statements within loop can execute zero or more
times
Python Essentials
99
The Structure and Behavior of a
while Loop (continued)
Python Essentials
100
The Structure and Behavior of a
while Loop (continued)
data is the loop control variable
Python Essentials
101
Count Control with a while Loop
Python Essentials
102
The while True Loop and the
break Statement
• while loop can be complicated to write correctly
– Possible to simplify its structure and improve its
readability
a while True loop with a delayed exit
loop’s termination condition
causes an exit from the loop
Python Essentials
103
The while True Loop and the
break Statement (continued)
• Alternative: Use a Boolean variable to control loop
Python Essentials
104
Random Numbers
• Programming languages include resources for
generating random numbers
• random module supports several ways to do this
– randint returns random number from among
numbers between two arguments, included
• Example: A simple guessing game
Python Essentials
105
Random Numbers (continued)
Python Essentials
106
Loop Logic, Errors, and Testing
• Errors to rule out during testing while loop:
– Incorrectly initialized loop control variable
– Failure to update this variable correctly within loop
– Failure to test it correctly in continuation condition
• To halt loop that appears to hang during testing,
type Control+c in terminal window or IDLE shell
• If loop must run at least once, use a while True
loop with delayed examination of termination
condition
– Ensure a break statement to be reached eventually
Python Essentials
107
Case Study: Approximating Square
Roots
• Request:
– Write a program that computes square roots
• Analysis:
• Design:
– Use Newton’s square root approximation algorithm:
• Square root y of a positive number x is the number y
such that y2 = x
• If initial estimate of y is z, a better estimate of y can be
obtained by taking the average of z together with x/z
Python Essentials
108
Case Study: Approximating Square
Roots (continued)
• A quick session with the Python interpreter shows
this method of successive approximations in action:
Python Essentials
109
Case Study: Approximating Square
Roots (continued)
• Design (continued): Algorithm
set x to the user’s input value
set tolerance to 0.000001
set estimate to 1.0
while True
set estimate to (estimate + x / estimate) / 2
set difference to abs(x - estimate ** 2)
if difference <= tolerance:
break
output the estimate
Python Essentials
110
Case Study: Approximating Square
Roots (continued)
• Implementation (Coding):
Python Essentials
111
Summary
• Control statements determine order in which other
statements are executed in program
• Definite iteration is process of executing set of
statements fixed, predictable number of times
– Example: use for loop
• for loop consists of header and set of statements
called body
– Can be used to implement a count-controlled loop
• Use xrange to generate sequence of numbers
– Can traverse and visit the values in any sequence
Python Essentials
112
Summary (continued)
• A format string and its operator % allow programmer
to format data using field width and precision
• An off-by-one error occurs when loop does not
perform intended number of iterations, there being
one too many or one too few
• Boolean expressions evaluate to True or False
– Constructed using logical operators: and, or, not
– Python uses short-circuit evaluation in compound
Boolean expressions
• Selection statements enable program to make
choices
Python Essentials
113
Summary (continued)
• if-else is a two-way selection statement
• Conditional iteration is the process of executing a
set of statements while a condition is true
– Use while loop (which is an entry-control loop)
• A break can be used to exit a loop from its body
• Any for loop can be converted to an equivalent
while loop
• Infinite loop: Continuation condition never becomes
false and no other exit points are provided
• random.randint returns a random number
Python Essentials
114
Python Essentials:
Chapter 4
Strings and Text Files
Objectives
After completing this chapter, you will be able to
• Access individual characters in a string
• Retrieve a substring from a string
• Search for a substring in a string
• Convert a string representation of a number from
one base to another base
Python Essentials
116
Objectives (continued)
• Use string methods to manipulate strings
• Open a text file for output and write strings or
numbers to the file
• Open a text file for input and read strings or
numbers from the file
• Use library functions to access and navigate a file
system
Python Essentials
117
Accessing Characters and Substrings
in Strings
• In this section, we examine the internal structure of
a string more closely
• You will learn how to extract portions of a string
called substrings
Python Essentials
118
The Structure of Strings
• An integer can’t be factored into more primitive parts
• A string is a immutable data structure
– Data structure: Consists of smaller pieces of data
– String’s length: Number of characters it contains (0+)
Python Essentials
119
The Subscript Operator
• The form of the subscript operator is:
• Examples:
Python Essentials
index is usually in range [0,len); can be negative
120
The Subscript Operator (continued)
• Subscript operator is useful when you want to use
the positions as well as the characters in a string
– Use a count-controlled loop
Python Essentials
121
Slicing for Substrings
• Python’s subscript operator can be used to obtain a
substring through a process called slicing
– Place a colon (:) in the subscript; an integer value
can appear on either side of the colon
Python Essentials
122
Testing for a Substring with the in
Operator
• When used with strings, the left operand of in is a
target substring and the right operand is the string
to be searched
– Returns True if target string is somewhere in search
string, or False otherwise
Python Essentials
123
Data Encryption
• It is easy to observe data crossing a network,
particularly in wireless networks
– Attacker may use sniffing software
• Data encryption can be used to protect
information transmitted on networks
– Many protocols have secure versions (e.g., HTTPS)
– One or more keys are use to encrypt messages to
produce cipher text, and to decrypt cipher text back
to its original plain text form
– Examples: Caesar cipher, block cipher
Python Essentials
124
Data Encryption (continued)
• Caesar cipher replaces each character in plain
text with a character a given distance away
Python Essentials
125
Data Encryption (continued)
• To decrypt, use inverse method
Python Essentials
126
Data Encryption (continued)
• Caesar cipher worked well in ancient times, but is
easy to break using modern computers
Python Essentials
127
Data Encryption (continued)
• Block cipher
– Uses plaintext character to compute two or more
encrypted characters
– Each encrypted character is computed using two or
more plaintext characters
– Uses an invertible matrix
Python Essentials
128
Strings and Number Systems
• The digits used in each system are counted from 0
to n - 1, where n is the system’s base
• To represent digits with values larger than 910,
systems such as base 16 use letters
– Example: A16 represents the quantity 1010, whereas
1016 represents the quantity 1610
Python Essentials
129
The Positional System for
Representing Numbers
• In positional notation, a digit has a positional
value, determined by raising the base to the power
specified by the position (baseposition)
Python Essentials
130
Converting Binary to Decimal
• Each digit or bit in binary number has positional
value that is power of 2
• We occasionally refer to a binary number as a
string of bits or a bit string
• To determine the integer quantity that a string of
bits represents:
Python Essentials
131
Converting Binary to Decimal
(continued)
Python Essentials
132
Converting Binary to Decimal
(continued)
Python Essentials
133
Conversion Shortcuts
• Thus, a quick way to compute the decimal value of
the number 111112 is 25 - 1, or 3110
Python Essentials
134
Octal and Hexadecimal Numbers
• To convert from octal to binary, start by assuming
that each digit in the octal number represents three
digits in the corresponding binary number
• To convert binary to octal, you begin at the right
and factor the bits into groups of three bits each
Python Essentials
135
Octal and Hexadecimal Numbers
(continued)
• To convert from hex to binary, replace each hex
digit with the corresponding 4-bit binary number
• To convert from binary to hex, factor the bits into
groups of 4 and look up the corresponding hex
digits
Python Essentials
136
String Methods
• Python includes a set of string operations called
methods that make tasks like counting the words
in a single sentence easy
Python Essentials
137
String Methods (continued)
• A method behaves like a function, but has a slightly
different syntax
– A method is always called with a given data value
called an object
• Methods can expect arguments and return values
• A method knows about the internal state of the
object with which it is called
• In Python, all data values are in fact objects
Python Essentials
138
String Methods (continued)
Python Essentials
139
String Methods (continued)
Python Essentials
140
String Methods (continued)
Python Essentials
141
String Methods (continued)
• Example: extracting a filename’s extension
• The subscript [-1] extracts the last element
– Can be used to write a general expression for
obtaining any filename’s extension, as follows:
Python Essentials
142
Text Files
• A text file is software object that stores data on
permanent medium such as disk or CD
• When compared to keyboard input from human
user, the main advantages of taking input data from
a file are:
– The data set can be much larger
– The data can be input much more quickly and with
less chance of error
– The data can be used repeatedly with the same
program or with different programs
Python Essentials
143
Text Files and Their Format
• Using a text editor such as Notepad or TextEdit,
you can create, view, and save data in a text file
• All data output to or input from a text file must be
strings
Python Essentials
144
Writing Text to a File
• Data can be output to a text file using a file
object
• To open a file for output:
– If file does not exist, it is created
– If it already exists, Python opens it; when data are
written to the file and the file is closed, any data
previously existing in the file are erased
Failure to close output file can result in data being lost
Python Essentials
145
Writing Numbers to a File
• The file method write expects a string as an
argument
– Other types of data must first be converted to strings
before being written to output file (e.g., using str)
Python Essentials
146
Reading Text from a File
• You open a file for input in a manner similar to
opening a file for output
– If the pathname is not accessible from the current
working directory, Python raises an error
• There are several ways to read data from a file
– Example: the read method
Python Essentials
147
Reading Text from a File (continued)
• After input is finished, read returns an empty string
Python Essentials
148
Reading Numbers from a File
• Examples:
Python Essentials
149
Reading Numbers from a File
(continued)
Python Essentials
150
Accessing and Manipulating Files and
Directories on Disk
• When designing Python programs that interact with
files, it’s a good idea to include error recovery
• For example, before attempting to open a file for
input, you should check to see if file exists
– Function os.path.exists supports this checking
• Example: To print all of the names of files in the
current working directory with a .py extension:
Python Essentials
151
Accessing and Manipulating Files and
Directories on Disk (continued)
Python Essentials
152
Accessing and Manipulating Files and
Directories on Disk (continued)
Python Essentials
153
Case Study: Text Analysis
• In 1949, Dr. Rudolf Flesch proposed a measure of
text readability known as the Flesch Index
– Index is based on the average number of syllables
per word and the average number of words per
sentence in a piece of text
– Scores usually range from 0 to 100, and indicate
readable prose for the following grade levels:
Python Essentials
154
Case Study: Request
• Write a program that computes the Flesch index
and grade level for text stored in a text file
Python Essentials
155
Case Study: Analysis
• Input is the name of a text file
• Outputs are the number of sentences, words, and
syllables in the file, as well as the file’s Flesch
index and grade-level equivalent
Python Essentials
156
Case Study: Design
Python Essentials
157
Case Study: Implementation (Coding)
Python Essentials
158
Case Study: Implementation (Coding)
(continued)
Python Essentials
159
Case Study: Testing
• Bottom-up testing:
– Each task is coded and tested before it is integrated
into the overall program
– After you have written code for one or two tasks, you
can test them in a short script
• This script is called a driver
Python Essentials
160
Summary
• A string is a sequence of zero or more characters
– Immutable data structure
– [] used to access a character at a given position
• Can also be used for slicing ([<start>:<end>])
• in operator is used to detect the presence or
absence of a substring in a string
• Method: operation that is used with an object
• The string type includes many useful methods for
use with string objects
Python Essentials
161
Summary (continued)
• A text file is a software object that allows a program
to transfer data to and from permanent storage
• A file object is used to open a connection to a
text file for input or output
– Some useful methods: read, write, readline
• for loop treats an input file as a sequence of lines
– On each pass through the loop, the loop’s variable is
bound to a line of text read from the file
Python Essentials
162
Python Essentials:
Chapter 5
Lists and Dictionaries
Objectives
After completing this chapter, you will be able to:
• Construct lists and access items in those lists
• Use methods to manipulate lists
• Perform traversals of lists to process items in the
lists
• Define simple functions that expect parameters and
return values
Python Essentials
164
Objectives (continued)
• Construct dictionaries and access entries in those
dictionaries
• Use methods to manipulate dictionaries
• Decide whether a list or a dictionary is an
appropriate data structure for a given application
Python Essentials
165
Introduction
• A list allows the programmer to manipulate a
sequence of data values of any types
• A dictionary organizes data values by association
with other data values rather than by sequential
position
• Lists and dictionaries provide powerful ways to
organize data in useful and interesting applications
Python Essentials
166
Lists
• List: Sequence of data values (items or elements)
• Some examples:
–
–
–
–
–
–
Shopping list for the grocery store
To-do list
Guest list for a wedding
Recipe, which is a list of instructions
Text document, which is a list of lines
Words in a dictionary
• Each item in a list has a unique index that
specifies its position (from 0 to length – 1)
Python Essentials
167
List Literals and Basic Operators
• Some examples:
['apples', 'oranges', 'cherries']
[[5, 9], [541, 78]]
• When an element is an expression, its value is
included in the list:
• Lists of integers can be built using range:
Python Essentials
168
List Literals and Basic Operators
(continued)
• len, [], +, and == work on lists as expected:
• To print the contents of a list:
• in detects the presence of an element:
Python Essentials
169
List Literals and Basic Operators
(continued)
Python Essentials
170
Replacing an Element in a List
• A list is mutable
– Elements can be inserted, removed, or replaced
– The list itself maintains its identity, but its state—its
length and its contents—can change
• Subscript operator is used to replace an element:
– Subscript is used to reference the target of the
assignment, which is not the list but an element’s
position within it
Python Essentials
171
Replacing an Element in a List
(continued)
• Examples:
Python Essentials
172
List Methods for Inserting and
Removing Elements
• The list type includes several methods for
inserting and removing elements
Python Essentials
173
List Methods for Inserting and
Removing Elements (continued)
Python Essentials
174
Searching a List
• in determines an element’s presence or absence,
but does not return position of element (if found)
• Use method index to locate an element’s position
in a list
– Raises an error when the target element is not found
Python Essentials
175
Sorting a List
• A list’s elements are always ordered by position,
but you can impose a natural ordering on them
– For example, in alphabetical order
• When the elements can be related by comparing
them <, >, and ==, they can be sorted
– The method sort mutates a list by arranging its
elements in ascending order
Python Essentials
176
Mutator Methods and the Value None
• All of the functions and methods examined in
previous chapters return a value that the caller can
then use to complete its work
• Mutator methods (e.g., insert, append) usually
return no value of interest to caller
– Python automatically returns the special value None
Python Essentials
177
Aliasing and Side Effects
• Mutable property of lists leads to interesting
phenomena:
first and second are aliases
(refer to the exact same list object)
Python Essentials
178
Aliasing and Side Effects (continued)
• To prevent aliasing, copy contents of object:
Alternative:
Python Essentials
179
Equality: Object Identity and Structural
Equivalence
Python Essentials
180
Example: Using a List to Find the
Median of a Set of Numbers
• To find the median of a set of numbers:
Python Essentials
181
Tuples
• A tuple resembles a list, but is immutable
– Indicate by enclosing its elements in ()
• Most of the operators and functions used with lists
can be used in a similar fashion with tuples
Python Essentials
182
Defining Simple Functions
• Defining our own functions allows us to organize
our code in existing scripts more effectively
Python Essentials
183
The Syntax of Simple Function
Definitions
• Definition of a function consists of header and body
– Docstring contains information about what the
function does; to display, enter help(square)
• A function can be defined in a Python shell, but it is
more convenient to define it in an IDLE window
• Syntax of a function definition:
Python Essentials
184
Parameters and Arguments
• A parameter is the name used in the function
definition for an argument that is passed to the
function when it is called
• For now, the number and positions of arguments of
a function call should match the number and
positions of the parameters in the definition
• Some functions expect no arguments
– They are defined with no parameters
Python Essentials
185
The return Statement
• Place a return statement at each exit point of a
function when function should explicitly return a
value
• Syntax:
• If a function contains no return statement, Python
transfers control to the caller after the last
statement in the function’s body is executed
– The special value None is automatically returned
Python Essentials
186
Boolean Functions
• A Boolean function usually tests its argument for
the presence or absence of some property
– Returns True if property is present; False otherwise
• Example:
Python Essentials
187
Defining a main Function
• main serves as the entry point for a script
– Usually expects no arguments and returns no value
• Definition of main and other functions can appear
in no particular order in the script
– As long as main is called at the end of the script
• Script can be run from IDLE, imported into the
shell, or run from a terminal command prompt
Python Essentials
188
Defining a main Function (continued)
Python Essentials
189
Case Study: Generating Sentences
• Request: write a program that generates sentences
• Analysis: program will generate sentences from a
simplified subset of English
Python Essentials
190
Case Study: Generating Sentences
(continued)
• Design:
– Assign task of generating each phrase to a separate
function
Python Essentials
191
Case Study: Generating Sentences
(continued)
• Implementation (coding):
– The variables for the data are initialized just below
the import statement
Python Essentials
192
Case Study: Generating Sentences
(continued)
Python Essentials
193
Case Study: Generating Sentences
(continued)
• Testing:
– Two approaches:
• Bottom-up
• Top-down
– Wise programmer can mix bottom-up and top-down
testing as needed
Python Essentials
194
Dictionaries
• A dictionary organizes information by association,
not position
– Example: When you use a dictionary to look up the
definition of “mammal,” you don’t start at page 1;
instead, you turn directly to the words beginning with
“M”
• Data structures organized by association are also
called tables or association lists
• In Python, a dictionary associates a set of keys
with data values
Python Essentials
195
Dictionary Literals
• A Python dictionary is written as a sequence of
key/value pairs separated by commas
– Pairs are sometimes called entries
– Enclosed in curly braces ({ and })
– A colon (:) separates a key and its value
• Examples:
{'Sarah':'476-3321', 'Nathan':'351-7743'}
A Phone book
{'Name':'Molly', 'Age':18}
Personal information
{}
An empty dictionary
• Keys can be data of any immutable types, including
other data structures
Python Essentials
196
Adding Keys and Replacing Values
• Add a new key/value pair to a dictionary using []:
• Example:
• Use [] also to replace a value at an existing key:
Python Essentials
197
Accessing Values
• Use [] to obtain the value associated with a key
– If key is not present in dictionary, an error is raised
• If the existence of a key is uncertain, test for it
using the dictionary method has_key
– Easier strategy is to use the method get
Python Essentials
198
Removing Keys
• To delete an entry from a dictionary, remove its key
using the method pop
– pop expects a key and an optional default value as
arguments
Python Essentials
199
Traversing a Dictionary
• To print all of the keys and their values:
• Alternative: Use the dictionary method items()
– Entries are represented as tuples within the list
• You can sort the list first:
Python Essentials
200
Traversing a Dictionary (continued)
Python Essentials
201
Example: The Hexadecimal System
Revisited
• You can keep a hex-to-binary lookup table to aid
in the conversion process
Python Essentials
202
Example: Finding the Mode of a List of
Values
• The mode of a list of values is the value that
occurs most frequently
• The following script inputs a list of words from a
text file and prints their mode
Python Essentials
203
Example: Finding the Mode of a List of
Values (continued)
Python Essentials
204
Case Study: Nondirective
Psychotherapy (Request)
• Doctor in this kind of therapy responds to patient’s
statements by rephrasing them or indirectly asking
for more information
• Request:
– Write a program that emulates a nondirective
psychotherapist
Python Essentials
205
Case Study: Nondirective
Psychotherapy (Analysis)
Python Essentials
206
Case Study: Nondirective
Psychotherapy (Analysis) (continued)
• When user enters a statement, program responds
in one of two ways:
– With a randomly chosen hedge, such as “Please tell
me more”
– By changing some key words in user’s input string
and appending string to a randomly chosen qualifier
• Thus, to “My teacher always plays favorites,” program
might reply, “Why do you say that your teacher always
plays favorites?”
Python Essentials
207
Case Study: Nondirective
Psychotherapy (Design)
• Program consists of a set of collaborating functions
that share a common data pool
• Pseudocode:
output a greeting to the patient
while True
prompt for and input a string from the patient
if the string equals “Quit”
output a sign-off message to the patient
break
call another function to obtain a reply to this string
output the reply to the patient
Python Essentials
208
Case Study: Nondirective
Psychotherapy (Implementation)
Python Essentials
209
Case Study: Nondirective
Psychotherapy (Implementation)
(continued)
Python Essentials
210
Case Study: Nondirective
Psychotherapy (Testing)
• Functions in this program can be tested in a
bottom-up or a top-down manner
• Program’s replies break down when:
– User addresses the therapist in the second person
– User uses contractions (for example, I’m and I’ll)
• With a little work, you can make the replies more
realistic
Python Essentials
211
Summary
• A list is a sequence of zero or more elements
– Can be manipulated with the subscript,
concatenation, comparison, and in operators
– Mutable data structure
– index returns position of target element in a list
– Elements can be arranged in order using sort
• Mutator methods are called to change the state of
an object; usually return the value None
• Assignment of a variable to another one causes
both to refer to the same data object (aliasing)
Python Essentials
212
Summary (continued)
• A tuple is similar to a list, but is immutable
• A function definition consists of header and body
– return returns a value from a function definition
• A dictionary associates a set of keys with values
– [] is used to add a new key/value pair to a dictionary
or to replace a value associated with an existing key
– dict type includes methods to access and remove
data in a dictionary
• Testing can be bottom-up, top-down, or you can use
a mix of both
Python Essentials
213
Python Essentials:
Chapter 6
Design with Functions
Objectives
After completing this chapter, you will be able to:
• Explain why functions are useful in structuring code
in a program
• Employ top-down design to assign tasks to
functions
• Define a recursive function
Python Essentials
215
Objectives (continued)
• Explain the use of the namespace in a program
and exploit it effectively
• Define a function with required and optional
parameters
• Use higher-order functions for mapping, filtering,
and reducing
Python Essentials
216
Functions as Abstraction Mechanisms
• An abstraction hides detail
– Allows a person to view many things as just one
thing
• We use abstractions to refer to the most common
tasks in everyday life
– For example, the expression “doing my laundry”
• Effective designers must invent useful abstractions
to control complexity
Python Essentials
217
Functions Eliminate Redundancy
• Functions serve as abstraction mechanisms by
eliminating redundant, or repetitious, code
Python Essentials
218
Functions Hide Complexity
• Functions serve as abstraction mechanisms is by
hiding complicated details
• For example, consider the previous sum function
– The idea of summing a range of numbers is simple;
the code for computing a summation is not
• A function call expresses the idea of a process to
the programmer
– Without forcing him/her to wade through the complex
code that realizes that idea
Python Essentials
219
Functions Support General Methods
with Systematic Variations
• An algorithm is a general method for solving a
class of problems
• The individual problems that make up a class of
problems are known as problem instances
– What are the problem instances of our summation
algorithm?
• Algorithms should be general enough to provide a
solution to many problem instances
– A function should provide a general method with
systematic variations
Python Essentials
220
Functions Support the Division of
Labor
• In a well-organized system, each part does its own
job in collaborating to achieve a common goal
• In a computer program, functions can enforce a
division of labor
– Each function should perform a single coherent task
• Example: Computing a summation
• Each of the tasks required by a system can be
assigned to a function
– Including the tasks of managing or coordinating the
use of other functions
Python Essentials
221
Problem Solving with Top-Down
Design
• Top-down design starts with a global view of the
entire problem and breaks the problem into
smaller, more manageable subproblems
– Process known as problem decomposition
• As each subproblem is isolated, its solution is
assigned to a function
• As functions are developed to solve subproblems,
solution to overall problem is gradually filled out
– Process is also called stepwise refinement
Python Essentials
222
The Design of the Text-Analysis
Program
Python Essentials
223
The Design of the Sentence-Generator
Program
Python Essentials
224
The Design of the Doctor Program
Python Essentials
225
Design with Recursive Functions
• In top-down design, you decompose a complex
problem into a set of simpler problems and solve
these with different functions
• In some cases, you can decompose a complex
problem into smaller problems of the same form
– Subproblems can be solved using the same function
• This design strategy is called recursive design
• Resulting functions are called recursive functions
Python Essentials
226
Defining a Recursive Function
• A recursive function is a function that calls itself
– To prevent function from repeating itself indefinitely,
it must contain at least one selection statement
• Statement examines base case to determine whether
to stop or to continue with another recursive step
• To convert displayRange to a recursive function:
– You can replace loop with a selection statement and
assignment statement with a recursive call
Python Essentials
227
Defining a Recursive Function
(continued)
• Making displayRange recursive (continued):
• Most recursive functions expect at least one
argument
• Another example: Recursive version of sum
Python Essentials
228
Tracing a Recursive Function
Python Essentials
229
Using Recursive Definitions to
Construct Recursive Functions
• Recursive functions are frequently used to design
algorithms that have a recursive definition
– A recursive definition consists of equations that state
what a value is for one or more base cases and one
or more recursive cases
• Example: Fibonacci sequence
1 1 2 3 5 8 13 . . .
Python Essentials
230
Recursion in Sentence Structure
• Recursive solutions can often flow from the
structure of a problem
• Example: Structure of sentences in a language
– A noun phrase can be modified by a prepositional
phrase, which also contains another noun phrase
 Indirect recursion
Python Essentials
231
Infinite Recursion
• Infinite recursion arises when programmer fails to
specify base case or to reduce size of problem in a
way that terminates the recursive process
– In fact, the Python virtual machine eventually runs
out of memory resources to manage the process
Python Essentials
232
The Costs and Benefits of Recursion
• PVM reserves an area of memory for the call stack
• For each call of a function, the PVM must allocate
on the call stack a stack frame, which contains:
– Values of the arguments
– Return address for the particular function call
– Space for the function call’s return value
• When a call returns, return address is used to locate
the next instruction, and stack frame is deallocated
• Amount of memory needed for a loop does not grow
with the size of the problem’s data set
Python Essentials
233
The Costs and Benefits of Recursion
(continued)
Python Essentials
234
Case Study: Gathering Information
from a File System
• Request: Write a program that allows the user to
obtain information about the file system
• Analysis:
–
–
–
–
File systems are tree-like structures
At the top of the tree is the root directory
Under the root are files and subdirectories
Each directory in the system except the root lies
within another directory called its parent
– Example of a path (UNIX-based file system):
• /Users/KenLaptop/Book/Chapter6/Chapter6.doc
Python Essentials
235
Case Study: Gathering Information
from a File System (continued)
Python Essentials
236
Case Study: Gathering Information
from a File System (continued)
– When user enters a number, program runs
command; then, displays CWD and menu again
– An unrecognized command produces an error
message
Python Essentials
237
Case Study: Gathering Information
from a File System (continued)
Python Essentials
238
Case Study: Gathering Information
from a File System (continued)
• Design:
Python Essentials
239
Case Study: Gathering Information
from a File System (continued)
…
Python Essentials
240
Managing a Program’s Namespace
• A program’s namespace is the set of its variables
and their values
– You can control it via good design principles
Python Essentials
241
Module Variables, Parameters, and
Temporary Variables
doctor.py file (module name is doctor):
A module variable
A parameter name
A temporary variable
A method name
• Module variables and temporary variables
receive their values as soon as they are introduced
• Parameters behave like a variable and are
introduced in a function or method header
– Do not receive a value until the function is called
Python Essentials
242
Scope
• Scope: Area in which a name refers to a given
value
– Temporary variables are restricted to the body of the
functions in which they are introduced
– Parameters are invisible outside function definition
– The scope of module variables includes entire module
below point where they are introduced
• A function can reference a module variable, but can’t
under normal circumstances assign a new value to it
Python Essentials
243
Lifetime
• Variable’s lifetime: Period of time when variable
has memory storage associated with it
– When variable comes into existence, storage is
allocated for it; when it goes out of existence,
storage is reclaimed by the PVM
• Module variables come into existence when
introduced and generally exist for lifetime of
program that introduces or imports them
• Parameters and temporary variables come into
existence when bound to values during call, but go
out of existence when call terminates
Python Essentials
244
Default (Keyword) Arguments
• Arguments provide the function’s caller with the
means of transmitting information to the function
• Programmer can specify optional arguments with
default values in any function definition:
– Following the required arguments are one or more
default or keyword arguments
– When function is called with these arguments,
default values are overridden by caller’s values
Python Essentials
245
Default (Keyword) Arguments
(continued)
Python Essentials
246
Default (Keyword) Arguments
(continued)
• The default arguments that follow can be supplied
in two ways:
– By position
– By keyword
Python Essentials
247
Higher-Order Functions
(Advanced Topic)
• A higher-order function expects a function and a
set of data values as arguments
– Argument function is applied to each data value and
a set of results or a single data value is returned
• A higher-order function separates task of
transforming each data value from logic of
accumulating the results
Python Essentials
248
Functions as First-Class Data Objects
• Functions can be assigned to variables, passed as
arguments, returned as the values of other
functions, and stored in data structures
Python Essentials
249
Functions as First-Class Data Objects
(continued)
• Passing a function as an argument is no different
from passing any other datum:
• Apply a function to its arguments by passing it and
a sequence of its arguments to the apply function:
Python Essentials
250
Mapping
• Mapping applies a function to each value in a list
and returns a new list of the results
Python Essentials
251
Mapping (continued)
Python Essentials
252
Filtering
• When filtering, a function called a predicate is
applied to each value in a list
– If predicate returns True, value is added to a new
list; otherwise, value is dropped from consideration
Python Essentials
253
Reducing
• When reducing, we take a list of values and
repeatedly apply a function to accumulate a single
data value
Python Essentials
254
Using lambda to Create Anonymous
Functions
• A lambda is an anonymous function
– When the lambda is applied to its arguments, its
expression is evaluated and its value is returned
Python Essentials
255
Creating Jump Tables
• A jump table is a dictionary of functions keyed by
command names
Python Essentials
256
Summary
• A function serves as abstraction mechanism and
eliminates redundant patterns of code
• Top-down design is strategy that decomposes
complex problem into simpler subproblems and
assigns their solutions to functions
• A structure chart is diagram of relationships among
cooperating functions
• Recursive design is special case of top-down
design, in which complex problem is decomposed
into smaller problems of the same form
Python Essentials
257
Summary (continued)
• A recursive function is a function that calls itself
– Parts: Base case and recursive step
– Can be computationally expensive
• Programmers must avoid infinite recursion
• Program namespace structured in terms of module
variables, parameters, and temporary variables
• Scope can be used to control the visibility of names
in a namespace
• The lifetime of a variable is duration of program
execution during which it uses memory storage
Python Essentials
258
Summary (continued)
• Functions are first-class data objects
• Higher-order functions can expect other functions
as arguments and/or return functions as values
• A mapping function expects a function and a list of
values as arguments
• A predicate is a Boolean function
• A filtering function expects a predicate and a list of
values as arguments
• A reducing function expects a function and a list of
values as arguments
Python Essentials
259
Python Essentials:
Chapter 7
Design with Classes
Objectives
After completing this chapter, you will be able to:
• Determine the attributes and behavior of a class of
objects required by a program
• List the methods, including their parameters and
return types, that realize the behavior of a class of
objects
• Choose the appropriate data structures to
represent the attributes of a class of objects
• Define a constructor, instance variables, and
methods for a class of objects
Python Essentials
261
Objectives (continued)
• Recognize the need for a class variable and define
it
• Define a method that returns the string
representation of an object
• Define methods for object equality and
comparisons
• Exploit inheritance and polymorphism when
developing classes
• Transfer objects to and from files
Python Essentials
262
Getting Inside Objects and Classes
• Programmers who use objects and classes know:
– Interface that can be used with a class
– State of an object
– How to instantiate a class to obtain an object
• Objects are abstractions
– Package their state and methods in a single entity
that can be referenced with a name
• Class definition is like a blueprint for each of the
objects of that class
Python Essentials
263
A First Example: The Student Class
• A course-management application needs to
represent information about students in a course
Python Essentials
264
The Student Class (continued)
Python Essentials
265
The Student Class (continued)
• Syntax of a simple class definition:
 class header
– Class name is a Python identifier
• Typically capitalized
• Python classes are organized in a tree-like class
hierarchy
– At the top, or root, of this tree is the object class
– Some terminology: subclass, parent class
Python Essentials
266
The Student Class (continued)
Python Essentials
267
Docstrings
• Docstrings can appear at three levels:
– Module
– Just after class header
• To describe its purpose
– After each method header
• Serve same role as they do for function definitions
• help(Student) prints the documentation for the
class and all of its methods
Python Essentials
268
Method Definitions
• Method definitions are indented below class header
• Syntax of method definitions similar to functions
– Can have required and/or default arguments, return
values, create/use temporary variables
– Returns None when no return statement is used
• Each method definition must include a first
parameter named self
• Example: s.getScore(4)
– Binds the parameter self in the method getScore
to the Student object referenced by the variable s
Python Essentials
269
The __init__ Method and Instance
Variables
• Most classes include the __init__ method
– Class’s constructor
– Runs automatically when user instantiates the class
• Example: s = Student("Juan", 5)
• Instance variables represent object attributes
– Serve as storage for object state
– Scope is the entire class definition
Python Essentials
270
The __str__ Method
• Classes usually include an __str__ method
– Builds and returns a string representation of an
object’s state
• When str function is called with an object, that
object’s __str__ method is automatically invoked
• Perhaps the most important use of __str__ is in
debugging
Python Essentials
271
Accessors and Mutators
• Methods that allow a user to observe but not
change the state of an object are called accessors
• Methods that allow a user to modify an object’s
state are called mutators
• Tip: if there’s no need to modify an attribute (e.g., a
student’s name), do not include a method to do that
Python Essentials
272
The Lifetime of Objects
• The lifetime of an object’s instance variables is the
lifetime of that object
• An object becomes a candidate for the graveyard
when it can no longer be referenced
Student object still exists, but interpreter will
recycle its storage during garbage collection
Python Essentials
273
Rules of Thumb for Defining a Simple
Class
• Before writing a line of code, think about the
behavior and attributes of the objects of new class
• Choose an appropriate class name and develop a
short list of the methods available to users
• Write a short script that appears to use the new
class in an appropriate way
• Choose appropriate data structures for attributes
• Fill in class template with __init__ and __str__
• Complete and test remaining methods incrementally
• Document your code
Python Essentials
274
Case Study: Playing the Game of
Craps
• Request:
– Write a program that allows the user to play and
study the game of craps
• Analysis: define Player and Die classes
– User interface: prompt for number of games to play
Python Essentials
275
Case Study: Design
Python Essentials
276
Case Study: Implementation (Coding)
Python Essentials
277
Case Study: Implementation (Coding)
(continued)
…
Python Essentials
278
Data-Modeling Examples
• As you have seen, objects and classes are useful
for modeling objects in the real world
• In this section, we explore several other examples
Python Essentials
279
Rational Numbers
• Rational number consists of two integer parts, a
numerator and a denominator
– Examples: 1/2, 2/3, etc.
• Python has no built-in type for rational numbers
– We will build a new class named Rational
Operators need to be overloaded
Python Essentials
280
Rational Number Arithmetic and
Operator Overloading
• Object on which the method is called corresponds
to the left operand
– For example, the code x + y is actually shorthand
for the code x.__add__(y)
Python Essentials
281
Rational Number Arithmetic and
Operator Overloading (continued)
• To overload an arithmetic operator, you define a
new method using the appropriate method name
• Code for each method applies a rule of rational
number arithmetic
Python Essentials
282
Rational Number Arithmetic and
Operator Overloading (continued)
• Operator overloading is another example of an
abstraction mechanism
– We can use operators with single, standard
meanings even though the underlying operations
vary from data type to data type
Python Essentials
283
Comparisons and the __cmp__
Method
• __cmp__ is called whenever you use the
comparison operators: ==, !=, <, >, <=, and >=
• Returns 0 if operands are equal, -1 if left operand is
< right one, 1 if left operand > right one
Python Essentials
284
Equality and the __eq__ Method
• Not all objects are comparable using < or >, but any
two objects can be compared for == or !=
twoThirds < "hi there" should generate an error
twoThirds != "hi there" should return True
• Include __eq__ in any class where a comparison
for equality uses a criterion other than object identity
Python Essentials
285
Savings Accounts and Class Variables
Python Essentials
286
Savings Accounts and Class Variables
(continued)
Python Essentials
287
Savings Accounts and Class Variables
(continued)
Python Essentials
288
Putting the Accounts into a Bank
Python Essentials
289
Putting the Accounts into a Bank
(continued)
Python Essentials
290
Putting the Accounts into a Bank
(continued)
Python Essentials
291
Using cPickle for Permanent
Storage of Objects
• cPickle allows programmer to save and load
objects using a process called pickling
– Python takes care of all of the conversion details
Python Essentials
292
Input of Objects and the try-except
Statement
Python Essentials
293
Playing Cards
• Use of the Card class:
• Because the attributes are only accessed and
never modified, we do not include any methods
other than __str__ for string representation
• A card is little more than a container of two data
values
Python Essentials
294
Playing Cards (continued)
Python Essentials
295
Playing Cards (continued)
• Unlike an individual card, a deck has significant
behavior that can be specified in an interface
• One can shuffle the deck, deal a card, and
determine the number of cards left in it
Python Essentials
296
Playing Cards (continued)
• During instantiation, all 52 unique cards are
created and inserted into a deck’s internal list
Python Essentials
297
Case Study: An ATM
• Develop a simple ATM program that uses the Bank
and SavingsAccount classes
• Request:
– Write a program that simulates a simple ATM
• Analysis:
– Figure 8.1 shows sample terminal-based interface
– Class diagram in Figure 8.2 shows the relationships
among the classes
• Name of each class appears in a box
• Edges connecting the boxes show the relationships
– Use model/view pattern to structure the code
Python Essentials
298
Case Study: An ATM (continued)
Python Essentials
299
Case Study: An ATM (continued)
• Design
Python Essentials
300
Structuring Classes with Inheritance
and Polymorphism
• Most object-oriented languages require the
programmer to master the following techniques:
– Data encapsulation: Restricting manipulation of an
object’s state by external users to a set of method calls
– Inheritance: Allowing a class to automatically reuse/
and extend code of similar but more general classes
– Polymorphism: Allowing several different classes to
use the same general method names
• Python’s syntax doesn’t enforce data encapsulation
• Inheritance and polymorphism are built into Python
Python Essentials
301
Inheritance Hierarchies and Modeling
Python Essentials
302
Inheritance Hierarchies and Modeling
(continued)
• In Python, all classes automatically extend the
built-in object class
• It is possible to extend any existing class:
• Example:
– PhysicalObject would extend object
– LivingThing would extend PhysicalObject
• Inheritance hierarchies provide an abstraction
mechanism that allows the programmer to avoid
reinventing the wheel or writing redundant code
Python Essentials
303
Example: A Restricted Savings
Account
A RestrictedSavingsAccount
permits up to three withdrawals
• To call a method in the parent class from within a
method with the same name in a subclass:
Python Essentials
304
Example: The Dealer and a Player in
the Game of Blackjack
Python Essentials
305
Example: The Dealer and a Player in
the Game of Blackjack (continued)
• An object belonging to Blackjack class sets up
the game and manages the interactions with user
Python Essentials
306
Example: The Dealer and a Player in
the Game of Blackjack (continued)
Python Essentials
307
Example: The Dealer and a Player in
the Game of Blackjack (continued)
Python Essentials
308
Example: The Dealer and a Player in
the Game of Blackjack (continued)
Python Essentials
309
Example: The Dealer and a Player in
the Game of Blackjack (continued)
Python Essentials
310
Polymorphic Methods
• We subclass when two classes share a substantial
amount of abstract behavior
– The classes have similar sets of methods/operations
– A subclass usually adds something extra
• The two classes may have the same interface
– One or more methods in subclass override the
definitions of the same methods in the superclass to
provide specialized versions of the abstract behavior
• Polymorphic methods (e.g., the __str__ method)
Python Essentials
311
Abstract Classes
• An abstract class includes data and methods
common to its subclasses, but is never instantiated
Python Essentials
312
The Costs and Benefits of ObjectOriented Programming
• Imperative programming
– Code consists of I/O, assignment, and control
(selection/iteration) statements
– Does not scale well
• Improvement: Embedding sequences of imperative
code in function definitions or subprograms
– Procedural programming
• Functional programming views a program as a
set of cooperating functions
– No assignment statements
Python Essentials
313
The Costs and Benefits of ObjectOriented Programming (continued)
• Functional programming does not conveniently
model situations where data must change state
• Object-oriented programming attempts to control
the complexity of a program while still modeling
data that change their state
– Divides up data into units called objects
– Well-designed objects decrease likelihood that
system will break when changes are made within a
component
– Can be overused and abused
Python Essentials
314
Summary
• A simple class definition consists of a header and a
set of method definitions
• In addition to methods, a class can also include
instance variables
• Constructor or __init__ method is called when a
class is instantiated
• A method contains a header and a body
• An instance variable is introduced and referenced
like any other variable, but is always prefixed with
self
Python Essentials
315
Summary (continued)
• Some standard operators can be overloaded for
use with new classes of objects
• When a program can no longer reference an
object, it is considered dead and its storage is
recycled by the garbage collector
• A class variable is a name for a value that all
instances of a class share in common
• Pickling is the process of converting an object to a
form that can be saved to permanent file storage
• try-except statement is used to catch and
handle exceptions
Python Essentials
316
Summary (continued)
• Most important features of OO programming:
encapsulation, inheritance, and polymorphism
– Encapsulation restricts access to an object’s data to
users of the methods of its class
– Inheritance allows one class to pick up the attributes
and behavior of another class for free
– Polymorphism allows methods in several different
classes to have the same headers
• A data model is a set of classes that are
responsible for managing the data of a program
Python Essentials
317