101331
101331
com
https://ebookgate.com/product/python-for-everyone-2nd-
edition-cay-horstmann/
OR CLICK BUTTON
DOWLOAD EBOOK
https://ebookgate.com/product/python-for-everyone-1st-edition-cay-s-
horstmann/
ebookgate.com
https://ebookgate.com/product/object-oriented-design-and-patterns-2nd-
edition-cay-s-horstmann/
ebookgate.com
https://ebookgate.com/product/java-concepts-late-objects-3rd-edition-
edition-cay-s-horstmann/
ebookgate.com
https://ebookgate.com/product/mark-for-everyone-2nd-edition-tom-
wright/
ebookgate.com
Python for Bioinformatics 2nd Edition Sebastian Bassi
https://ebookgate.com/product/python-for-bioinformatics-2nd-edition-
sebastian-bassi/
ebookgate.com
https://ebookgate.com/product/python-for-scientists-2nd-edition-john-
m-stewart/
ebookgate.com
https://ebookgate.com/product/six-sigma-for-everyone-1st-edition-
george-eckes/
ebookgate.com
https://ebookgate.com/product/a-web-for-everyone-1st-edition-sarah-
horton/
ebookgate.com
https://ebookgate.com/product/python-the-complete-manual-the-
essential-handbook-for-python-users-master-python-today-first-edition-
unknown/
ebookgate.com
Cay Horstmann
San Jose State University
Rance Necaise
Randolph-Macon College
Python for
Everyone
2/e
Copyright © 2016 John Wiley & Sons, Inc.
ISBN 978-1-119-05655-3
ISBN-BRV 978-1-119-05636-2
Toolbox Sections
Many optional “Toolbox” sections introduce useful packages in the wonderful eco-
system of Python libraries. Students are empowered to perform useful work such
as statistical computations, drawing graphs and charts, sending e-mail, processing
spreadsheets, and analyzing web pages. The libraries are placed in the context of
computer science principles, and students learn how those principles apply to solving
real-world problems. Each Toolbox is accompanied by many new end-of-chapter
review and programming exercises.
Data Plotting
Several new Worked Examples show students how to create a visual representation
of data through graphical plots. These examples use the pyplot library to create simple
data plots as they show students how to apply the language constructs introduced in
the respective chapters.
Interactive Learning
Additional interactive content is available that integrates with this text and immerses
students in activities designed to foster in-depth learning. Students don’t just watch
animations and code traces, they work on generating them. The activities provide
instant feedback to show students what they did right and where they need to study
more. To find out more about how to make this content available in your course, visit
http://wiley.com/go/pfe2interactivities.
“CodeCheck” is an innovative online service that students can use to work on pro-
gramming problems. You can assign exercises that have already been prepared, and
you can easily add your own. Visit http://codecheck.it to learn more and to try it out.
Fundamentals
1. Introduction
Object-Oriented Programming
Data Structures & Algorithms
2. Programming
with Numbers
and Strings
3. Decisions
4. Loops
A gentle
introduction to recursion
is optional.
5. Functions
Exercises
End-of-chapter exercises contain a broad mix of review and programming questions,
with optional questions from graphics, science, and business. Designed to engage
students, the exercises illustrate the value of programming in applied fields.
Web Resources
This book is complemented by a complete suite of online resources. Go to www.wiley.
com/college/horstmann to visit the online companion sites, which include
• Source code for all examples programs and Worked Examples in the book.
• Lecture presentation slides (for instructors only).
• Solutions to all review and programming exercises (for instructors only).
• A test bank that focuses on skills, not just terminology (for instructors only). This
extensive set of multiple-choice questions can be used with a word processor or
imported into a course management system.
• “CodeCheck” assignments that allow students to work on programming prob-
lems presented in an innovative online service and receive immediate feedback.
Instructors can assign exercises that have already been prepared, or easily add
their own.
CONTENTS
PREFACE iii CE3 Unbalanced Parentheses 41
SPECIAL FEATURES xviii PT3 Use Spaces in Expressions 42
ST1 Other Ways to Import Modules 42
ST2 Combining Assignment and Arithmetic 42
1 INTRODUCTION 1 ST3 Line Joining 43
ST2 Redirection of Input and Output 179 CE1 Trying to Modify Arguments 254
WE1 Analyzing Baby Names 407 ST3 Storing Data Records 475
TOOLBOX2 Working with Files and WE2 Translating Text Messages 476
Directories 410 8.3 Complex Structures 478
CS1 Encryption Algorithms 412 A Dictionary of Sets 478
7.4 Binary Files and Random Access A Dictionary of Lists 481
(Optional) 413 ST4 User Modules 484
Reading and Writing Binary Files 413 WE3 GRAPHICS: Pie Charts 484
Random Access 414 TOOLBOX1 Harvesting JSON Data from
Image Files 415 the Web 489
Processing BMP Files 416
WE2 GRAPHICS: Displaying a Scene File 419 9 OBJECTS AND CLASSES 499
7.5 Exception Handling 422
Raising Exceptions 423
9.1 Object-Oriented Programming 500
Handling Exceptions 424 9.2 Implementing a Simple Class 502
The finally Clause 426 9.3 Specifying the Public Interface of
PT1 Raise Early, Handle Late 428 a Class 506
PT2 Do Not Use except and finally in the
Same try Statement 428
9.4 Designing the Data Representation 508
PT1 Make All Instance Variables Private, Most
ST4 The with Statement 428
Methods Public 509
TOOLBOX3 Reading Web Pages 429
9.5 Constructors 510
7.6 APPLICATION: Handling Input Errors 430
CE1 Trying to Call a Constructor 512
TOOLBOX4 Statistical Analysis 433
ST1 Default and Named Arguments 512
WE3 Creating a Bubble Chart 438
CS2 The Ariane Rocket Incident 441 9.6 Implementing Methods 513
PT2 Define Instance Variables Only in the
Constructor 516
8 SETS AND ST2 Class Variables 516
DICTIONARIES 457 9.7 Testing a Class 517
8.1 Sets 458 HT1 Implementing a Class 519
WE1 Implementing a Bank Account Class 522
Creating and Using Sets 458
Adding and Removing Elements 459 9.8 PROBLEM SOLVING: Tracing Objects 525
Subsets 460 9.9 PROBLEM SOLVING: Patterns for
Set Union, Intersection, and Difference 461
Object Data 528
WE1 Counting Unique Words 465
Keeping a Total 528
Counting Events 529
Collecting Values 529 11 RECURSION 611
Managing Properties of an Object 530
Modeling Objects with Distinct States 530 11.1 Triangle Numbers Revisited 612
Describing the Position of an Object 531 CE1 Infinite Recursion 615
CS1 Electronic Voting Machines 533 ST1 Recursion with Objects 616
9.10 Object References 534 11.2 PROBLEM SOLVING: Thinking
Shared References 534 Recursively 616
The None Reference 536 WE1 Finding Files 620
The self Reference 536
11.3 Recursive Helper Functions 621
The Lifetime of Objects 537
11.4 The Efficiency of Recursion 622
9.11 APPLICATION: Writing a Fraction
Class 538 11.5 Permutations 627
CS1 The Limits of Computation 630
Fraction Class Design 538
The Constructor 539 11.6 Backtracking 631
Special Methods 540 WE2 Towers of Hanoi 636
Arithmetic Operations 542
11.7 Mutual Recursion 639
Logical Operations 543
TOOLBOX1 Analyzing Web Pages with
ST3 Object Types and Instances 546 Beautiful Soup 643
WE2 GRAPHICS: A Die Class 547
CS2 Open Source and Free Software 550
12 SORTING AND
SEARCHING 655
10 INHERITANCE 563
12.1 Selection Sort 656
10.1 Inheritance Hierarchies 564
12.2 Profiling the Selection Sort
PT1 Use a Single Class for Variation in Values,
Inheritance for Variation in Behavior 567
Algorithm 658
ST1 The Cosmic Superclass: object 568 12.3 Analyzing the Performance of the
10.2 Implementing Subclasses 569 Selection Sort Algorithm 660
ST1 Oh, Omega, and Theta 662
CE1 Confusing Super- and Subclasses 572
ST2 Insertion Sort 663
10.3 Calling the Superclass Constructor 573
12.4 Merge Sort 664
10.4 Overriding Methods 577
CE2 Forgetting to Use the super Function When
12.5 Analyzing the Merge Sort Algorithm 667
Invoking a Superclass Method 580 ST3 The Quicksort Algorithm 669
Programming
Special Topics Random Facts
Tips
© Stephen Coburn/123RF.com.
© Mikhail Mishchenko/123RF Limited. © modella/123RF.com.
Interactive Mode 9 The Python Interpreter 10 Computers Are Everywhere 5
Backup Copies 9
Count Iterations 191 Processing Sentinel Values The First Bug 172
with a Boolean Variable 179 Digital Piracy 223
Redirection of Input and
Output 179
Special Form of the print
Function 188
7 Backslashes in File Names 388 Working with CSV Files 399 Processing Text Files 404
Working with Files and Analyzing Baby Names 407
Directories 410 Graphics: Displaying a
Reading Web Pages 429 Scene File 419
Statistical Analysis 433
Creating a Bubble Chart 438
11 Infinite Recursion 615 Analyzing Web Pages with Finding Files 620
Beautiful Soup 643 Towers of Hanoi 636
Programming
Special Topics Random Facts
Tips
© Stephen Coburn/123RF.com.
Use ListsMishchenko/123RF
© Mikhail for SequencesLimited.
of Reverse Subscripts
© modella/123RF.com. 320 Computer Viruses 321
Related Items 321 Slices 328
Call by Value and
Call by Reference 341
Tuples 342
Functions with a Variable
Number of Arguments 342
Tuple Assignment 343
Returning Multiple Values
with Tuples 343
Tables with Variable
Row Lengths 364
Raise Early, Handle Late 428 Reading the Entire File 397 Encryption Algorithms 412
Do Not Use except and finally Regular Expressions 397 The Ariane Rocket Incident 441
in the Same try Statement 428 Character Encodings 398
The with Statement 428
Use Python Sets, Not Lists, for Hashing 467 Standardization 468
Efficient Set Operations 466 Iterating over
Dictionary Items 475
Storing Data Records 475
User Modules 484
Make all Instance Variables Private, Default and Named Electronic Voting Machines 533
Most Methods Public 509 Arguments 512 Open Source and
Define Instance Variables Class Variables 516 Free Software 550
Only in the Constructor 516 Object Types and Instances 546
Searching and Sorting 679 Oh, Omega, and Theta 662 The First Programmer 683
Insertion Sort 663
The Quicksort Algorithm 669
Comparing Objects 679
1
INTRODUCTION
CHAPTER GOALS
CHAPTER CONTENTS
© JanPietruszka/iStockphoto.
JanPietruszka/iStockphoto.
2
1.2 The Anatomy of a Computer 3
make small changes in a program that lead to immediate improvements, and to see the
computer become an extension of your mental powers.
Figure 1 Central
© Amorphis/iStockphoto. Processing Unit Figure 2 A Hard Disk
PhotoDisc, Inc./Getty Images, Inc.
4 Chapter 1 Introduction
Printer
CPU
Monitor
Microphone
Memory
Speakers
Network
controller Internet
To interact with a human user, a computer requires peripheral devices. The com-
puter transmits information (called output) to the user through a display screen,
speakers, and printers. The user can enter information (called input) for the computer
by using a keyboard or a pointing device such as a mouse.
Some computers are self-contained units, whereas others are interconnected
through networks. Through the network cabling, the computer can read data and
programs from central storage locations or send data to other computers. To the user
of a networked computer, it may not even be obvious which data reside on the com-
puter itself and which are transmitted through the network.
Figure 3 gives a schematic overview of the architecture of a personal computer.
Program instructions and data (such as text, numbers, audio, or video) are stored on
the hard disk, on a compact disk (or DVD), or elsewhere on the network. When a
program is started, it is brought into memory, where the CPU can read it. The CPU
reads the program one instruction at a time. As directed by these instructions, the
CPU reads data, modifies it, and writes it back to memory or the hard disk. Some pro-
gram instructions will cause the CPU to place dots on the display screen or printer or
to vibrate the speaker. As these actions happen many times over and at great speed,
the human user will perceive images and sound. Some program instructions read user
input from the keyboard or mouse. The program analyzes the nature of these inputs
and then executes the next appropriate instruction.
© UPPA/Photoshot.
SELF CHECK 6. Why don’t you specify a program directly in CPU instructions?
7. What are the two most important benefits of the Python language?
Practice
© Nicholas It Now you
Homrich/iStockphoto. can try this exercise at the end of the chapter: R1.5.
Figure 5
Running the
hello.py Program
in an Integrated
Development
Environment
© Tatiana Popova/iStockphoto.
You will spend many hours creating and improving Python pro-
grams. It is easy to delete a file by accident, and occasionally files
are lost because of a computer malfunction. Retyping the contents
of lost files is frustrating and time-consuming. It is therefore cru-
cially important that you learn how to safeguard files and get in
the habit of doing so before disaster strikes. Backing up files on a
memory stick is an easy and convenient storage method for many
people.
© Mikhail Mishchenko/123RF Another increasingly popular form of backup is Internet
Limited.
file storage. Here are a few pointers to keep in mind: © Tatiana Popova/iStockphoto.
• Back up often. Backing up a file takes only a few seconds, and you will hate yourself if
Develop a strategy
for keeping backup you have to spend many hours recreating work that you could have saved easily. We
copies of your work recommend that you back up your work once every thirty minutes.
before disaster
• Rotate backups. Use more than one directory for backups, and rotate them. That is, first
strikes.
back up onto the first directory. Then back up onto the second directory. Then use the
10 Chapter 1 Introduction
third, and then go back to the first. That way you always have three recent backups. If
your recent changes made matters worse, you can then go back to the older version.
• Pay attention to the backup direction. Backing up involves copying files from one place to
another. It is important that you do this right—that is, copy from your work location to
the backup location. If you do it the wrong way, you will overwrite a newer file with an
older version.
• Check your backups once in a while. Double-check that your backups are where you think
they are. There is nothing more frustrating than to find out that the backups are not there
when you need them.
• Relax, then restore. When you lose a file and need to restore it from a backup, you are
likely to be in an unhappy, nervous state. Take a deep breath and think through the
recovery process before you start. It is not uncommon for an agitated computer user to
wipe out the last backup when trying to restore a damaged file.
Python Interpreter
Byte Virtual
Compiler
code Machine
Editor
Running
Source File Program
Library
modules
ch01/sec04/hello.py
© Amanda Rohde/iStockphoto.
A Python program contains one or more lines of instructions or statements that will
be translated and executed by the Python interpreter. The first line
# My first Python program.
© Amanda Rohde/iStockphoto.
A comment provides
is a comment. Comments begin with # and are not statements. They provide descrip-
information to the tive information to the programmer. Comments will be discussed in more detail in
programmer. Section 2.1.5.
The second line contains a statement
print("Hello, World!")
A function is
that prints or displays a line of text, namely “Hello, World!”. In this statement, we
a collection of call a function named print and pass it the information to be displayed. A function is
instructions a collection of programming instructions that carry out a particular task. We do not
that perform a
particular task.
have to implement this function, it is part of the Python language. We simply want
the function to perform its intended task, namely to print a value.
To use, or call, a function in Python, you need to specify:
A function is called
1. The name of the function you want to use (in this case, print).
by specifying the 2. Any values the function needs to carry out its task (in this case, "Hello, World!").
function name and
its arguments.
The technical term for such a value is an argument. Arguments are enclosed in
parentheses; multiple arguments are separated by commas. The number of
arguments required depends on the function.
A sequence of characters enclosed in quotation marks
"Hello, World!"
A string is a sequence
is called a string. You must enclose the contents of the string inside quotation marks
of characters to make it clear that you literally mean "Hello, World!". There is a reason for this
enclosed in a pair requirement. Suppose you need to work with the word print. By enclosing it in quo-
of single or double
quotation marks.
tation marks, it is clear that "print" means the sequence of characters p r i n t, not the
function named print. The rule is simply that you must enclose all text strings in a pair
of either single (') or double (") quotation marks.
You can also print numerical values. For example, the statement
print(3 + 4)
evaluates the expression 3 + 4 and displays the number 7. You can pass multiple val-
ues to the function. For example,
print("The answer is", 6 * 7)
displays The answer is 42. Each value passed to the print function will be displayed,
one after the other in the order they are given and separated by a blank space. By
default, the print function starts a new line after its arguments are printed.
12 Chapter 1 Introduction
Syntax print()
print(value1, value2, ..., valuen)
For example,
print("Hello")
print("World!")
If no arguments are given to the print function, it starts a new line. This is similar to
pressing the Enter key in a text editor.
For example,
print("Hello")
print()
print("World!")
World
Statements in a Python program must begin in the same column. For example, the
following program
print("Hello")
print("World!")
Program Run
7
Hello
World!
My favorite numbers are 7 and 13
Goodbye
SELF CHECK 10. How do you modify the hello.py program to greet you instead?
11. How would you modify the hello.py program to print the word “Hello”
vertically?
12. Would
© Nicholas Homrich/iStockphoto. the program continue to work if you replaced line 2 of hello.py with:
print(Hello)
13. What does the following statement print?
print("My lucky numbers are", 3 * 4 + 5, 5 * 6 – 1)
14. What do the following statements print?
print("Hello")
print()
print("World")
Practice It Now you can try these exercises at the end of the chapter: R1.7, R1.8, P1.5, P1.7.
1.6 Errors
Experiment a little with the hello.py program.
What happens if you make a typing error such as
© Martin Carlsson/iStockphoto.
print("Hello, World!)
run. For this reason, compile-time errors are sometimes called syntax errors. When
such an error is found, no executable program is created. You must fix the error and
attempt to run the program again. The interpreter is quite picky, and it is common to go
through several rounds of fixing compile-time errors before the program runs for the
first time. In this case, the fix is simple: add a quotation mark at the end of the string.
Unfortunately, the interpreter is not very smart and often provides no help in
identifying the syntax error. For example, suppose you forget both quotation marks
around a string
print(Hello, World!)
This statement does not violate the rules of the Python language, and the program
will start running. However, when the division by zero occurs, the program will stop
and display the following error message:
Traceback (most recent call last):
File "hello.py", line 3, in <module>
ZeroDivisionError: int division or modulo by zero
An exception
This is called an exception. Unlike a compile-time error, which is reported as the pro-
occurs when an gram code is analyzed, an exception occurs when the program runs. An exception is
instruction is a run-time error.
syntactically correct,
but impossible to
There is another kind of run-time error. Consider a program that contains the fol-
perform. lowing statement:
print("Hello, Word!")
A run-time error is
The program is syntactically correct and runs without exceptions, but it doesn’t pro-
any error that occurs duce the results we expected. Instead of printing “Hello, World!”, it prints “Word” in
when the program place of “World”.
compiles and
runs, but produces
Some people use the term logic error instead of run-time error. After all, when the
unexpected results. program misbehaves, something is wrong with the program logic. A well-written
program would make sure that there are no divisions by zero and no faulty outputs.
During program development, errors are unavoidable. Once a program is longer
than a few lines, it would require superhuman concentration to enter it correctly with-
out slipping up once. You will find yourself misspelling words, omitting quotation
marks, or trying to perform an invalid operation more often than you would like.
Fortunately, these problems are reported at compile-time, and you can fix them.
Run-time errors are more troublesome. They are the harder to find and fix because
the interpreter cannot flag them for us. It is the responsibility of the program author
to test the program and prevent any run-time errors.
SELF CHECK
15. Suppose you omit the "" characters around Hello, World! from the hello.py
program. Is this a compile-time error or a run-time error?
© Nicholas Homrich/iStockphoto.
1.7 Problem Solving: Algorithm Design 15
16. Suppose you change the parentheses used with the print function to curly
braces. Is this a compile-time error or a run-time error?
17. Suppose you omit the hash symbol (#) that indicates a comment from the first
line of the hello.py program. Is this a compile-time error or a run-time error?
18. When you used your computer, you may have experienced a program that
“crashed” (quit spontaneously) or “hung” (failed to respond to your input). Is
that behavior a compile-time error or a run-time error?
19. Why can’t you test a program for run-time errors when it has compile-time
errors?
Practice It Now you can try these exercises at the end of the chapter: R1.9, R1.10, R1.11.
objective standard for good looks, and your brother’s opinion (or that of a computer
program analyzing the digitized photo) will likely be different from yours. If you
can’t give written instructions for someone to solve the problem, there is no way the
computer can magically find the right solution. The computer can only do what you
tell it to do. It just does it faster, without getting bored or exhausted. For that reason,
a computerized match-making service cannot guarantee to find the optimal match for
you.
Contrast the problem of finding partners with the following problem:
You put $10,000 into a bank account that earns 5 percent interest per year. How many
years does it take for the account balance to be double the original?
Could you solve this problem by hand? Sure, you could. You figure out the balance
as follows:
You keep going until the balance is at least $20,000. Then the last number in the year
column is the answer.
Of course, carrying out this computation is intensely boring to you (and your
younger brother). But computers are very good at carrying out repetitive calcula-
tions quickly and flawlessly. What is important to the computer is a description of the
steps for finding the solution. Each step must be clear and unambiguous, requiring no
guesswork. Here is such a description:
Start with a year value of 0, a column for the interest, and a balance of $10,000.
Repeat the following steps while the balance is less than $20,000
Add 1 to the year value.
Compute the interest as balance x 0.05 (i.e., 5 percent interest).
Add the interest to the balance.
14 942.82 19799.32
15 989.96 20789.28
Pseudocode is an
Of course, these steps are not yet in a language that a computer can understand, but
informal description you will soon learn how to formulate them in Python. This informal description is
of a sequence of called pseudocode.
steps for solving a
problem.
There are no strict requirements for pseudocode because it is read by human read-
ers, not a computer program. Here are the kinds of pseudocode statements that we
will use in this book:
• Use statements such as the following to describe how a value is set or changed:
total cost = purchase price + operating cost
Multiply the balance value by 1.05.
Remove the first and last character from the word.
• You can describe decisions and repetitions as follows:
If total cost 1 < total cost 2
While the balance is less than $20,000
For each picture in the sequence
Use indentation to indicate which statements should be selected or repeated:
For each car
operating cost = 10 x annual fuel cost
total cost = purchase price + operating cost
Here, the indentation indicates that both statements should be executed for
each car.
• Indicate results with statements such as:
Choose car1.
Report the final year value as the answer.
The exact wording is not important. What is important is that pseudocode describes
a sequence of steps that is
• Unambiguous
• Executable
• Terminating
An algorithm for
The step sequence is unambiguous when there are
solving a problem is precise instructions for what to do at each step and
a sequence of steps where to go next. There is no room for guesswork
that is unambiguous,
executable, and
or personal opinion. A step is executable when it
terminating. can be carried out in practice. Had we said to use
the actual interest rate that will be charged in years
to come, and not a fixed rate of 5 percent per year,
that step would not have been executable, because
© Claudiad/iStockphoto.
© Claudiad/iStockphoto.
18 Chapter 1 Introduction
Develop and
describe an
A sequence of steps that is unambiguous, executable, and termi- algorithm
nating is called an algorithm. We have found an algorithm to solve
our investment problem, and thus we can find the solution by pro-
gramming a computer. The existence of an algorithm is an essential
Test the
prerequisite for programming a task. You need to first discover and algorithm with
describe an algorithm for the task that you want to solve before you simple inputs
start programming (see Figure 8).
Translate
the algorithm
SELF CHECK 20. Suppose the interest rate was 20 percent. How long would it into Python
take for the investment to double?
21. Suppose your cell phone carrier charges you $29.95 for up to
300 minutes of calls, and $0.45 for each additional minute, plus
© Nicholas Homrich/iStockphoto. Compile and test
12.5 percent taxes and fees. Give an algorithm to compute the your program
monthly charge from a given number of minutes.
22. Consider the following pseudocode for finding the most at-
tractive photo from a sequence of photos:
Pick the first photo and call it "the best so far".
For each photo in the sequence
If it is more attractive than the "best so far"
Discard "the best so far".
Call this photo "the best so far".
The photo called "the best so far" is the most attractive photo in the sequence.
Is this an algorithm that will find the most attractive photo?
23. Suppose each photo in Self Check 22 had a price tag. Give an algorithm for find-
ing the most expensive photo.
24. Suppose you have a random sequence of black and white marbles and want to
rearrange it so that the black and white marbles are grouped together. Consider
this algorithm:
Repeat until sorted
Locate the first black marble that is preceded by a white marble, and switch them.
What does the algorithm do with the sequence mlmll? Spell out the steps
until the algorithm stops.
25. Suppose you have a random sequence of colored marbles. Consider this
pseudocode:
Repeat until sorted
Locate the first marble that is preceded by a marble of a different color, and switch them.
Why is this not an algorithm?
Practice It Now you can try these exercises at the end of the chapter: R1.15, R1.17, P1.4.
1.7 Problem Solving: Algorithm Design 19
© dlewis33/iStockphoto.
One is more fuel efficient than the other, but also more expen-
© Steve Simzer/iStockphoto.
sive. You know the price and fuel efficiency (in miles per gallon,
mpg) of both cars. You plan to keep the car for ten years. Assume
a price of $4 per gallon of gas and usage of 15,000 miles per year.
You will pay cash for the car and not worry about financing
costs. Which car is the better deal?
For each car, we need to know the total cost of driving it. Let’s do this computation separately
for each car. Once we have the total cost for each car, we can decide which car is the better deal.
The total cost for each car is purchase price + operating cost.
We assume a constant usage and gas price for ten years, so the operating cost depends on the
cost of driving the car for one year.
The operating cost is 10 x annual fuel cost.
The annual fuel cost is price per gallon x annual fuel consumed.
The annual fuel consumed is annual miles driven / fuel efficiency. For example, if you drive the car
for 15,000 miles and the fuel efficiency is 15 miles/gallon, the car consumes 1,000 gallons.
Step 3 Describe each subtask in pseudocode.
In your description, arrange the steps so that any intermediate values are computed before
they are needed in other computations. For example, list the step
total cost = purchase price + operating cost
after you have computed operating cost.
Here is the algorithm for deciding which car to buy:
For each car, compute the total cost as follows:
annual fuel consumed = annual miles driven / fuel efficiency
annual fuel cost = price per gallon x annual fuel consumed
operating cost = 10 x annual fuel cost
total cost = purchase price + operating cost
If total cost1 < total cost2
Choose car1.
Else
Choose car2.
20 Chapter 1 Introduction
Problem Statement Make a plan for tiling a rectangular bathroom floor with alternating
black and white tiles measuring 4 × 4 inches. The floor dimensions, measured in inches, are
multiples of 4.
Step 1
© Tom Horyn/iStockphoto. Determine the inputs and outputs.
© kilukilu/Shutterstock.
The inputs are the floor dimensions (length × width), measured
in inches. The output is a tiled floor.
Step 2 Break down the problem into smaller tasks.
A natural subtask is to lay one row of tiles. If you can solve that,
then you can solve the problem by laying one row next to the © kilukilu/Shutterstock.
other, starting from a wall, until you reach the opposite wall.
How do you lay a row? Start with a tile at one wall. If it is white, put a black one next to it.
If it is black, put a white one next to it. Keep going until you reach the opposite wall. The row
will contain width / 4 tiles.
Step 3 Describe each subtask in pseudocode.
In the pseudocode, you want to be more precise about exactly where the tiles are placed.
Place a black tile in the northwest corner.
While the floor is not yet filled, repeat the following steps:
Repeat this step width / 4 – 1 times:
Place a tile east of the previously placed tile. If the previously placed tile was white, pick a black one;
otherwise, a white one.
Locate the tile at the beginning of the row that you just placed. If there is space to the south, place a tile of
the opposite color below it.
Step 4 Test your pseudocode by working a sample problem.
Suppose you want to tile an area measuring 20 × 12 inches. The first step is to place a black tile
in the northwest corner.
20 inches
1
12 inches
Chapter Summary 21
Next, alternate four tiles until reaching the east wall. (width / 4 – 1 = 20 / 4 – 1 = 4)
1 2 3 4 5
There is room to the south. Locate the tile at the beginning of the completed row. It is black.
Place a white tile south of it.
1 2 3 4 5
6
There is still room to the south. Locate the tile at the beginning of the completed row. It is
white. Place a black tile south of it.
1 2 3 4 5
6 7 8 9 10
11
Complete the row.
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
CHAPTER SUMMARY
• The central processing unit (CPU) performs program control and data
processing.
• Storage devices include memory and secondary storage.
© Amorphis/iStockphoto.
22 Chapter 1 Introduction
• Set aside some time to become familiar with the programming environment that
you will use for your class work.
• A text editor is a program for entering and modifying text, such as a Python
program.
• Python is case sensitive. You must be careful about distinguishing between
upper- and lowercase letters.
• The Python interpreter reads Python programs and executes the program
instructions.
• Develop a strategy for keeping backup copies of your work before disaster
strikes.
© Tatiana Popova/iStockphoto.
Describe the building blocks of a simple program.
REVIEW EXERCISES
© Claudiad/iStockphoto.
• R1.1 Explain the difference between using a computer program and programming a
computer.
• R1.2 Which parts of a computer can store program code? Which can store user data?
• R1.3 Which parts of a computer serve to give information to the user? Which parts take
user input?
Review Exercises 23
••• R1.4 A toaster is a single-function device, but a computer can be programmed to carry out
different tasks. Is your cell phone a single-function device, or is it a programmable
computer? (Your answer will depend on your cell phone model.)
• R1.5 Which programming languages were mentioned in this chapter? When were they
invented? By whom? (Look it up on the Internet.)
•• R1.6 On your own computer or on a lab computer, find the exact location (folder or
directory name) of
a. The sample file hello.py, which you wrote with the editor.
b. The Python program launcher python, python.exe, or python.app.
•• R1.8 What does this program print? Pay close attention to spaces.
print("Hello", "World", "!")
•• R1.10 Write three versions of the hello.py program that have different compile-time errors.
Write a version that has a run-time error.
• R1.11 How do you discover compile-time errors? How do you discover run-time errors?
•• R1.12 Write an algorithm to settle the following question: A bank account starts out with
$10,000. Interest is compounded monthly at 0.5 percent per month. Every month,
$500 is withdrawn to meet college expenses. After how many years is the account
depleted?
••• R1.13 Consider the question in Exercise R1.12. Suppose the numbers ($10,000, 6 percent,
$500) were user selectable. Are there values for which the algorithm you developed
would not terminate? If so, change the algorithm to make sure it always terminates.
••• R1.14 In order to estimate the cost of painting a house, a painter needs to know the surface
area of the exterior. Develop an algorithm for computing that value. Your inputs are
the width, length, and height of the house, the number of windows and doors, and
their dimensions. (Assume the windows and doors have a uniform size.)
•• R1.15 You want to decide whether you should drive your car to work or take the train.
You know the one-way distance from your home to your place of work, and the
fuel efficiency of your car (in miles per gallon). You also know the one-way price of
a train ticket. You assume the cost of gas at $4 per gallon, and car maintenance at 5
cents per mile. Write an algorithm to decide which commute is cheaper.
•• R1.16 You want to find out which fraction of your car’s use is for commuting to work,
and which is for personal use. You know the one-way distance from your home to
work. For a particular period, you recorded the beginning and ending mileage on the
odometer and the number of work days. Write an algorithm to settle this question.
• R1.17 In How To 1.1, you made assumptions about the price of gas and annual usage to
compare cars. Ideally, you would like to know which car is the better deal without
making these assumptions. Why can’t a computer program solve that problem?
24 Chapter 1 Introduction
••• R1.18 The value of π can be computed according to the following formula:
π 1 1 1 1
= 1 − + − + −…
4 3 5 7 9
Write an algorithm to compute π. Because the formula is an infinite series and an
algorithm must stop after a finite number of steps, you should stop when you have
the result determined to six significant digits.
•• R1.19 Suppose you put your younger brother in charge of backing up your work. Write a
set of detailed instructions for carrying out his task. Explain how often he should do
it, and what files he needs to copy from which folder to which location. Explain how
he should verify that the backup was carried out correctly.
• Business R1.20 Imagine that you and a number of friends go to a luxury restaurant, and when you
ask for the bill you want to split the amount and the tip (15 percent) between all.
Write pseudocode for calculating the amount of money that everyone has to pay.
Your program should print the amount of the bill, the tip, the total cost, and the
amount each person has to pay. It should also print how much of what each person
pays is for the bill and for the tip.
PROGRAMMING EXERCISES
• P1.1 Write a program that prints a greeting of your choice, perhaps in a language other
than English.
•• P1.2 Write a program that prints the sum of the first ten positive integers, 1 + 2 + … + 10.
•• P1.3 Write a program that prints the product of the first ten positive integers, 1 × 2 × … ×
10. (Use * to indicate multiplication in Python.)
•• P1.4 Write a program that prints the balance of an account after the first, second, and
third year. The account has an initial balance of $1,000 and earns 5 percent interest
per year.
• P1.5 Write a program that displays your name inside a box on the screen, like this:
Dave
••• P1.6 Write a program that prints your name in large letters, such as
* * ** **** **** * *
* * * * * * * * * *
***** * * **** **** * *
* * ****** * * * * *
* * * * * * * * *
•• P1.7 Write a program that prints a face similar to (but different from) the following:
/////
+"""""+
(| o o |)
| ^ |
| '-' |
+-----+
Answers to Self-Check Questions 25
•• P1.8 Write a program that prints an imitation of a Piet Mondrian painting. (Search the
Internet if you are not familiar with his paintings.) Use character sequences such as
@@@ or ::: to indicate different colors, and use - and | to form lines.
•• P1.9 Write a program that prints a house that looks exactly like the following:
+
+ +
+ +
+-----+
| .-. |
| | | |
+-+-+-+
••• P1.10 Write a program that prints an animal speaking a greeting, similar to (but different
from) the following:
/\_/\ -----
( ' ' ) / Hello \
( - ) < Junior |
| | | \ Coder!/
(__|__) -----
• P1.11 Write a program that prints three items, such as the names of your three best friends
or favorite movies, on three separate lines.
• P1.12 Write a program that prints a poem of your choice. If you don’t have a favorite
poem, search the Internet for “Emily Dickinson” or “e e cummings”.
•• P1.13 Write a program that prints the United States flag, using * and = characters.
• Business P1.14 Write a program that prints a two-column list of your friends’ birthdays. In the first
column, print the names of your best friends; in the second column, print their
birthdays.
Sales Tax Rates
• Business P1.15 In the United States there is no federal sales tax, so every state -----------
may impose its own sales taxes. Look on the Internet for the sales Alaska: 0%
tax charged in five U.S. states, then write a program that prints the Hawaii: 4%
tax rate for five states of your choice. . . .
1. A program that reads the data from a sound 2. A CD player can do one thing—play music
file and sends output to the speakers and the CDs. It cannot execute programs.
screen. 3. Nothing.
26 Chapter 1 Introduction
4. In secondary storage, typically a hard disk. 21. Is the number of minutes at most 300?
5. The central processing unit. a. If so, the answer is $29.95 × 1.125 = $33.70.
6. (1) It would be very tedious to do so. b. If not,
(2) Programs that are written for one CPU are 1. Compute the difference: (number of
not portable to a different CPU type. minutes) – 300.
7. Ease of use and portability. 2. Multiply that difference by 0.45.
8. The answer varies among systems. A typical 3. Add $29.95.
answer might be /home/dave/cs1/hello/hello.py 4. Multiply the total by 1.125. That is the
or c:\Users\Dave\Workspace\hello\hello.py answer.
9. You back up your files and folders. 22. No. The step If it is more attractive than the "best
10. Change World to your name (here, Dave): so far" is not executable because there is no
print("Hello, Dave!")
objective way of deciding which of two photos
is more attractive.
11. print("H")
23. Pick the first photo and call it "the most expensive so far".
print("e")
print("l") For each photo in the sequence
print("l") If it is more expensive than "the most expensive so far"
print("o") Discard "the most expensive so far".
12. No. The interpreter would look for an
Call this photo "the most expensive so far".
The photo called "the most expensive so far" is the most
item whose name is Hello. You need to expensive photo in the sequence.
enclose Hello in quotation marks:
print("Hello") 24. The first black marble that is preceded by a
white one is marked in blue:
13. My lucky numbers are 17 29
mlmll
14. Hello
Switching the two yields
a blank line
World lmmll
15. This is a compile-time error at the point of the The next black marble to be switched is
! symbol. lmmll
16. This is a compile-time error at the point of the yielding
{ symbol.
lmlml
17. This is a compile-time error. The interpreter
The next steps are
will either complain of an indentation error or
a syntax error because plain sentences cannot llmml
be used as instructions. llmlm
18. It is a run-time error. After all, the program lllmm
had been compiled in order for you to run it. Now the sequence is sorted.
19. When a program has compile-time errors, the 25. The sequence doesn’t terminate. Consider the
interpreter stops translating the instructions input mlmlm. The first two marbles keep
and does not execute the program. getting switched.
20. 4 years:
0 10,000
1 12,000
2 14,400
3 17,280
4 20,736
2
PROGRAMMING
WITH NUMBERS
AND STRINGS
CHAPTER GOALS
CHAPTER CONTENTS
© samxmeg/iStockphoto.
2.1 Variables
When your program carries out computations, you will want to store values so that
you can use them later. In a Python program, you use variables to store values. In this
section, you will learn how to define and use variables.
To illustrate the use of variables, we
mxmeg/iStockphoto.
will develop a program that solves the
(bottle) © travismanley/iStockphoto.
following problem. Soft drinks are sold
(cans) © blackred/iStockphoto;
in cans and bottles. A store offers a six-
pack of 12-ounce cans for the same price
as a two-liter bottle. Which should you
buy? (Twelve fluid ounces equal approx-
imately 0.355 liters.)
In our program, we will define vari-
ables for the number of cans per pack
and for the volume of each can. Then we
(cans) © blackred/iStockphoto; (bottle) © travismanley/iStockphoto.
will compute the volume of a six-pack in What contains more soda? A six-pack of
liters and print out the answer. 12-ounce cans or a two-liter bottle?
A variable is a
A variable is a storage location in a computer program. Each variable has a name and
storage location holds a value.
with a name. A variable is similar to a parking space in a parking garage. The parking space has
an identifier (such as “J 053”), and it can hold a vehicle. A variable has a name (such as
cansPerPack), and it can hold a value (such as 6).
.
The expression that replaces the previous value
.
.
total = total + cans * CAN_VOLUME
An assignment
You use the assignment statement to place a value into a variable. Here is an
statement stores a example
value in a variable.
cansPerPack = 6 1 2
1 Because this is the first assignment, 2 The variable is initialized. 3 The second assignment overwrites
the variable is created. the stored value.
ebookgate.com