(eBook PDF) Python for Everyone, 2nd Edition by Cay S. Horstmann download
(eBook PDF) Python for Everyone, 2nd Edition by Cay S. Horstmann download
https://ebooksecure.com/product/ebook-pdf-python-for-
everyone-2nd-edition-by-cay-s-horstmann/
http://ebooksecure.com/product/ebook-pdf-big-java-early-
objects-6th-edition-by-cay-s-horstmann/
https://ebooksecure.com/download/op-amps-for-everyone-ebook-pdf/
http://ebooksecure.com/product/python-for-dummies-1st-edition-
pdf-version/
http://ebooksecure.com/product/ebook-pdf-police-2nd-edition-by-
john-s-dempsey/
(eBook PDF) Fundamentals of Python: First Programs 2nd
Edition
http://ebooksecure.com/product/ebook-pdf-fundamentals-of-python-
first-programs-2nd-edition/
http://ebooksecure.com/product/ebook-pdf-abnormal-psychology-2nd-
edition-by-robin-s-rosenberg/
http://ebooksecure.com/product/original-pdf-foundations-of-
criminal-justice-2nd-edition-by-stephen-s-owen/
http://ebooksecure.com/product/ebook-pdf-django-for-
professionals-production-websites-with-python-django/
https://ebooksecure.com/download/fundamentals-of-python-data-
structures-ebook-pdf/
Python for
Everyone
2/e
Cay Horstmann
Rance Necaise
vi Preface
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.
Preface vii
Acknowledgments
Many thanks to Byran Gambrel, Don Fowley, Jessy Moor, Jennifer Lartz, Graig
Donini, and Billy Ray at John Wiley & Sons, and Vickie Piercey at Publishing Ser-
vices for their help with this project. An especially deep acknowledgment and thanks
goes to Cindy Johnson for her hard work, sound judgment, and amazing attention to
detail.
We are grateful to the following for their excellent work preparing and reviewing
the supplemental materials:
Jim Carrier, Guilford Technical Community College
Akshaye Dhawan, Ursinus College
Byron Hoy, Stockton University
Maria Laurent-Rice, Orange Coast College
John McManus, Randolph-Macon College
Ben Stephenson, University of Calgary
Amanda Stouder, Rose-Hulman Institute of Technology
Dean Zeller, University of Northern Colorado
Many thanks to the individuals who provided feedback, reviewed the manuscript,
made valuable suggestions, and brought errors and omissions to our attention. They
include:
Claude Anderson, Rose Hulman Institute of Technology
Gokcen Cilingir, Washington State University
Lee D. Cornell, Minnesota State University, Mankato
Dirk Grunwald, University of Colorado Boulder
Andrew Harrington, Loyola University Chicago
Debbie Keen, University of Kentucky
Nicholas A. Kraft, University of Alabama
Aaron Langille, Laurentian University
Shyamal Mitra, University of Texas Austin
Chandan R. Rupakheti, Rose-Hulman Institute of Technology
John Schneider, Washington State University
Amit Singhal, University of Rochester
Ben Stephenson, University of Calgary
Amanda Stouder, Rose-Hulman Institute of Technology
Dave Sullivan, Boston University
Jay Summet, Georgia Institute of Technology
James Tam, University of Calgary
Krishnaprasad Thirunarayan, Wright State University
Leon Tietz, Minnesota State University, Mankato
Peter Tucker, Whitworth University
Frances VanScoy, West Virginia University
viii Walkthrough
ch01/hello.py
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
Throughout each chapter, # My first Python program.
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.
A function is called
To use, or call, a function in Python, you need to specify
by specifying the
1. The name of the function you want to use (in this case, print).
function name and
its arguments. 2. Any values the function needs to carry out its task (in this case, "Hello, World!").
The technical term for such a value is an argument. Arguments are enclosed in
Annotated syntax boxes parentheses with multiple arguments separated by commas. The number of
arguments required depends on the function.
provide a quick, visual overview
of new language constructs.
Syntax 1.1 print Statement
Syntax print()
print(value1, value2, ..., valuen)
A recipe for a fruit pie may say to use any kind of fruit.
Here, “fruit” is an example of a parameter variable.
Apples and cherries are examples of arguments.
evaluating proposed solutions, often Now how does that help us with our problem, switching the first and the second
using pencil and paper or other half of the list?
Let’s put the first coin into place, by swapping it with the fifth coin. However, as
artifacts. These sections emphasize Python programmers, we will say that we swap the coins in positions 0 and 4:
Figure 2
1 Check the loop condition
Execution of the
doubleinv.py Loop while balance < TARGET :
The condition is true
Progressive figures trace code
10000.0
segments to help students visualize
balance = year = year + 1
interest = balance * RATE / 100
year = 0 balance = balance + interest
the program flow. Color is used
2 Execute the statements in the loop consistently to make variables and
balance = 10500.0
while balance < TARGET :
year = year + 1 other elements easily recognizable.
interest = balance * RATE / 100 g
year = 1 balance = balance + interest
the new material—and can 27. Write a for loop that prints all even numbers between 10 and 20 (inclusive).
28. Write a for loop that computes the total of the integers from 1 to n.
spark discussion in lecture. 29. How would you modify the loop of the investment.py program to print all bal-
ances until the investment has doubled?
Practice It Now you can try these exercises at the end of the chapter: R4.18, R4.19, P4.8.
business exercises engage •• Business P4.29 Write a program that first asks the user
•• Graphics P2.30 Write
to type a program
in today’s pricethat displays
of one dollarthe Olympic rings. Color the rings in the Olympic
students with realistic applications. colors.yen, then reads U.S. dollar
in Japanese
l d h
Most spreadsheet applications store their data in proprietary file formats that cannot be
accessed directly by other programs. Fortunately, most can save a copy of the data in a porta-
ble format known as CSV (Comma-Separated Values). A CSV file is simply a text file in which
each row of the spreadsheet is stored as a line of text. The data values in each row are separated
by commas. For example, the CSV file created from the spreadsheet shown above contains:
Common Errors describe the kinds Common Error 3.2 Exact Comparison of Floating-Point Numbers
Floating-point numbers have only a limited precision, and cal-
of errors that students often make, culations can introduce roundoff errors. You must take these
inevitable roundoffs into account when comparing floating-
with an explanation of why the errors point numbers. For example, the following code multiplies the
square root of 2 by itself. Ideally, we expect to get the answer 2:
occur, and what to do about them. from math import sqrt
r = sqrt(2.0)
if r * r == 2.0 : Take limited precision into
print("sqrt(2.0) squared is 2.0") account when comparing
else : floating-point numbers.
print("sqrt(2.0) squared is not 2.0 but", r * r)
This program displays
sqrt(2.0) squared is not 2.0 but 2.0000000000000004
Hand-Tracing It does not make sense in most circumstances to compare floating-point numbers exactly.
Programming Tip 3.2 Instead, we should test whether they are close enough. That is, the magnitude of their differ-
A very useful technique for ence understanding whether
should be less a prothreshold.
than some gram Mathematically, we would write that x and y are close
works correctly is called hand-tracing.
enough if You simulate the pro-
gram’s activity on a sheet of paper. You can use this method with
pseudocode or Python code.
Get an index card, a cocktail napkin, or whatever sheet of paper
is within reach. Make a column for each variable. Have the pro-
gram code ready. Use a marker, such as a paper clip, to mark the
current statement. In your mind, execute statements one at a time.
Programming Tips explain Every time the value of a variable changes, cross out the old value
and write the new value below the old one. Hand-tracing helps you
good programming practices, Let’s trace the taxes.py program on page 107 with the inputs from understand whether a
the program run that follows it. In lines 12 and 13, income and program works correctly.
and encourage students to be maritalStatus are initialized by input statements.
Suppose the value of quantity is zero. Then the test quantity > 0 fails, and the second test is not
attempted. That is just as well, because it is illegal to divide by zero.
Similarly, when the first condition of an or expres-
sion is true, then the remainder is not evaluated because
Special Topics present optional the result must be true.
topics and provide additional In a short circuit, electricity travels along the path of
least resistance. Similarly, short-circuit evaluation
explanation of others. takes the fastest path for computing the result
of a Boolean expression.
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
xii
Contents xiii
ST2 Redirection of Input and Output 179 CE1 Trying to Modify Arguments 254
7.2 Text Input and Output 388 PT1 Use Python Sets, Not Lists, for Efficient Set
Iterating over the Lines of a File 388 Operations 466
Reading Words 390 ST1 Hashing 467
Reading Characters 392 CS1 Standardization 468
Reading Records 393 8.2 Dictionaries 468
ST1 Reading the Entire File 397 Creating Dictionaries 469
ST2 Regular Expressions 397 Accessing Dictionary Values 470
ST3 Character Encodings 398 Adding and Modifying Items 470
TOOLBOX1 Working with CSV Files 399 Removing Items 471
7.3 Command Line Arguments 401 Traversing a Dictionary 472
HT1 Processing Text Files 404 ST2 Iterating over Dictionary Items 475
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
xvi Contents
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
For Clora, maybe—C.H.
To my parents
Willard and Ella—R.N.
CHAPTER 1
INTRODUCTION
CHAPTER GOALS
CHAPTER CONTENTS
1
Another Random Scribd Document
with Unrelated Content
Janne oli seisahtunut Eeron eteen ja lausui viimeiset sanansa
omituisella äänen painolla, aivan kuin olisi itseltään epäillen kysynyt,
oliko se mahdollista, ja hän lisäsi samaan tapaan:
— Älä nyt noin, Janne… eihän hukka niin pian peri, totta tämä on
autettavissa. Ethän sinä, Janne, ennen ole juopotellut?
— Ai ai, Janne, siinä olet tehnyt väärin, kun tiesit kumminkin, ettei
Leena siitä pitänyt.
— Niin niin, väärin olen tehnyt, sen minä nyt ymmärrän. Mutta voi,
ei se sillä parane, en minä sillä häntä takaisin saa, ja minä en jaksa
elää ilman häntä. Hän on niin kaunis, niin kaunis.
— Kuules, Janne!
— Mitä?
Eero oli äkkiä keksinyt pelastuskeinon, ja hänen silmänsä loistivat.
— On.
— En.
— Aah!
— Luulen.
— Niin on tapahtuva kuin sinä ehdotit, Eero. Hän oli nyt aivan
tyyni, ja vähän entistä reippautta loisti silmistä.
— Mitä? puhemiehenä?
— Kyllä suostun.
— Nyt samallako?
Kuinka kaikki oli toisenlaista nyt kuin silloin. Ihan pelotti ajatella,
mitä muutoksia aika oli tuonut mukanaan. Silloin oli mieli vielä
täynnä uskallusta ja uskoa, uskoa ei niin paljon itseensä kuin muihin,
kuin siihen, että maailma on hyvä, että ihmiset ovat jaloja, että
elämä on ihana. Silloin ei ollut ystäviä muita kuin Aarno, mutta
kuinka rakas, kuinka luotettava, kuinka ihailtava se ystävä oli! Ja
Eero oli käynyt miettimään suhdettansa tuohon nuoruutensa
uskottuun, tuohon sielunsa lemmittyyn, ja kun hän ajatteli, että se
sama suhde nyt oli rikkoutunut, että liitot ja lupaukset eivät
sittenkään voineet kestää elämän kourissa, niin kaipauksen kyynel
vieri hänen poskelleen, mutta katkeruus ei astunut hänen
sydämeensä tänä hiljaisena, runollisena yönä. Pysyttääkseen vienon
tunnelmansa ja elvyttääkseen vanhoja muistojaan, oli Eero
papereittensa joukosta hakenut pienen vihkosen, jonka kansilehdelle
oli sirosti piirrettynä eri riville nimet "Aarnolle Eero", — saman
vihkosen, johon hän sinä yönä kolme vuotta takaperin oli sydämensä
vuodattanut. Sitä hän nyt kynttilän valossa istui lukemaan, ja sen
sisältö oli näin kuuluva:
Muistatko?
— Jaa Aarnoko?
— Aarno, niin.
— Kuljin.
— Paleletko, Aarno?
— Todellako nukuit?
— Minun on kylmä.
— Hyvä.
ystävältäsi Eerolta.'
— Kuule, mitä sinä oikein olet juonut, Aarno?… Minä en ole yhtään
hutikassa…
— Onhan se!
— Niin, onhan se. Est, est… kuinka se Caesarin lause taas kuuluu?
— Mikä?
"Minä, joka olin toivonut heistä aivan toista! Olin toivonut, että he
kaikissa tapauksissa säilyttäisivät pyhänä uskonsa puhtauteen,
siveyteen, miehuuteen. Olin toivonut, etteivät he luopuisi hyvästä,
jos kohta luopuivat minusta ja minun pyrinnöistäni…
Eero kyllä kuuli, että Aarno pyrki sisään, että hän koputti ovelle ja
sammalti jotakin Tuomolle, että hänen kiihkonsa yltyi jostain tämän
vastauksesta ja että hän oli vähällä ruveta meluamaan, mutta kun
sitten äkkiä kaikki hiljeni, ja Tuomo arvattavasti sai Aarnon
luopumaan aikeestaan, ei Eerokaan hievahtanut paikaltaan, makasi
siellä vain synkissä mietteissään ja surunvoittoisissa tunteissaan,
kunnes vihdoin nukkui levottomaan uneen.
VI.
Kun sitten tuli käsky päivällisille ja kaikki kolme taas olivat koolla,
huomasi Eero oitis, että Aarnon ja Tuomon käytös oli vapaampi kuin
aamulla, jopa yrittivät lausua jonkun ystävällisen sanankin. Eero
kuitenkin pysyi totisena ja mykkänä ja tunsi miltei loukkaantuvansa
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about testbank and eager to explore new worlds of
knowledge? At our website, we offer a vast collection of books that
cater to every interest and age group. From classic literature to
specialized publications, self-help books, and children’s stories, we
have it all! Each book is a gateway to new adventures, helping you
expand your knowledge and nourish your soul
Experience Convenient and Enjoyable Book Shopping Our website is more
than just an online bookstore—it’s a bridge connecting readers to the
timeless values of culture and wisdom. With a sleek and user-friendly
interface and a smart search system, you can find your favorite books
quickly and easily. Enjoy special promotions, fast home delivery, and
a seamless shopping experience that saves you time and enhances your
love for reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebooksecure.com