0% found this document useful (0 votes)
18 views

101331

The document promotes various programming ebooks available for instant download at ebookgate.com, including titles such as 'Python for Everyone' and 'Object Oriented Design and Patterns.' It highlights the features of the second edition of 'Python for Everyone,' which serves as an introductory programming guide using Python, emphasizing effective learning and problem-solving strategies. Additionally, it outlines the availability of interactive content and online resources to enhance the learning experience for students.

Uploaded by

vigenageb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

101331

The document promotes various programming ebooks available for instant download at ebookgate.com, including titles such as 'Python for Everyone' and 'Object Oriented Design and Patterns.' It highlights the features of the second edition of 'Python for Everyone,' which serves as an introductory programming guide using Python, emphasizing effective learning and problem-solving strategies. Additionally, it outlines the availability of interactive content and online resources to enhance the learning experience for students.

Uploaded by

vigenageb
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Instant Ebook Access, One Click Away – Begin at ebookgate.

com

Python for Everyone 2nd Edition Cay Horstmann

https://ebookgate.com/product/python-for-everyone-2nd-
edition-cay-horstmann/

OR CLICK BUTTON

DOWLOAD EBOOK

Get Instant Ebook Downloads – Browse at https://ebookgate.com


Click here to visit ebookgate.com and download ebook now
Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Python for Everyone 1st Edition Cay S. Horstmann

https://ebookgate.com/product/python-for-everyone-1st-edition-cay-s-
horstmann/

ebookgate.com

Object Oriented Design and Patterns 2nd Edition Cay S.


Horstmann

https://ebookgate.com/product/object-oriented-design-and-patterns-2nd-
edition-cay-s-horstmann/

ebookgate.com

Java Concepts Late Objects 3rd Edition Edition Cay S.


Horstmann

https://ebookgate.com/product/java-concepts-late-objects-3rd-edition-
edition-cay-s-horstmann/

ebookgate.com

Mark for Everyone 2nd Edition Tom Wright

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

Python for Scientists 2nd Edition John M. Stewart

https://ebookgate.com/product/python-for-scientists-2nd-edition-john-
m-stewart/

ebookgate.com

Six Sigma for Everyone 1st Edition George Eckes

https://ebookgate.com/product/six-sigma-for-everyone-1st-edition-
george-eckes/

ebookgate.com

A Web for Everyone 1st Edition Sarah Horton

https://ebookgate.com/product/a-web-for-everyone-1st-edition-sarah-
horton/

ebookgate.com

Python The Complete Manual The essential handbook for


Python users Master Python today First Edition Unknown

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

Printed in the United States of America


P R E FA C E

This book is an introduction to computer programming using Python that focuses on


the essentials—and on effective learning. Designed to serve a wide range of student
interests and abilities, it is suitable for a first course in programming for computer
scientists, engineers, and students in other disciplines. No prior programming expe-
rience is required, and only a modest amount of high school algebra is needed. For
pedagogical reasons, the book uses Python 3, which is more regular than Python 2.
Here are the book’s key features:
Present fundamentals first.
The book takes a traditional route, first stressing control structures, functions, proce-
dural decomposition, and the built-in data structures. Objects are used when appro-
priate in the early chapters. Students start designing and implementing their own
classes in Chapter 9.
Guidance and worked examples help students succeed.
Beginning programmers often ask “How do I start? Now what do I do?” Of course,
an activity as complex as programming cannot be reduced to cookbook-style instruc-
tions. However, step-by-step guidance is immensely helpful for building confidence
and providing an outline for the task at hand. “Problem Solving” sections stress the
importance of design and planning. “How To” guides help students with common
programming tasks. Numerous Worked Examples demonstrate how to apply chap-
ter concepts to interesting problems.
Problem solving strategies are made explicit.
Practical, step-by-step illustrations of techniques help students devise and evaluate
solutions to programming problems. Introduced where they are most relevant, these
strategies address barriers to success for many students. Strategies included are:
• Algorithm Design (with pseudocode) • Stepwise Refinement
• First Do It By Hand (doing sample • Adapting Algorithms
calculations by hand) • Discovering Algorithms by
• Flowcharts Manipulating Physical Objects
• Test Cases • Tracing Objects
• Hand-Tracing • Patterns for Object Data
• Storyboards • Thinking Recursively
• Solve a Simpler Problem First • Estimating the Running Time of
• Reusable Functions an Algorithm

Practice makes perfect.


Of course, programming students need to be able to implement nontrivial programs,
but they first need to have the confidence that they can succeed. This book contains
a substantial number of self-check questions at the end of each section. “Practice It”
pointers suggest exercises to try after each section. And additional practice oppor-
tunities, including automatically-graded programming exercises and skill-oriented
multiple-choice questions, are available online.
A visual approach motivates the reader and eases navigation.
Photographs present visual analogies that explain the
nature and behavior of computer concepts. Step-by-
step figures illustrate complex program operations.
Syntax boxes and example tables present a variety
of typical and special cases in a compact format. It
is easy to get the “lay of the land” by browsing the
visuals, before focusing on the textual material.
Focus on the essentials while being
technically accurate.
An encyclopedic coverage is not helpful for a begin-
ning programmer, but neither is the opposite—
reducing the material to a list of simplistic bullet points. In this book, the essentials
are presented in digestible chunks, with separate notes that go deeper into good prac-
tices or language features when the reader is ready for the additional information.
© Terraxplorer/iStockphoto.

New to This Edition


Extended Graphics and Image Processing
The use of graphics to reinforce language constructs has been extended to include the
use of image processing. Students are introduced to image processing in Chapter 4 as
they learn to design and use loops and again in Chapter 5 where they build a toolkit of
image processing functions.

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.

A Tour of the Book


Figure 1 shows the dependencies between the chapters and how topics are organized.
The core material of the book is:
Chapter 1. Introduction Chapter 5. Functions
Chapter 2. Programming with Chapter 6. Lists
Numbers and Strings Chapter 7. Files and Exceptions
Chapter 3. Decisions Chapter 8. Sets and Dictionaries
Chapter 4. Loops

Two chapters cover object-oriented programming:


Chapter 9. Objects and Classes
Chapter 10. Inheritance
Two chapters support a course that goes more deeply into algorithm design and
analysis:
Chapter 11. Recursion
Chapter 12. Sorting and Searching

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

Sections 6.1 – 6.3


Sections 7.1 and 7.2 (lists) can be covered
(text file processing) can be with Chapter 4.
6.6.Iteration
Lists
covered with Chapter 4.

7. Files and 8. Sets and 9. Objects


6. Iteration 11. Recursion
Exceptions Dictionaries and Classes

Figure 1 12. Sorting


10. Inheritance
and Searching
Chapter Dependencies
Appendices Six appendices provide a handy reference for students on operator
precedence, reserved words, Unicode, the Python standard library, and more.

Graphics and Image Processing


Writing programs that create drawings or process images can provide students with
effective visualizations of complex topics. Chapter 2 introduces the EzGraphics
open-source library and how to use it to create basic graphical drawings. The library,
which students find easier to use than Python’s standard Tkinter library, also sup-
ports simple image processing. Graphics Worked Examples and exercises are pro-
vided throughout the text, all of which are optional.

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.

Custom Book and eBook Options


Python For Everyone may be ordered in both custom print and eBook formats. You
can order a custom print version that includes your choice of chapters—including
those from other Horstmann titles. Visit customselect.wiley.com to create your custom
order.
Python For Everyone is also available in an electronic eBook format with three key
advantages:
• The price is significantly lower than for the printed book.
• The eBook contains all material in the printed book plus the web appendices in
one easy-to-browse format.
• You can customize the eBook to include your choice of chapters.
The interactive edition of Python For Everyone adds even more value by integrating
a wealth of interactive exercises into the eBook. See http://wiley.com/go/pfe2interac-
tivities to find out more about this new format.
Please contact your Wiley sales rep for more information about any of these
options or check www.wiley.com/college/horstmann for available versions.

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

1.1 Computer Programs   2 2.3 PROBLEM SOLVING: First Do It By Hand   43


1.2 The Anatomy of a Computer   3 WE1 Computing Travel Time 45

CS1 Computers Are Everywhere 5 2.4 Strings  46


1.3 The Python Programming Language   5 The String Type 46
Concatenation and Repetition 47
1.4 Becoming Familiar with Your Programming
Converting Between Numbers and Strings 48
Environment  6 Strings and Characters 48
PT1 Interactive Mode 9 String Methods 50
PT2 Backup Copies 9 ST4 Character Values 51
ST1 The Python Interpreter 10 ST5 Escape Sequences 52
1.5 Analyzing Your First Program   11 CS1 International Alphabets and Unicode 52
1.6 Errors  13 2.5 Input and Output   53
CE1 Misspelling Words 15 User Input 53
1.7 PROBLEM SOLVING: Algorithm Design   15 Numerical Input 54
HT1 Describing an Algorithm with Formatted Output 54
Pseudocode 19 PT4 Don’t Wait to Convert 58
WE1 Writing an Algorithm for Tiling a Floor 20 HT1 Writing Simple Programs 58
WE2 Computing the Cost of Stamps 61
CS2 The Pentium Floating-Point Bug 63
2 PROGRAMMING WITH
NUMBERS AND STRINGS 27 2.6 GRAPHICS: Simple Drawings   63
Creating a Window 64
2.1 Variables  28 Lines and Polygons 66
Defining Variables 28 Filled Shapes and Color 67
Number Types 30 Ovals, Circles, and Text 69
Variable Names 31 HT2 GRAPHICS: Drawing Graphical Shapes 70
Constants 32 TOOLBOX1 Symbolic Processing with SymPy 73
Comments 33
CE1 Using Undefined Variables 34
PT1 Choose Descriptive Variable Names 34
3 DECISIONS 91
PT2 Do Not Use Magic Numbers 35
3.1 The if Statement   92
2.2 Arithmetic  35 CE1 Tabs 96
Basic Arithmetic Operations 35 PT1 Avoid Duplication in Branches 96
Powers 36 ST1 Conditional Expressions 97
Floor Division and Remainder 37
3.2 Relational Operators   97
Calling Functions 38
CE2 Exact Comparison of Floating-Point
Mathematical Functions 39
Numbers 101
CE2 Roundoff Errors 41
ST2 Lexicographic Ordering of Strings 101
HT1 Implementing an if Statement 102 Maximum and Minimum 184
WE1 Extracting the Middle 104 Comparing Adjacent Values 185
3.3 Nested Branches   106 4.6 The for Loop   187
PT2 Hand-Tracing 108 PT1 Count Iterations 191
CS1 Denver’s Luggage Handling System 109 HT1 Writing a Loop 192

3.4 Multiple Alternatives   110 4.7 Nested Loops   194


TOOLBOX1 Sending E-mail 113 ST3 Special Form of the print Function 198
WE1 Average Exam Grades 198
3.5 PROBLEM SOLVING: Flowcharts   115
WE2 A Grade Distribution Histogram 200
3.6 PROBLEM SOLVING: Test Cases   119
PT3 Make a Schedule and Make Time for 4.8 Processing Strings   202
Unexpected Problems 120 Counting Matches 202
Finding All Matches 203
3.7 Boolean Variables and Operators   121
Finding the First or Last Match 203
CE3 Confusing and and or Conditions 124
Validating a String 204
PT4 Readability 124
Building a New String 204
ST3 Chaining Relational Operators 125
4.9 APPLICATION: Random Numbers and
ST4 Short-Circuit Evaluation of Boolean
Operators 125 Simulations  206
ST5 De Morgan’s Law 126 Generating Random Numbers 207
Simulating Die Tosses 207
3.8 Analyzing Strings   126
The Monte Carlo Method 208
3.9 APPLICATION: Input Validation   130 WE3 GRAPHICS: Bull’s Eye 210
ST6 Terminating a Program 133
4.10 GRAPHICS: Digital Image Processing   212
ST7 Interactive Graphical Programs 133
Filtering Images 212
CS2 Artificial Intelligence 134
Reconfiguring Images 215
WE2 GRAPHICS: Intersecting Circles 134
TOOLBOX2 Plotting Simple Graphs 138 4.11 PROBLEM SOLVING: Solve a Simpler
Problem First   217
CS2 Digital Piracy 223
4 LOOPS 165
4.1 The while Loop   166 5 FUNCTIONS 245
CE1 Don’t Think “Are We There Yet?” 170
CE2 Infinite Loops 171 5.1 Functions as Black Boxes   246
CE3 Off-by-One Errors 171 5.2 Implementing and Testing Functions   248
CS1 The First Bug 172 Implementing a Function 248
4.2 PROBLEM SOLVING: Hand-Tracing   173 Testing a Function 249
Programs that Contain Functions 250
4.3 APPLICATION: Processing Sentinel
PT1 Function Comments 252
Values  176
5.3 Parameter Passing   252
ST1 Processing Sentinel Values with a
Boolean Variable 179 PT2 Do Not Modify Parameter Variables 254

ST2 Redirection of Input and Output 179 CE1 Trying to Modify Arguments 254

4.4 PROBLEM SOLVING: Storyboards   180 5.4 Return Values   255


ST1 Using Single-Line Compound
4.5 Common Loop Algorithms   183
Statements 256
Sum and Average Value 183 HT1 Implementing a Function 257
Counting Matches 184
WE1 Generating Random Passwords 259
Prompting Until a Match is Found 184
5.5 Functions Without Return Values   263 Copying Lists 326
5.6 PROBLEM SOLVING: Reusable ST2 Slices 328

Functions  265 6.3 Common List Algorithms   328


CS1 Personal Computing 268 Filling 329
5.7 PROBLEM SOLVING: Stepwise Combining List Elements 329
Element Separators 329
Refinement  269
Maximum and Minimum 330
PT3 Keep Functions Short 273
Linear Search 330
PT4 Tracing Functions 274
Collecting and Counting Matches 331
PT5 Stubs 275
Removing Matches 331
WE2 Calculating a Course Grade 275 Swapping Elements 332
WE3 Using a Debugger 278 Reading Input 333
5.8 Variable Scope   282 WE1 Plotting Trigonometric Functions 335
PT6 Avoid Global Variables 285 6.4 Using Lists with Functions   338
WE4 GRAPHICS: Rolling Dice 285 ST3 Call by Value and Call by Reference 341
5.9 GRAPHICS: Building an Image Processing ST4 Tuples 342
Toolkit  288 ST5 Functions with a Variable Number of
Getting Started 288 Arguments 342
Comparing Images 289 ST6 Tuple Assignment 343
Adjusting Image Brightness 290 ST7 Returning Multiple Values with Tuples 343
Rotating an Image 291 TOOLBOX1 Editing Sound Files 344
Using the Toolkit 292 6.5 PROBLEM SOLVING: Adapting
WE5 Plotting Growth or Decay 294 Algorithms  345
5.10 Recursive Functions (Optional)   296 HT1 Working with Lists 347
HT2 Thinking Recursively 299 WE2 Rolling the Dice 349

6.6 PROBLEM SOLVING: Discovering Algorithms by


6 LISTS 315 Manipulating Physical Objects   352
6.7 Tables  356
6.1 Basic Properties of Lists   316
Creating Tables 357
Creating Lists 316
Accessing Elements 358
Accessing List Elements 317
Locating Neighboring Elements 358
Traversing Lists 318
Computing Row and Column Totals 359
List References 319
Using Tables with Functions 360
CE1 Out-of-Range Errors 320
WE3 A World Population Table 362
ST1 Reverse Subscripts 320
ST8 Tables with Variable Row Lengths 364
PT1 Use Lists for Sequences of Related
WE4 GRAPHICS: Drawing Regular Polygons 365
Items 321
CS1 Computer Viruses 321

6.2 List Operations   322 7 FILES AND EXCEPTIONS 383


Appending Elements 322 7.1 Reading and Writing Text Files   384
Inserting an Element 322
Opening a File 384
Finding an Element 323
Reading from a File 385
Removing an Element 324
Writing from a File 386
Concatenation and Replication 325
A File Processing Example 386
Equality Testing 325
CE1 Backslashes in File Names 388
Sum, Maximum, Minimum, and Sorting 325
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
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

10.5 Polymorphism  580 12.6 Searching  671


ST2 Subclasses and Instances 584 Linear Search 671
Binary Search 672
ST3 Dynamic Method Lookup 584
ST4 Abstract Classes 585 12.7 PROBLEM SOLVING: Estimating the Running
CE3 Don’t Use Type Tests 586 Time of an Algorithm   674
HT1 Developing an Inheritance Hierarchy 586 Linear Time 674
WE1 Implementing an Employee Hierarchy for Quadratic Time 675
Payroll Processing 591 The Triangle Pattern 676
Logarithmic Time 677
10.6 APPLICATION: A Geometric Shape Class
PT1 Searching and Sorting 679
Hierarchy  594
ST4 Comparing Objects 679
The Base Class 595
WE1 Enhancing the Insertion Sort Algorithm 680
Basic Shapes 597
Groups of Shapes 600 CS1 The First Programmer 683
Appendix A PYTHON OPERATOR SUMMARY   A-1 GLOSSARY  A-20
Appendix B PYTHON RESERVED WORD INDEX  A-25
SUMMARY  A-3 CREDITS  A-40
Appendix C THE PYTHON STANDARD
LIBRARY  A-5
Appendix D THE BASIC LATIN AND LATIN-1 SUBSETS
OF UNICODE*
Appendix E BINARY NUMBERS AND BIT OPERATIONS*
Appendix F HTML SUMMARY*

*On the companion site at www.wiley.com/college/horstmann.

ALPHABETICAL LIST OF SYNTAX BOXES


Assignment  29
Calling Functions  38
Constructor  511
for Statement  188
for Statement with range Function  189
Function Definition  249
Handling Exceptions  425
if Statement  94
Lists  317
Method Definition  514
Opening and Closing FIles   385
print Statement  12
Program with Functions   250
Raising an Exception   424
Set and Dictionary Literals   469
String Format Operator   55
Subclass Constructor  573
Subclass Definition  570
The finally Clause  426
while Statement  167
xviii Special Features

Toolboxes How Tos


CHAPTE R Common and and
Errors © Steve Simzer/iStockphoto.

Worked Examples Worked Examples


chalice: Paul Fleet/Getty Images, Inc.; © Tom Horyn/iStockphoto.

.otohpkcotSi/eélessI cirE © tools: mattjeacock/Getty Images, Inc.

1 Misspelling Words 15 Describing an Algorithm


with Pseudocode 19
Writing an Algorithm for
Tiling a Floor 20

2 Using Undefined Variables 34 Symbolic Processing Computing Travel Time  45


Roundoff Errors 41 with SymPy 73 Writing Simple Programs 58
Unbalanced Parentheses 41 Computing the Cost
of Stamps  61
Graphics: Drawing
Graphical Shapes  70

3 Tabs 96 Sending E-mail 113 Implementing an


Exact Comparison of Plotting Simple Graphs 138 if Statement 102
Floating-Point Numbers 101 Extracting the Middle 104
Confusing and and Graphics: Intersecting
or Conditions 124 Circles 134

4 Don’t Think “Are We A Grade Distribution Writing a Loop 192


There Yet?” 170 Histogram 200 Average Exam Grades 198
Infinite Loops 171 Graphics: Bull’s Eye 210
Off-by-One Errors 171

5 Trying to Modify Plotting Growth or Decay 294 Implementing a Function 257


Arguments 254 Generating Random
Passwords 259
Calculating a Course Grade 275
Using a Debugger 278
Graphics: Rolling Dice 285
Thinking Recursively 299
Special Features xix

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

Choose Descriptive Other Ways to Import Modules 42 International Alphabets and


Variable Names  34 Combining Assignment and Unicode  52
Do Not Use Magic Numbers  35 Arithmetic  42 The Pentium Floating-
Use Spaces in Expressions  42 Line Joining  43 Point Bug 63
Don’t Wait to Convert  58 Character Values  51
Escape Sequences  52

Avoid Duplication in Branches  96 Conditional Expressions   97 Denver’s Luggage


Hand-Tracing 108 Lexicographic Ordering Handling System  109
Make a Schedule and Make Time of Strings  101 Artificial Intelligence  134
for Unexpected Problems  120 Chaining Relational
Readability 124 Operators  125
Short-Circuit Evaluation of
Boolean Operators  125
De Morgan’s Law 126
Terminating a Program  133
Interactive Graphical Programs 133

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

Function Comments 252 Using Single-Line Compound Personal Computing  257


Do Not Modify Parameter Statements  256
Variables 254
Keep Functions Short 273
Tracing Functions  274
Stubs 275
Avoid Global Variables  285
xx Special Features

Toolboxes How Tos


CHAPTE R Common and and
Errors © Steve Simzer/iStockphoto.

Worked Examples Worked Examples


chalice: Paul Fleet/Getty Images, Inc.; © Tom Horyn/iStockphoto.

.otohpkcotSi/eélessI cirE © tools: mattjeacock/Getty Images, Inc.

6 Out-of-Range Errors  320 Plotting Trigonometric Working with Lists  347


Functions 335 Rolling the Dice  349
Editing Sound Files 344 A World Population
Table 362
Graphics: Drawing Regular
Polygons 365

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

8 Harvesting JSON Data Counting Unique Words  465


from the Web 489 Translating Text
Messages  476
Graphics: Pie Charts  484

9 Trying to Call a Constructor  512 Implementing a Class  519


Implementing a Bank
Account Class  522
Graphics: A Die Class  547

10 Confusing Super- and Developing an


Subclasses 572 Inheritance Hierarchy 586
Forgetting to Use the super Implementing an
Function When Invoking Employee Hierarchy for
a Superclass Method 580 Payroll Processing 591
Don’t Use Type Tests 586

11 Infinite Recursion  615 Analyzing Web Pages with Finding Files 620
Beautiful Soup 643 Towers of Hanoi 636

12 Enhancing the Insertion


Sort Algorithm 680
Special Features xxi

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

Use a Single Class for Variation The Cosmic Superclass:


in Values, Inheritance for object 568
Variation in Behavior 567 Subclasses and Instances 584
Dynamic Method Lookup 584
Abstract Classes 585

Recursion with Objects 616 The Limits of


Computation 630

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

To learn about computers


and programming
To write and run your first Python program
To recognize compile-time and run-time errors
© JanPietruszka/iStockphoto.

To describe an algorithm with pseudocode

CHAPTER CONTENTS

1.1 COMPUTER PROGRAMS 2 1.5 ANALYZING YOUR FIRST


PROGRAM 11
1.2 THE ANATOMY OF A
Syntax 1.1: print Statement 12
COMPUTER 3
Computing & Society 1.1: Computers Are 1.6 ERRORS 13
Everywhere 5 Common Error 1.1: Misspelling Words 15

1.3 THE PYTHON PROGRAMMING 1.7 PROBLEM SOLVING:


LANGUAGE 5 ALGORITHM DESIGN 15
How To 1.1: Describing an Algorithm with
1.4 BECOMING FAMILIAR WITH YOUR
Pseudocode 19
PROGRAMMING ENVIRONMENT 6
Worked Example 1.1: Writing an Algorithm for
Programming Tip 1.1: Interactive Mode 9
Tiling a Floor 20
Programming Tip 1.2: Backup Copies 9
Special Topic 1.1: The Python Interpreter 10
Just as you gather tools, study a project, and make a plan for
tackling it, in this chapter you will gather up the basics you
need to start learning to program. After a brief introduction
to computer hardware, software, and programming in
general, you will learn how to write and run your first
Python program. You will also learn how to diagnose and
fix programming errors, and how to use pseudocode to
describe an algorithm—a step-by-step description of how
to solve a problem—as you plan your computer programs.

© JanPietruszka/iStockphoto.

JanPietruszka/iStockphoto.

1.1 Computer Programs


Computers
You have probably used a computer for work or fun. Many people use computers
execute very basic for everyday tasks such as electronic banking or writing a term paper. Computers are
instructions in rapid good for such tasks. They can handle repetitive chores, such as totaling up numbers
succession.
or placing words on a page, without getting bored or exhausted.
The flexibility of a computer is quite an amazing phenomenon. The same machine
can balance your checkbook, lay out your term paper, and play a game. In contrast,
other machines carry out a much nar­rower range of tasks; a car drives and a toaster
toasts. Computers can carry out a wide range of tasks because they execute different
programs, each of which directs the computer to work on a specific task.
A computer program
The computer itself is a machine that stores data (numbers, words, pictures), inter-
is a sequence of acts with devices (the monitor, the sound system, the printer), and executes programs.
instructions and A computer program tells a computer, in minute detail, the sequence of steps that are
decisions.
needed to fulfill a task. The physical computer and periph­eral devices are collectively
called the hardware. The programs the computer executes are called the soft­ware.
Today’s computer programs are so sophisticated that it is hard to believe that they
are composed of extremely primitive instructions. A typical instruction may be one
of the following:
• Put a red dot at a given screen position.
• Add up two numbers.
• If this value is negative, continue the program at a certain instruction.
The computer user has the illusion of smooth interaction because a program contains
a huge number of such instructions, and because the computer can execute them at
great speed.
Programming is the
The act of designing and implementing computer programs is called program-
act of designing ming. In this book, you will learn how to program a computer—that is, how to direct
and implementing the computer to execute tasks.
computer programs.
To write a computer game with motion and sound effects or a word processor
that supports fancy fonts and pictures is a complex task that requires a team of many
highly-skilled programmers. Your first programming efforts will be more mundane.
The concepts and skills you learn in this book form an important foundation, and
you should not be disappointed if your first programs do not rival the sophis­ticated
software that is familiar to you. Actually, you will find that there is an immense thrill
even in sim­ple programming tasks. It is an amazing experience to see the computer
precisely and quickly carry out a task that would take you hours of drudgery, to

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.

SELF CHECK 1. What is required to play music on a computer?


2. Why is a CD player less flexible than a computer?
3. What does a computer user need to know about programming in order to play a
video game?
© Nicholas Homrich/iStockphoto.

1.2 The Anatomy of a Computer


To understand the programming process, you need to have a rudimentary under-
standing of the building blocks that make up a computer. We will look at a personal
computer. Larger computers have faster, larger, or more powerful components, but
they have fundamentally the same design.
At the heart of the computer lies the central processing unit (CPU) (see Figure 1).
The inside wiring of the CPU is enormously complicated. The CPUs used for per­
sonal computers at the time of this writing are composed of several hundred million
The central structural elements, called transistors.
processing unit (CPU) The CPU performs program control and data processing. That is, the CPU locates
performs program and executes the program instructions; it carries out arithmetic operations such as
control and data
processing. addition, subtraction, multiplication, and division; it fetches data from external mem-
ory or devices and places processed data into storage.
Storage devices
There are two kinds of storage. Primary storage is made from memory chips:
include memory and electronic circuits that can store data, provided they are supplied with electric power.
secondary storage. Secondary storage, usually a hard disk (see Figure 2), provides slower and less
expensive storage that persists without electricity. A hard disk consists of rotating
platters, which are coated with a mag­netic material, and read/write heads, which can
detect and change the magnetic flux on the platters.
The computer stores both data and programs. They are located in secondary stor-
age and loaded into memory when the program starts. The program then updates the
data in memory and writes the modified data back to secondary storage.

PhotoDisc, Inc./Getty Images, Inc.


© Amorphis/iStockphoto.

Figure 1 Central
© Amorphis/iStockphoto. Processing Unit Figure 2 A Hard Disk
PhotoDisc, Inc./Getty Images, Inc.
4 Chapter 1 Introduction

Printer

Mouse/Trackpad Ports Disk


controller

Keyboard Secondary storage

CPU
Monitor
Microphone
Memory

Speakers

Network
controller Internet

Figure 3 Schematic Design of a Personal Computer

To interact with a human user, a computer requires peripheral devices. The com-
puter transmits infor­mation (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 instruc­tions 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.

SELF CHECK 4. Where is a program stored when it is not currently running?


5. Which part of the computer carries out arithmetic operations, such as addition
and multiplication?
© Nicholas Homrich/iStockphoto.
Practice It Now you can try these exercises at the end of the chapter: R1.2, R1.3.
1.3 The Python Programming Language 5

Computing & Society 1.1 Computers Are Everywhere


When computers were first The advent of ubiqui­
invented in the 1940s, a tous computing changed
computer filled an entire many aspects of our
© Stephen
room.Coburn/123RF.com.
The photo below shows the lives. Factories used

© Maurice Savage/Alamy Limited.


ENIAC (electronic numerical integrator to employ people to
and computer), completed in 1946 at do repetitive assembly
the University of Pennsylvania. The tasks that are today car-
ENIAC was used by the military to com- ried out by computer-
pute the trajectories of projectiles. controlled robots, oper-
Nowadays, computing facilities of ated by a few people
search engines, Internet shops, and who know how to work
social networks fill huge buildings with those computers.
called data centers. At the other end of Books, music, and mov-
the spectrum, computers are all around ies nowadays are often
us. Your cell phone has a computer consumed on comput-
This transit card contains a computer.
inside, as do many credit cards and fare ers, and computers ©areMaurice Savage/Alamy Limited.
cards for public transit. A modern car almost always involved
has several computers––to control the in their production. The book that you been written without computers.
engine, brakes, lights, and the radio. are reading right now could not have Knowing about computers and
how to program them has become
an essential skill in many careers.
Engineers design computer-controlled
cars and medical equipment that
preserve lives. Computer scientists
develop programs that help people
come together to support social
causes. For example, activists used
social networks to share videos
showing abuse by repressive regimes,
and this information was instrumental
in changing public opinion.
As computers, large and small,
become ever more embedded in our
everyday lives, it is increasingly impor-
tant for everyone to understand how
they work, and how to work with them.
© UPPA/Photoshot.

As you use this book to learn how to


program a computer, you will develop
a good understanding of computing
fundamentals that will make you a
more informed citizen and, perhaps,
a computing professional.
The ENIAC

© UPPA/Photoshot.

1.3 The Python Programming Language


In order to write a computer program, you need to provide a sequence of instruc-
tions that the CPU can execute. A computer program consists of a large number of
simple CPU instructions, and it is tedious and error-prone to specify them one by
one. For that reason, high-level programming languages have been created. These
languages allow a programmer to specify the desired program actions at a high level.
The high-level instructions are then automatically translated into the more detailed
instructions required by the CPU.
6 Chapter 1 Introduction

In this book, we will use a high-level programming


language called Python, which was developed in the

Sauria Associates, LLC/FlickrVision/Getty Images, Inc.


early 1990s by Guido van Rossum. Van Rossum
needed to carry out repetitive tasks for administering
computer systems. He was dissatisfied with other
available languages that were optimized for writing
large and fast programs. He needed to write smaller
programs that didn’t have to run at optimum speed. It
was important to him that he could author the pro-
grams quickly and update them quickly as his needs
changed. Therefore, he designed a language that made
it very easy to work with complex data. Python has
evolved considerably since its beginnings. In this
book, we use version 3 of the Python language. Van
Rossum is still the principal author of the language,
but the effort now includes many volunteers.
Python is portable
Python has become popular for business, scientific, and academic applications and
and easy to learn is very suitable for the beginning programmer. There are many reasons for the suc-
and use. cess of Python. Python has a much simpler and cleaner syntax than other popular
languages such as Java, C, and C++, which makes it easier to learn. Moreover, you
© Sauria Associates, LLC/FlickrVision/Getty Images, Inc.
can try out short Python programs in an interactive environment, which encourages
experimentation and rapid turnaround. Python is also very portable between com-
puter systems. The same Python program will run, without change, on Windows,
UNIX, Linux, and Macintosh.

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.

1.4 Becoming Familiar with Your Programming


Environment
Set aside some
Many students find that the tools they need as programmers are very different from
time to become the software with which they are familiar. You should spend some time making your-
familiar with the self familiar with your programming environment. Because computer systems vary
programming
environment that
widely, this book can only give an outline of the steps you need to follow. It is a good
you will use for your idea to participate in a hands-on lab, or to ask a knowledgeable friend to give you
class work. a tour.
Step 1 Install the Python development environment.
Your instructor may have given you installation instructions for the environment
that is used in your course. If not, follow the installation instructions that we provide
at http://horstmann.com/python4everyone/install.html.
1.4 Becoming Familiar with Your Programming Environment 7

Step 2 Start the Python development environment.


Computer systems differ greatly in this regard. On many computers there is an inte-
grated development environment in which you can write and test your programs.
On other computers you first launch a text editor, a program that functions like a
A text editor is a
word processor, in which you can enter your Python instructions; you then open a
program for entering terminal window and type commands to execute your program. Follow the instruc-
and modifying text, tions from your instructor or those at http://horstmann.com/python4everyone/install.html.
such as a Python
program. Step 3 Write a simple program.
The traditional choice for the very first program in a new programming language is
a program that dis­plays a simple greeting: “Hello, World!”. Let us follow that tradi-
tion. Here is the “Hello, World!” pro­gram in Python:
# My first Python program.
print("Hello, World!")
We will examine this program in the next section.
No matter which programming environment you use, you begin your activity by
typing the program instructions into an editor window.
Create a new file and call it hello.py, using the steps that are appropriate for your
environ­ment. (If your environment requires that you supply a project name in addi-
tion to the file name, use the name hello for the project.) Enter the program instruc-
tions exactly as they are given above. Alternatively, locate the electronic copy in this
book’s companion code and paste it into your editor.
Python is case
As you write this program, pay careful attention to the various symbols, and keep
sensitive. You must in mind that Python is case sensitive. You must enter upper- and lowercase letters
be careful about exactly as they appear in the program listing. You cannot type Print or PRINT. If you
distinguishing
between upper- and
are not careful, you will run into problems—see Common Error 1.1 on page 15.
lowercase letters.
Step 4 Run the program.
The process for running a program depends greatly on your programming environ-
ment. You may have to click a button or enter some commands. When you run the
test program, the message
Hello, World!

will appear somewhere on the screen (see Figures 4 and 5).


The Python
A Python program is executed using the Python interpreter. The interpreter
interpreter reads reads your program and executes all of its steps. (Special Topic 1.1 on page 10
Python programs explains in more detail what the Python interpreter does.) In some programming
and executes
the program
environments, the Python interpreter is automatically launched when you click on a
instructions. “Run” button or select the “Run” option from a menu. In other environments, you
have to launch the interpreter explicitly.

Figure 4 Running the hello.py Program in a Terminal Window


8 Chapter 1 Introduction

Figure 5
Running the
hello.py Program
in an Integrated
Development
Environment

Step 5 Organize your work.


As a programmer, you write programs, try them out, and improve them. If you want
to keep your programs, or turn them in for grading, you store them in files. A Python
program can be stored in a file with any name, provided it ends with .py. For example,
we can store our first program in a file named hello.py or welcome.py.
Files are stored in folders or directories. A folder can contain files as well as other
folders, which themselves can contain more files and folders (see Figure 6). This hier-
archy can be quite large, and you need not be concerned with all of its branches.
However, you should create folders for organizing your
work. It is a good idea to make a separate folder for your pro-
gramming class. Inside that folder, make a separate folder for
each program.
Some programming environments place your programs
into a default location if you don’t specify a folder. In that
case, you need to find out where those files are located.
Be sure that you understand where your files are located in
the folder hierarchy. This information is essential when you
submit files for grading, and for making backup copies (see Figure 6
Programming Tip 1.2 on page 9). A Folder Hierarchy

SELF CHECK 8. Where is the hello.py file stored on your computer?


9. What do you do to protect yourself from data loss when you work on program-
ming projects?
© Nicholas Homrich/iStockphoto.
Practice It Now you can try this exercise at the end of the chapter: R1.6.
1.4 Becoming Familiar with Your Programming Environment 9

Programming Tip 1.1 Interactive Mode


When you write a complete program, you place the program instructions in a file and let the
Python interpreter execute your program file. The interpreter, however, also provides an
interactive mode in which Python instructions can be entered one at a time. To launch the
Python interactive mode from a terminal window, enter the command
python
(On systems where multiple versions of Python are installed, use the command python3 to run
version 3 of Python.) Interactive mode can also be started from within most Python integrated
© Mikhail Mishchenko/123RF Limited.
development environments.
The interface for working in interactive mode is known as the Python shell. First, you will
see an informational message similar to the following:
Python 3.1.4 (default, Nov 3 2014, 14:38:10)
[GCC 4.9.1 20140930 (Red Hat 4.9.1-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
The >>> at the bottom of the output is the prompt. It indicates that you can enter Python
instructions. (Your prompt may look different, such as In [1]:.) After you type an instruc-
tion and press the Enter key, the code is immediately executed by the Python interpreter. For
example, if you enter
print("Hello, World!")
the interpreter will respond by executing the print function and displaying the output, fol-
lowed by another prompt:
>>> print("Hello, World!")
Hello World
>>>
Interactive mode is very useful when you are first learning to program. It allows you to experi-
ment and test individual Python instructions to see what happens. You can also use interactive
mode as a simple calculator. Just enter mathematical expressions using Python syntax:
>>> 7035 * 0.15
1055.25
>>>
Make it a habit to use interactive mode as you experiment with new language constructs.

Programming Tip 1.2 Backup Copies

© 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 impor­tant 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 rec­ommend 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.

Special Topic 1.1 The Python Interpreter


When you use the Python interpreter to execute a program, you can imagine it reading your
program and executing it, one step at a time. However, that is not actually what is happening.
Because one typically runs a program many times, the Python interpreter employs a divi-
sion of labor. The time-consuming task of reading a program and comprehending its instruc-
tions is carried out once, by a component called a compiler. The compiler reads the file con-
taining your source code (that is, the Python instructions that you wrote), and translates the
instructions into byte code. Byte codes are very simple instructions understood by the virtual
© modella/123RF.com. machine, a separate program that is similar to the CPU of a computer. After the compiler has
translated your program into virtual machine instructions, they are executed by the virtual
machine, as often as you like.
Your source code doesn’t contain all the information that the virtual machine needs. For
example, it does not contain the implementation of the print function. The virtual machine
locates functions such as print in library modules. Generally, you need not be concerned
with library modules. However, when you want to do specialized tasks, such as graphics
programming, you may need to install the required libraries. The details depend on your
Python environment.
You may find files containing virtual machine instructions in your file system. These files
have the extension .pyc and are produced by the compiler. You don’t have to pay much atten-
tion to these files, but don’t turn them in for grading. They are only useful for the Python
virtual machine, not a human grader.

Python Interpreter

Byte Virtual
Compiler
code Machine

Editor
Running
Source File Program

Library
modules

Figure 7 From Source Code to Running Program


1.5 Analyzing Your First Program 11

1.5 Analyzing Your First Program


In this section, we will analyze the first Python program in detail. Here again is the
code:

ch01/sec04/hello.py
© Amanda Rohde/iStockphoto.

1 # My first Python program.


2 print("Hello, World!")

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 1.1 print Statement

Syntax print()
print(value1, value2, ..., valuen)

All arguments are optional. If no arguments


are given, a blank line is printed.

print("The answer is", 6 + 7, "!")

The values to be printed,


one after the other,
separated by a blank space.

For example,
print("Hello")
print("World!")

prints two lines of text:


Hello
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!")

prints three lines of text including a blank line:


Hello

World
Statements in a Python program must begin in the same column. For example, the
following program
print("Hello")
print("World!")

is not valid because the indenting is inconsistent.


A sample program that demonstrates the use of the print function is below.
ch01/sec05/printtest.py
1 ##
2 # Sample program that demonstrates the print function.
3 #
4
5 # Prints 7.
6 print(3 + 4)
7
8 # Prints “Hello World!” in two lines.
9 print("Hello")
10 print("World!")
11
1.6 Errors 13

12 # Prints multiple values with a single print function call.


13 print("My favorite numbers are", 3 + 4, "and", 3 + 10)
14
15 # Prints three lines of text with a blank line.
16 print("Goodbye")
17 print()
18 print("Hope to see you again")

Program Run
7
Hello
World!
My favorite numbers are 7 and 13
Goodbye

Hope to see you again

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!)

(Note the missing quotation marks at the end of the


greeting.) When you attempt to run the program,
the interpreter will stop and display the following
message
File "hello.py", line 2
print("Hello, World)
^ © Martin Carlsson/iStockphoto.
A compile-time Programmers spend a fair amount
error is a violation SyntaxError: EOL while scanning string literal
of time fixing compile-time and
of the programming
language rules that
This is a compile-time error. (The process of trans- run-time errors.
is detected when the forming Python instructions into an executable
code is translated form is called compilation—see Special Topic 1.1). Something is wrong according to
into executable form.
the rules of the language, and the error is detected before your program is actually
14 Chapter 1 Introduction

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!)

The error report looks like this:


File "hello.py", line 2
print(Hello, World!)
^
SyntaxError: invalid syntax

It is up to you to realize that you need to enclose strings in quotation marks.


Some errors can only be found when the program executes. For example, suppose
your program includes the statement
print(1 / 0)

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 spontane­ously) 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.

Common Error 1.1 Misspelling Words


If you accidentally misspell a word, then strange things may happen, and it may not always be
completely obvious from the error message what went wrong. Here is a good example of how
simple spelling errors can cause trouble:
.otohpkcotSi/eélessI cirE © Print("Hello, World!")
print("How are you?")
The first statement calls the Print function. This is not the same as the print function because
Print starts with an uppercase letter and the Python language is case sensitive. Upper- and
lowercase letters are considered to be completely different from each other; to the interpreter
Print is no better match for print than pint. Of course, the message Name 'Print' is not defined
should give you a clue where to look for the error.
If you get an error message that seems to indicate that the Python interpreter is on the
wrong track, it is a good idea to check for spelling and capitalization.

1.7 Problem Solving: Algorithm Design


You will soon learn how to program calculations and decision making in Python. But
before we look at the mechanics of implementing computations in the next chapter,
let’s consider how you can describe the steps that are necessary for finding a solution
to a problem.
You may have run across advertisements that
encourage you to pay for a computerized service
that matches you up with a romantic partner. Think © mammamaart/iStockphoto.
how this might work. You fill out a form and send
it in. Others do the same. The data are processed
by a computer program. Is it reasonable to assume
that the computer can perform the task of finding
the best match for you?
Suppose your younger brother, not the
computer, had all the forms on his desk. What
instructions could you give him? You can’t say, © mammamaart/iStockphoto.
“Find the best-looking person who likes inline Finding the perfect partner is not a
skating and browsing the Internet”. There is no problem that a computer can solve.
16 Chapter 1 Introduction

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
com­puter 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:

year interest balance


0 10000
1 10000.00 x 0.05 = 500.00 10000.00 + 500.00 = 10500.00
2 10500.00 x 0.05 = 525.00 10500.00 + 525.00 = 11025.00
3 11025.00 x 0.05 = 551.25 11025.00 + 551.25 = 11576.25
4 11576.25 x 0.05 = 578.81 11576.25 + 578.81 = 12155.06

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 unam­biguous, 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.

year interest balance


0 10000

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.

year interest balance


0 10000
1 500.00 10500.00

14 942.82 19799.32
15 989.96 20789.28

Report the final year value as the answer.


1.7 Problem Solving: Algorithm Design 17

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.

there is no way for anyone to know what that


interest rate will be. A sequence of steps is termi-
nating if it will eventually come to an end. In our
example, it requires a bit of thought to see that the
sequence will not go on forever: With every step,
the balance goes up by at least $500, so eventually An algorithm is a recipe for
it must reach $20,000. finding a solution.

© Claudiad/iStockphoto.
18 Chapter 1 Introduction

Figure 8 The Software Development Process


Understand
the problem

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 expen­sive 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

How To 1.1 Describing an Algorithm with Pseudocode


This is the first of many “How To” sections in this book that give you step-by-step proce-
dures for carrying out important tasks in developing computer programs.
Before you are ready to write a program in Python, you need to develop an algorithm—a
method for arriving at a solution for a particular problem. Describe the algorithm in pseudo-
code: a sequence of precise steps formulated in English.
Problem Statement You have the choice of buying two cars.

© 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?

Step 1 Determine the inputs and outputs.


© dlewis33/iStockphoto.
In our sample problem, we have these inputs:
• purchase price1 and fuel efficiency1, the price and fuel efficiency (in mpg) of the first car
• purchase price2 and fuel efficiency2, the price and fuel efficiency of the second car
We simply want to know which car is the better buy. That is the desired output.
Step 2 Break down the problem into smaller tasks.

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

Step 4 Test your pseudocode by working a problem.


We will use these sample values:
Car 1: $25,000, 50 miles/gallon
Car 2: $20,000, 30 miles/gallon
Here is the calculation for the cost of the first car:
annual fuel consumed = annual miles driven / fuel efficiency = 15000 / 50 = 300
annual fuel cost = price per gallon x annual fuel consumed = 4 x 300 = 1200
operating cost = 10 x annual fuel cost = 10 x 1200 = 12000
total cost = purchase price + operating cost = 25000 + 12000 = 37000
Similarly, the total cost for the second car is $40,000. Therefore, the output of the algorithm is
to choose car 1.

Worked Example 1.1 Writing an Algorithm for Tiling a Floor

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 lay­ing 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

Complete the row.


1 2 3 4 5
6 7 8 9 10

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

Now the entire floor is filled, and you are done.

CHAPTER SUMMARY

Define “computer program” and programming.

• Computers execute very basic instructions in rapid succession.


• A computer program is a sequence of instructions and decisions.
• Programming is the act of designing and implementing computer programs.
Describe the components of a computer.

• The central processing unit (CPU) performs program control and data
processing.
• Storage devices include memory and secondary storage.
© Amorphis/iStockphoto.
22 Chapter 1 Introduction

Describe the benefits of the Python language.

• Python is portable and easy to learn and use.


Become familiar with your Python programming environment.

• 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.

• A comment provides information to the programmer.


• A function is a collection of instructions that perform a particular task.
• A function is called by specifying the function name and its arguments.
• A string is a sequence of characters enclosed in a pair of single or double
quotation marks.
© Amanda Rohde/iStockphoto.
Classify program errors as compile-time and run-time errors.

• A compile-time error is a violation of the programming language rules that is


detected when the code is translated into executable form.
• An exception occurs when an instruction is syntactically correct, but impossible
to perform.
• A run-time error is any error that occurs when the program compiles and runs,
© Martin Carlsson/iStockphoto. but produces unexpected results.
Write pseudocode for simple algorithms.

• Pseudocode is an informal description of a sequence of steps


for solving a problem.
• An algorithm for solving a problem is a sequence of steps that
is unambiguous, executable, and terminating.

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 programma­ble
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.7 What does this program print?


print("39 + 3")
print(39 + 3)

•• R1.8 What does this program print? Pay close attention to spaces.
print("Hello", "World", "!")

•• R1.9 What is the compile-time error in this program?


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 dig­its.
•• 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

Do your best to approximate lines with characters such as | - +.

••• 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. . . .

• Business P1.16 The ability to speak more than one language is


List of Phrases to Translate
a valuable skill in today’s labor market. One of
the basic skills is learning to greet people. Write Good morning.
a program that prints a two-column list with the
greeting phrases shown in the following table; in It is a pleasure to meet you.
the first column, print the phrase in English, in Please call me tomorrow.
the second column, print the phrase in a language
of your choice. If you don’t speak any language Have a nice day!
other than English, use an online translator or
ask a friend.

ANSWERS TO SELF-CHECK QUESTIONS

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

To define and use variables and constants


To understand the properties and limitations of integers and floating-point numbers
To appreciate the importance of comments and good code layout
To write arithmetic expressions and assignment statements
To create programs that read and process inputs, and display the results
To learn how to use Python strings
To create simple graphics programs using basic shapes and text

CHAPTER CONTENTS

2.1 VARIABLES 28 2.4 STRINGS 46


Syntax 2.1: Assignment 29 Special Topic 2.4: Character Values 51
© samxmeg/iStockphoto.
Common Error 2.1: Using Undefined Special Topic 2.5: Escape Sequences 52
Variables 34 Computing & Society 2.1: International Alphabets
Programming Tip 2.1: Choose Descriptive and Unicode 52
Variable Names 34
2.5 INPUT AND OUTPUT 53
Programming Tip 2.2: Do Not Use
Magic Numbers 35 Syntax 2.3: String Format Operator 55
Programming Tip 2.4: Don’t Wait to Convert 58
2.2 ARITHMETIC 35 How To 2.1: Writing Simple Programs 58
Syntax 2.2: Calling Functions 38 Worked Example 2.2: Computing the Cost
Common Error 2.2: Roundoff Errors 41 of Stamps 61
Common Error 2.3: Unbalanced Parentheses 41 Computing & Society 2.2: The Pentium Floating-
Programming Tip 2.3: Use Spaces in Point Bug 63
Expressions 42
2.6 GRAPHICS: SIMPLE DRAWINGS 63
Special Topic 2.1: Other Ways to Import
Modules 42 How To 2.2: Graphics: Drawing Graphical
Shapes 70
Special Topic 2.2: Combining Assignment and
Arithmetic 42 Toolbox 2.1: Symbolic Processing with
SymPy 73
Special Topic 2.3: Line Joining 43

2.3 PROBLEM SOLVING: FIRST DO IT


BY HAND 43
Worked Example 2.1: Computing Travel Time 45
Numbers and character strings (such as the ones on this
display board) are important data types in any Python
program. In this chapter, you will learn how to work with
numbers and text, and how to write simple programs that
perform useful tasks with them.

© 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 pro­gram 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?

2.1.1 Defining Variables

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).

Javier Larrea/Age Fotostock.

Like a variable in a computer


program, a parking space has
an identifier and a contents.

28 Javier Larrea/Age Fotostock.


2.1 Variables 29

Syntax 2.1 Assignment

Syntax variableName = value

A variable is defined total = 0 Names of previously


the first time it . defined variables
is assigned a value. .
total = bottles * BOTTLE_VOLUME

.
The expression that replaces the previous value
.
.
total = total + cans * CAN_VOLUME

The same name


can occur on both sides. Names of previously
See Figure 2. defined variables

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

The left-hand side of an assignment statement consists of a variable. The right-hand


side is an expression that has a value. That value is stored in the variable.
The first time a variable is assigned a value, the variable is created and initialized
with that value. After a variable has been defined, it can be used in other statements.
A variable is created
For example,
the first time it is print(cansPerPack)
assigned a value.
will print the value stored in the variable cansPerPack.
Assigning a value
If an existing variable is assigned a new value, that value replaces the previous con-
to an existing tents of the variable. For example,
variable replaces
cansPerPack = 8 3
the previously
stored value. changes the value contained in variable cansPerPack from 6 to 8. Figure 1 illustrates the
two assignment statements used above.
The assignment
The = sign does not mean that the left-hand side is equal to the right-hand side.
operator = does not Instead, the value on the right-hand side is placed into the variable on the left.
denote mathematical Do not confuse this assignment operator with the = used in algebra to denote
equality.
equality. Assignment is an instruction to do something—namely, place a value into a
variable.

1 Because this is the first assignment, 2 The variable is initialized. 3 The second assignment overwrites
the variable is created. the stored value.

cansPerPack = cansPerPack = 6 cansPerPack = 8

Figure 1 Executing Two Assignments


Exploring the Variety of Random
Documents with Different Content
had become already so firmly established in the minds of the
Reformers that it was accepted as a matter of course, which needed
no special confirmation. Although laws were passed prohibiting the
Mass and abolishing the supremacy of the pope, none were thought
necessary to legalize the marriages of the clergy. Even in Knox’s
Confession of Faith, adopted by the parliament on the 17th of July,
there is no direct allusion to the matter. The only passage which can
be construed as having any bearing upon it occurs in Chapter xiv.,
when considering “What works are reputed good before God”—“And
evill works we affirme not onely those that are expressly done
against God’s commandment, but those also that in matters of
religion and worshipping of God have no assurance, but the
invention and opinion of man, which God from the beginning hath
ever rejected, as by the prophet Isaiah and by our Master Christ
Jesus we are taught in these words—In vain do they worship me,
teaching doctrines which are precepts of Men.”1316
Nothing more, in fact, was needed when the triumph of the new
ideas was so complete that Knox could exultingly exclaim, “For what
Adulterer, what Fornicator, what known Masse-monger or pestilent
Papist durst have been seen in publike within any Reformed Town
within this Realme before that the Queen arrived?... For while the
Papists were so confounded that none within the Realme durst avow
the hearing or saying of Masse then the thieves of Tiddisdale durst
avow their stouth or stealing in the presence of any upright
judge.”1317 When persecution thus had changed sides, no minister
could feel that his nuptials required special authorization. How
thoroughly, indeed, they were legitimated is shown by a curious little
incident occurring in 1563. A minister named Baron made complaint
to the General Assembly that his wife, an English woman named
Anne Goodacre, “after great rebellions by her committed,” had left
him and taken refuge in England, whereupon he requested the
Assembly to have her brought back to him. Spotswood, the
Superintendent of Lothian, with Knox and Craig, actually wrote to
Archbishop Parker officially asking him to have the woman sought
for and sent to Scotland; but Parker, considering it to be an
international question and beyond his sphere, prudently referred the
request to Secretary Cecil.1318
It were foreign to our object to enter into the dark details of
Mary’s short and disastrous reign. The intrigues of the camarilla, the
boyish weakness of Darnley, the subtlety of Rizzio, and the coarse
ambition of Huntley and Bothwell, were alike harmless against the
earnest reverence of the people for the new faith; and the expiring
struggles of Catholicism were too feeble to give any practical
importance to the vain attempts at reaction.
XXVIII.
THE COUNCIL OF TRENT.
It has already been observed that the dissolute and unchristian life
of the priesthood was one of the efficient causes which led to the
success of the Reformation. At an early period in the movement, the
Catholic church felt the necessity of purifying itself, if it was to retain
the veneration of the people; and the veneration of the people was
now not merely a source of revenue, but a condition of the very
existence of the stupendous structure reared upon the credulity of
ages. As soon as it became clearly apparent that Lutheranism was
not to be suppressed by the ordinary machinery, and that it was
spreading with a rapidity which portended the worst results, an
effort was made to remove the reproach which incorrigible
immorality had entailed upon the church. Allusion has been made
above to the stringent measures of reform proclaimed by the legate
Campeggi at Ratisbon, in 1524, in which he acknowledged that the
new heresy had no little excuse in the detestable morals and
abandoned lives of the clergy—a truth repeatedly admitted by the
ecclesiastical authorities.1319 His well-meant endeavors had little
result, and we have seen that, some years later, Erasmus still urged
the abolition of the rule of celibacy as the only practicable mode of
removing the scandal.
Not long afterwards the Gallican church made a strenuous effort
of the same nature to check the spread of Lutheranism. In 1521,
before it had to encounter a hostile heresy, the council of Paris had
deplored the pervading corruptions with exceeding candor. The
condition of conventual discipline was such as to threaten the very
existence of the system, and the customary denunciations of
ineradicable abuses were freely published.1320 In 1528 the Cardinal-
legate Duprat, Chancellor of France, held a council in Paris, where he
condemned, seriatim, the new doctrines as heresies, and elevated
the rule of celibacy to the dignity of a point of faith.1321 He also
caused the adoption of a series of canons designed to remove from
the church the disgrace caused by the laxity of clerical morals and
manners. The bishops were instructed to enforce the decrees of the
councils and of the fathers until concubinage and incontinence
should be completely exterminated, and a rule was laid down which
would have been eventually effectual if conscientiously carried out.
No one was thereafter to be admitted to holy orders without written
testimony as to his age and moral character from his parish priest,
substantiated by the oaths of two or three approved witnesses.1322
At the same time similar councils were held at Bourges by the
Cardinal Archbishop Tournon, and at Lyons by Claude, Bishop of
Macon. To what extent these excellent rules were put in force may
be guessed by a description of the French clergy in 1560, as
portrayed by Monluc, Bishop of Valence, in a speech before the royal
council. The parish priests were for the most part engrossed in
worldly pursuits, and had obtained their preferment by illicit means,
nor did there seem much prospect of an improvement so long as the
prelates were in the habit of bestowing the benefices within their gift
on their lackeys, barbers, cooks, and other serving men, rendering
the ecclesiastics as a body an object of contempt to the people.1323
We need, therefore, not be surprised to find in the councils of the
period a repetition of all the old injunctions, showing that the
maintenance of improper consorts and the disgrace of priestly
families were undiminished evils.1324 This description of the French
clergy is most emphatically extended to the whole church in the
project for reformation drawn up by order of Paul III. in 1538, and
to these evils are attributed the innumerable scandals which afflicted
the faithful, as well as the contempt in which the ecclesiastical body
was held and the virtual extinction of all reverence for the services of
religion.1325
In 1530 Clement VII. addressed himself vigorously to the task of
putting an end to the scandalous practice of hereditary transmission
of benefices, which he describes as almost universal. A special Bull
was issued, prohibiting the children of priests or monks from
enjoying any preferment in their father’s benefices, and, recognizing
that the Roman curia was one of the chief obstacles to all reform, he
provided that if he or his successors should grant dispensations
permitting such infraction of the canons, they should be considered
as issued unwittingly, and be held null and void.1326 Like so many
others, this Bull seems to have been forgotten almost as soon as
issued, and the pecuniary needs of the Roman court rendered it
unable to abandon so lucrative a source of revenue. Even as soon as
1538 the cardinals to whom Paul III. committed the task of drawing
up the project of reformation cautiously intimate that they hear of
such dispensations being granted, and to this they attribute a large
share of the troubles of the church and the enmity felt towards the
Holy See.1327 This warning passed unheeded, and, as we have seen,
in 1559 a Scottish council prayed the queen-regent to use her
influence with the pope to prevent dispensations being granted to
enable illegitimate children to hold preferment in their father’s
benefices,1328 while in 1562 the frequency and readiness with which
such dispensations were still obtained are enumerated in a list of
abuses laid before the council of Trent by Sebastian King, of
Portugal, as one of the matters requiring reformation by the
supreme power of the council.1329 To this and other similar appeals
the papal legates loftily replied that laws were not to be prescribed
to the Holy See;1330 and the motive for the refusal is easily
comprehended when we see that in the “Taxes of the Penitentiary”
the price for a dispensation admitting the bastard of a priest to holy
orders was a ducat and a carlino.1331
In Spain, the most dangerous opponent of the Reformation,
Ignatius Loyola, succeeded to some extent in repressing the public
and unblushing manifestation of concubinage. His biographer states
that the female companions of the Peninsular clergy were
accustomed to pledge their faith to their consorts, as if united by the
marriage-tie, and that they wore the distinguishing costume of
married women, as though glorying in their shame.1332 Scandalized
by this, on his return to his native land, in 1535, Ignatius exerted
himself to abolish it, together with other priestly peccadilloes, and
his influence was sufficient to procure the enactment and
enforcement by the temporal authorities of sundry laws which
relieved the Spanish church from so great an opprobrium.1333 Yet,
though this semi-authorized cohabitation may have been checked,
the custom of notorious concubinage continued to flourish.
Bernardino Diaz de Luco, a Spanish jurist, not long afterwards,
deplores the frequency of the vice, but warns judges that they
should not be over-severe in repressing it, since so few are found
guiltless, and there is danger that those who are restrained from it
may be forced into darker sins.1334
About the same time, Hermann von Wied, Archbishop of Cologne,
undertook the reformation of his extensive diocese. He assembled a
council which issued a series of 275 canons, prescribing minutely the
functions, duties, and obligations of all grades of the clergy. As
regards the delicate subject of concubinage, he contented himself
with quoting the Nicene canon prohibiting the residence of women
not nearly connected by blood, and added that if the degeneracy of
the times prevented the enforcement of a regulation so strict, at all
events he forbade the companionship of females obnoxious to
suspicion.1335 The good bishop himself could hardly have expected
that so mild an allocution would have much effect upon a perverse
and hardened generation.
In 1537, Matthew, Archbishop of Salzburg, assembled his
provincial synod, which, recognizing the urgent necessity of
preserving the church and protecting the people, adopted a series of
reformatory canons. Apparently afraid of promulgating them,
however, it was resolved to suppress them for the present under the
pretext that the approaching general council would regulate the
discipline of the church at large, and the archbishop contented
himself with a pastoral letter addressed to his suffragans, in which
he urged upon them to consider the contamination to which the laity
were exposed through the vices of their pastors, and timidly
suggested that, if the clergy could not restrain their passions, they
should at all events indulge them secretly, so that scandal might be
avoided and the punishment of their transgressions be left to an
avenging God.1336
Even in the council of Trent itself, the Bishop of St. Mark, in
opening its proceedings with a speech, January 6th, 1546, drew a
fearful picture of the corruption of the world, which had reached a
degree that posterity might possibly equal but not exceed. This he
assured the assembled fathers was attributable solely to the
wickedness of the pastors, who drew their flocks with them into the
abyss of sin. The Lutheran heresy had been provoked by their own
guilt, and its suppression was only to be hoped for by their own
reformation.1337 At a later session, the Bavarian orator, August
Baumgartner, told the assembled fathers that the progress of the
Reformation was attributable to the scandalous lives of the clergy,
whose excesses he could not describe without offending the chaste
ears of his auditory. He even asserted that out of a hundred priests
there were not more than three or four who were not either married
or concubinarians1338—a statement repeated in a consultation on
the subject of ecclesiastical reform drawn up in 1562 by order of the
Emperor Ferdinand, with the addition that the clergy would rather
see the whole structure of the church destroyed than submit to even
the most moderate measure of reform.1339

It is not to be wondered therefore that the Christian world had


long and earnestly demanded the convocation of an œcumenic
council which should represent all parties, should have full powers to
reconcile all differences, and should give to the ancient church the
purification thus recognized as the only efficient means of healing
the schism. This was a remedy to the last degree distasteful to the
Holy See. The recollections of Constance and Bâle were full of
pregnant warnings as to the almost inevitable antagonism between
the Vicegerent of Christ and an independent representative body,
believing itself to act under the direct inspiration of the Holy Ghost,
claiming autocratic supremacy in the church, and convoked for the
special purpose of reforming abuses, the most of which were fruitful
sources of revenue to the papal court. Such a body, if assembled in
Germany, would be the pope’s master; if in Italy, his tool; and it
behooved him to act warily if he desired to meet the unanimous
demand of Christendom without risking the sacrifice of his most
cherished prerogatives. Had the council been called in the early days
of the Reformation, it could hardly have prevented the separation of
the churches; yet, in the temper which then existed, it would
probably have effected as thorough a purification of the
ecclesiastical establishment as was possible in so corrupt an age. By
delaying it until the reactionary movement had fairly set in, the
chances of troublesome puritans gaining the ascendency were
greatly diminished, and the papal court exposed itself to little danger
when, under the urgent pressure of the emperor, it at length, in
1536, proposed to convoke the long desired assembly at
Mantua.1340
A place so completely under papal influence was not likely to meet
the views of the opposition, and it is not surprising that both the
Lutherans and Henry VIII. refused to connect themselves with such
a council. The latter, indeed, in his epistle of April 8, 1538, to Charles
V., expressed himself more forcibly than elegantly:—“Nowe, if he
[the pope] calle us to one of his owne townes, we be afraid to be at
suche an hostes table. We saye, Better to ryse a hungred, then to
goo thense with oure bellyes fulle.”1341 The formality of its opening,
May 17th, 1537, was therefore an empty ceremony; its transfer to
Vicenza was little more; and, as no delegates presented themselves
up to the 1st of May, 1538, it was prorogued until Easter, 1539, with
the promise of selecting a satisfactory place for the meeting. The
pressure still continued until, in May, 1542, Paul finally convoked it to
assemble at Trent. The Reformers were no better satisfied than
before. They had so long professed their readiness to submit all the
questions in dispute to a free and unbiased general council, that
they could not refuse absolutely to countenance it; but they were
now so completely established as a separate organization, that they
had little to hope and everything to fear from the appeal which they
had themselves provoked, and nothing which Rome could now offer
would have brought them into willing attendance upon such a
body.1342 They accordingly kept aloof, and on the assembling of the
council, November 22d, 1542, its numbers were so scanty that it
could accomplish nothing, and it was accordingly suspended in July,
1543. When again convoked, March 15th, 1545, but twenty bishops
and a few ambassadors were present; these waited with what
patience they might command for accessions, which were so tardy in
arriving that when at length the assembly was formally opened, on
the 13th of December, the number had increased by only five. For
fifteen months the council continued its sessions, completely under
the control of the pope, and occupied solely with measures designed
to draw the line between the Catholic and the Reformed churches
more sharply than ever.
The appeals of the German bishops and of the imperial
ambassadors for some effective efforts at reform became at length
too pressing, and to evade them, in March, 1547, the council was
transferred to Bologna, against the earnest protest of the emperor
and the Spaniards, who refused to follow.1343 At Bologna little was
done except to dispute over the sharp protests of the emperor and
to adjourn the council from time to time, until, after falling into
universal contempt, it was suspended in 1549. Julius III., who
received the tiara on the 22d of February, 1550, signalized his
accession by convoking it again at Trent; and there it once more
assembled on the 1st of May, 1551.
At that time Lutheranism in Germany was under the heel of
Charles V.; Maurice of Saxony was ripening his schemes of revolt,
and concealing them with the dexterity in which he was unrivalled; it
was the policy of both that Protestant theologians should take part
in the discussions—of the one, that they should there receive their
sentence; of the other, that their presence might assist in cloaking
his designs. The flight from Innspruck, followed by the Transaction
of Passau, changed the face of affairs. The Lutheran doctors
rejoicingly shook the dust from their feet as they departed from
Trent, complaining that they had been treated as criminals on trial,
not as venerable members of a body assembled to decide the
gravest questions relating to this life and that to come. Other
symptoms of revolt among the Catholic nations were visible, and on
the 28th of April, 1552, the council again broke up.1344
Ten years passed away; the faithful impatiently demanded the
continuation of the work which had only been commenced, and at
last the pressure became so strong that Pius IV. was obliged to
reassemble the council.1345 His Bull bears date November, 1560, but
it was not until twenty years after Trent had witnessed the first
convocation that the holy men again gathered within its walls, and
on the 18th of January, 1562, the council resumed its oft-interrupted
sessions. The States of the Augsburg Confession had been politely
invited to participate in the proceedings, but they declined with the
scantest of courtesy.1346
During this long-protracted farce there were times when those
who sincerely desired the restoration of the church could not restrain
their impatience. In 1536, Paul III., who earnestly admitted the
necessity of some reform, called to his aid nine of his prelates most
eminent for virtue and piety, as a commission to prepare a scheme
for internal reformation.1347 According to a papal historian, his
object in this was to stop the mouths of the heretics who found in
the Roman court an inexhaustible subject of declamation.1348 For
two years the commission labored at its work, and finally produced
the “Consilium de emendanda ecclesia,” to which allusion has been
made above.
The stern and unbending Cardinal Caraffa was head of the
commission, assisted by such men as Contarini, Sadoleto, and
Reginald Pole. They seem to have been inspired with a sincere
desire to root out the chief abuses which gave such power to the
assaults of the Protestants, and the result of their labors affords us a
picture of ecclesiastical corruptions almost as damaging to the
church as the complaints of the Diet of Nürnburg. As regards
celibacy, they were disposed to make no concession; indeed, they
protest against the facility with which men in holy orders were able
to purchase from the Roman curia dispensations to marry. It is
significant, however, that they had so little confidence in the
possibility of purifying the religious orders that they actually
recommended the abolition of the whole monastic system. To
prevent individual cases of suffering they proposed that the convents
should not be immediately abolished, but that all novices should be
discharged and no more be admitted, thus allowing the orders to die
out gradually, as had been done in Saxony; and meanwhile they
urged that, to prevent further scandals, all nunneries should be
removed from the supervision and direction of monks.1349 The
“Consilium,” in fact, was so candid a confession of most of the
abuses charged upon the church by the reformers that Luther
forthwith translated it and published it with a commentary, as an
effective pamphlet in aid of his cause. Caraffa himself, after he had
attained the papacy, under the name of Paul IV., quietly put his own
work, in 1559, into the Index Expurgatorius.1350
The changes recommended in the “Consilium” attacked too many
vested interests for Paul III., however earnest himself, to be able to
give it effect. The project therefore was dropped and only resulted in
rendering still more clamorous the call for a reform in the head and
members of the church. As, moreover, it had shown the
powerlessness of the papacy to overcome acknowledged abuses, the
only hope of a radical change, such as was needful, was seen to lie
in the untrammelled debates of a great assembly, which should meet
as a parliament of the nations; and the prospect of this grew more
and more distant. While the project of transferring the council from
Trent was being matured, it occurred to the papal court that possibly
the objections to that measure and the pressure on the council for a
thorough reformation might be averted by showing a disposition on
the part of Rome to undertake the task of cleansing the Augean
stable. It was also recognized as an important gain if the council
could be confined to the harmless task of defining questions of faith,
while the substantial powers involved in reforming the corruptions of
the church could be claimed and exercised by the Pope. Accordingly
Pius III. drew up an elaborate Bull designed to limit some of the
more flagrant pecuniary abuses which existed, and exhorting the
bishops to correct the morals of their subordinates. This was sent to
the legates at Trent, but they and their confidants unanimously
agreed that, in the existing temper of the council, the promulgation
of such a document would be in the highest degree imprudent. It
was accordingly suppressed, and has only seen the light within the
present century.1351 In its failure the church lost but little, for it
touched the evils of the time with a tender and hesitating hand, and
would have proved utterly inefficacious.
At length, when shortly afterwards the unmannerly urgency of the
Germans, clamoring for decided measures of reform, was met by the
translation of the council to Bologna in 1547, and men despaired of
further results from it, Charles V. resolved to take the matter into his
own hands, and to effect, for his own dominions at least, that which
had been vainly expected of the council for Christendom. The
“Interim,” which has already been alluded to, was intended to
answer this purpose as far as Lutheranism was concerned, in healing
the breach of religion. The other great object of the council, the
restoration of the neglected discipline of the church, he attempted to
effect by means of the secular authority of the empire acting on the
regular machinery of the Teutonic ecclesiastical establishment. How
utterly neglected that discipline had become is inferable from an
expression in the important and carefully drawn project which had
been laid by Charles before the Diet of Ratisbon in 1541, to the
effect that if the canon requiring celibacy was to be enforced, it
would be necessary also to revive those canons which punished
incontinence, thus admitting that there existed no check whatever
upon immorality.1352
To accomplish this desirable revival of discipline he accordingly
caused the adoption by the Diet of Augsburg of a code of
reformation, well adapted, if enforced, to restore the long-forgotten
purity of the church, while at the same time it acknowledged that
the degeneracy of the times rendered impossible the resuscitation of
the ancient canons in their strictness. Thus, after reciting the canon
of Neocæsarea (see p. 51), it adds, that as such severity was now
impracticable, those in holy orders convicted of impurity should be
separated from their concubines, and visited with suspension from
function and benefice proportioned to the gravity of the offence. A
repetition of the fault was punishable with increased severity, and
incorrigible sinners who were found to be incapable of reformation
were finally to be deprived of their benefices. As concubines were
threatened with immediate excommunication, it is evident that a
severity was designed towards them which was not ventured on with
respect to their more guilty partners. Relaxation of the rules is also
observable in the section which, despite the Nicene canon, permitted
the residence of women over forty years of age, whose character
and conduct relieved them from suspicion.1353 The imperative
injunctions of chastity laid upon the regular clergy, canons, and
nuns, show not only the determination to remove the prevailing
scandals, but also the magnitude and extent of the evil.1354
Nor was this all. Local councils were ordered for the purpose of
embodying these decrees in their statutes, and of carrying out with
energy the reformation so earnestly desired. Thus, in November,
1548, about five months after the Diet, a synod assembled at
Augsburg, which inveighed bitterly against the unclerical dress and
pomp of the clergy, their habits of drunkenness, gluttony,
licentiousness, tavern-lounging, and general disregard of discipline;
and adopted a canon embracing the regulations enacted by the
emperor.1355 The Archbishop of Trèves did not wait for his synod,
but issued, October 30th, a mandate especially directed against
concubinary priests, in which he announced his intention of carrying
out the reform commanded by Charles. He could find no reason
more self-evident for the dislike and contempt felt by the people for
so many of the clergy than the immorality of their lives, differing
little, except in legality, from open marriage. “This vice, existing
everywhere throughout our diocese, in consequence of the license of
the times and the neglect of the officials, we must eradicate.
Therefore all of you, of what grade soever, shall dismiss your
concubines within nine days, removing them beyond the bounds of
your parishes, and be no longer seen to associate with loose and
wanton women. Those who neglect this order shall be suspended
from office and benefice, their concubines shall be excommunicated,
and they themselves be brought before our synod to be presently
held.”1356
These were brave words, but when, some three weeks later, the
synod was assembled, and the malefactors perchance brought
before it, the good bishop found apparently that his flock was not
disposed to submit quietly to the curtailment of privileges which had
almost become imprescriptible. His tone accordingly was softened,
for though he deprecated their immorality more strongly than ever,
and asserted his intention of enforcing his mandate, he
condescended to argue at much length on the propriety of chastity,
and even descended to entreaty, beseeching them to preserve the
purity so essential to the character of the church, the absence of
which had drawn upon the clergy an odium which could scarce be
described in words.1357 How slender was his success may be
inferred from the fact that the next year he felt it necessary to hold
another synod, in which he renewed and confirmed the proceedings
of the former one, and endeavored to reduce the monks and nuns of
his diocese into some kind of subjection to the rules of
discipline.1358
The Archbishop of Cologne was as energetic as his brother of
Trèves, with about equal success. On September 1st he issued the
Augsburg Formula of Reformation, with a call for a synod to be held
on October 2d. At the same time he manifested his sense of the
primary importance of correcting clerical immorality by promulgating
a special mandate respecting concubinage. He asserted this to be
the chief cause of the contempt popularly felt for the church,1359
and he ordered all ecclesiastics to send their women beyond the
bounds of their parishes within nine days, under the penalties
provided in the imperial decree. The synod was held at the time
indicated, and, though it adopted no regular canons, it accepted the
Augsburg Formula and the mandate of the archbishop, with a trifling
alteration.1360
This proved utterly ineffectual, for in March, 1549, he assembled a
provincial council, in which he deplored the license of the times,
which rendered the strictness of the ancient canons unadvisable,
and he announced that it had been decided to proceed gradually
with the intended reforms. As to the morals of the clergy, he stated
that everywhere the cure of souls was delegated to improper
persons, many of them living in the foulness of concubinage, in
perpetual drunkenness, and in other infamous vices, encouraged by
the negligence of bishops and the thirst of archdeacons for
unhallowed gains. The unions of those who, infected by the new
heresies, did not hesitate to enter into matrimony, were of course
pronounced illicit and impious, their offspring illegitimate, and the
parents anathematized; but for those who remained in the church,
yet submitted to no restraint upon their passions, a more merciful
spirit was shown, for the punishments ordered by the Diet of
Augsburg were somewhat lightened in their favor. The extreme
license of the period may be understood from another canon
directed against the comedians, who, not content with the ordinary
theatres, were in the habit of visiting the nunneries, where their
profane plays and amatory acting excited to unholy desires the
virgins dedicated to God.1361 No one acquainted with the coarseness
of the drama of that rude age can doubt the propriety of the
archbishop’s reproof. Supplementary synods were also held in
October, 1549, and February, 1550, to perfect the details of a very
thorough inquisitorial visitation of the whole province.
This visitation, so pompously heralded, did not take place. At a
synod held in October, 1550, the archbishop made sundry lame
excuses for its postponement. Another synod was assembled in
February, 1551, at which we hear nothing more of it; but the
prelates of the diocese were requested to collect such ancient and
forgotten canons as they could find, which might be deemed
advantageous in the future;1362 and with this the work of
reformation in the province of Cologne appears to end.
In 1549, Ernest, Archbishop of Salzburg, assembled the synod of
his extensive province, but when his clergy understood that it was
intended to confirm the reformatory edict of the emperor, they had
the audacity to present a petition praying that the clause ordering
the removal of their concubines should not be enforced. They
declared that the attempt to do so would be attended with serious
difficulty, and that it would lead to greater evils than it sought to
remove, and they asked that the consideration of the matter should
be referred to the general council, whose reassembling was no
longer dreaded. The synod, with a proper sense of its dignity,
refused to receive the shameless petition, and listened rather to
those of its members who complained of the practice of the officials
in receiving bribes for permitting illicit indulgences, and the
representations of Duke William, of Bavaria, who asserted that the
Lutheran heresy had been caused by the scandalous corruption of
the church. A canon was accordingly adopted which renewed the
regulations of Bâle and ordered the speedy removal of all recognized
and notorious concubines.1363
In October and November, 1548, and April, 1549, the Bishops of
Paderborn, Wurzburg, and Strassburg held synods which adopted
the reformatory measures decreed at Augsburg.1364 These were
preparatory to the metropolitan synod of Mainz, assembled in May,
1549, which commanded that no one should be thereafter admitted
to orders without a preliminary examination by his bishop on the
subject of doctrine, and testimonials from the people as to purity of
character. After thus wisely providing for the future, attention was
directed to the present. It was declared intolerable that, in spite of
the reiterated prohibitions of the fathers and councils, concubines
should be universally kept; the Basilian canon was therefore revived,
and its enforcement strictly enjoined on the ordinaries, who were
forbidden in any manner to connive at these disorders for the sake
of profit.1365
The pressure was continued, for when Cambrai, which owed
temporal obedience to the emperor, while ecclesiastically it formed
part of the province of Rheims, neglected to adopt the Formula of
Augsburg for two years, it was not allowed to escape. In October,
1550, a synod was finally assembled there under stringent orders
from Charles, and the Formula was published, together with an
elaborate series of canons, which would have been well adapted to
correct abuses that were not incorrigible.1366

Charles had thus exerted all the resources of his imperial


supremacy, and, whether willingly or not, the powerful prelates who
ruled the German church had united in carrying out his views. The
temporal and spiritual authorities had thus been concentrated upon
the vices of the church, and if its reformation had been possible, in
the existing condition of its organization, some improvement must
have resulted from these combined and persistent efforts. How
nugatory were the results may be guessed from a memorial
presented in 1558, by the University of Louvain, to Philip II.,
exhorting him to grant no toleration to the heretics, but, at the same
time, urging upon him the absolute necessity of some
comprehensive system of reform to purify the church, all the orders
of which were given over utterly to the twin vices of avarice and
licentiousness.1367 The same testimony is borne by a consultation
drawn up in 1562 by order of the Emperor Ferdinand. After alluding
to the efforts at reform made by Paul III. and Charles V., it declares
that their only result has been to make the condition of clerical
morality worse than before, exciting the hatred of the people for
their priests to an incredible pitch, and doing more to inflame the
ardor of heresy than all the teaching of Christian truth can do to
restrain it.1368
As the failure of all efforts to improve clerical morality under the
existing rules of discipline was thus found to be complete, there
arose in the minds of thinking men a conviction, such as Erasmus
had already declared, that, since all other measures had proved
fruitless, the only mode of securing a virtuous clergy was to remove
the prohibition of marriage. At the Polish Diet of 1552 petitions
praying for sacerdotal matrimony were presented, and, though they
failed in their object, the Diet of 1556 authorized King Sigismund
Augustus to address Paul IV. with a request, in the name of the
nation, to grant it as well as communion in both elements.1369
The dissension thus existing within the church is exhibited in a
volume published in 1558 by Stanislas Hosius, Bishop of Ermeland,
earnestly arguing against communion in both elements, clerical
marriage, and the use of the vulgar tongue in worship. As regards
celibacy, he assumes that it had been maintained unbrokenly for
fifteen hundred years, and was not now to be abandoned to gratify a
few disorderly monks. The example of the Greek church he meets by
pointing out that the Greeks were suffered to be persecuted by the
Turks; the argument that marriage would purify the church he
silences with the observation that many married men are adulterers;
and he holds it to be a doubting of God to suppose that the gift of
continence would be denied to those who properly seek it.1370 In
spite of the logic of polemics such as Hosius, the opinions of the
innovators continued to gain ground, until at length they won even
the highest dignitaries of the empire, and in 1560 the Emperor
Ferdinand himself undertook their advocacy with the pope, after
having for some years countenanced the practice within his own
territories.
Almost immediately on the consecration of Pius IV., in addressing
to him an argument for the reassembling of the council of Trent, or
the convocation of a new council, Ferdinand seized the opportunity
to ask especially for the communication of the cup to the laity, and
permission for the clergy to marry. The latter of these points he
considered to be the only remedy for the fearful immorality of the
church, for, though all flesh was corrupt, the corruption of the
priesthood surpassed that of all other men.1371 That he had not
waited for the papal assent to favor these innovations within his own
dominions is shown by his statement that the Archbishop of Salzburg
had recently, in a synod, earnestly called upon him to put a stop to
the progress which they were making, but, he added, his long
experience in such matters had shown him what was possible, and
what impossible, and he had accordingly set forth the difficulties of
the task in a paper addressed to the archbishop, a copy of which he
inclosed to the pope.1372
The nuncio Commendone, in transmitting this document to Rome,
accompanied it with a letter from the Cardinal Bishop of Augsburg,
recommending the postponement of the question until the
reassembling of the council of Trent, and, as Pius answered it in this
sense, no further action was taken, though Ferdinand made haste to
repeat his demand, in view of the impatience of both clergy and
people, who could ill brook the delays inseparable from the
discussion of the subject in so unwieldy a body.1373 When
Commendone, moreover, passed through Cleves on his way to the
council, then about to be reopened, the Duke of Cleves earnestly
besought him to lend his influence to the accomplishment of the
measure, urging as a reason that in the whole of his dominions—and
he was sovereign of three populous duchies—there could not be
found five priests who did not keep concubines. In order to secure
his favor for the approaching council, Commendone did not scruple
to hold out expectations that the concessions would be granted.1374
During the progress of the Reformation, when the fate of the
Catholic church of Germany had sometimes seemed to hang in the
balance, no princes had earned a larger title to the gratitude of
Rome than the powerful Dukes of Bavaria, who were the leaders of
the reaction. Yet now the influence of that important region was
thrown in favor of the abrogation of celibacy, and Duke Albert was
the first who boldly brought the matter before the council by a
demand for ecclesiastical marriage, presented on the 27th of June,
1562. To this the evasive answer was returned that the council
would take such action as would be found to redound to the glory of
God and to the benefit of the church.1375 During the same year the
Emperor Ferdinand also repeatedly urged its consideration. A plan
for the reform of the church presented by his delegates not only
called attention to the necessity of purifying the morals of the
regular and secular clergy, but demanded that, to some nations at
least, the privilege of sacerdotal marriage should be conceded.1376
Another elaborate paper argued the question with much temperate
force, and declared that many priests had already married for the
purpose of escaping the corruptions of celibacy, while studiously
preserving themselves from the errors of Lutheranism. Out of a
hundred parish priests scarcely one could be found who was not
either openly or secretly married, and it was necessary to tolerate
them to prevent the utter destruction of the church.1377
A third document is extant, without date, which was laid before
the cardinals of the papal court by the emperor, in which the
question was argued at considerable length and with much
vehemence. After asserting that from the records of the primitive
church celibacy was not then recognized as imperative, it proceeded
to declare that if marriage ever were permissible, the present carnal
and licentious age rendered it a necessity, for not one Catholic priest
out of fifty could be found who lived chastely. All were asserted to
be notoriously dissolute, scandalizing the people and inflicting great
damage on the church. The request was made not so much to
satisfy the priests who desired marriage as to meet the wishes of the
laity, for many patrons of livings refused presentation to all but
married men. However preferable a single life might be for the
clergy, it therefore was thought better to give it up than to leave
open the door to the scandalous impurities traceable to celibacy.
Another weighty reason was alleged in the great scarcity of priests,
caused alone by the prohibition of marriage, in proof of which it was
urged that the Catholic schools of divinity were all but empty and the
episcopal function of ordination nearly disused, while the Lutheran
colleges were crowded by those who subsequently obtained
admission into the true church, where they worked incredible
mischief. The argument that the temporal possessions of the church
would be imperilled by sacerdotal matrimony was met by indignantly
denouncing the worldly wisdom which would protect such perishable
interests at the cost of innumerable souls sacrificed by the existing
condition of affairs. For these and other reasons it asked that
marriage should in future be allowed to all the priesthood, whether
already in orders or to be subsequently admitted: that married men
of good character and education should be ordained to supply the
want of pastors: that those who had contracted matrimony, in
contravention of the canons, should no longer be ejected, seeing
that it was most absurd to turn out men because they were married,
while retaining notorious concubinarians, and that if, with equal
justice, both classes should be dismissed, the people would be left
almost, if not entirely, destitute of spiritual guides. The paper
concluded by asserting that if the prayer be granted the clergy could
be retained in the church and in the faith, to the great benefit of
their flocks, and that the scandal of promiscuous licentiousness,
which had involved the church in so much disgrace, would be
removed.1378
This vivid sketch of the condition of the church, with the evils
which were everywhere felt, and the remedies which suggested
themselves to clear-sighted and impartial men, was as ineffectual as
other similar efforts had been, for to all such arguments the council
of Trent was deaf. France, too, was more than willing to see celibacy
abolished. M. de Lanssac, the French ambassador, was ordered to
place himself in close relations with the representatives of the
emperor, and to unite with them in seeking the relaxation of all
regulations which tended to prevent the reunion of the Protestants,
while the Gallican bishops were commanded to show themselves
reasonable and yielding in such matters; and when Lanssac reported
the demands of the emperor, comprehending clerical marriage
among other changes, Charles IX. assented to them in terms of
warm commendation.1379 The Cardinal of Lorraine, moreover, was
instructed to urge some measures efficient to reform the licentious
lives of the ecclesiastics which spread corruption and debauchery
among the people, while permission for priestly marriage was
recommended as one of the means essential to recall the heretics to
the bosom of the true church.1380 As a compromise, however, the
French prelates contented themselves with suggesting that none but
elderly men should be eligible to the priesthood, and that the
testimony of the people in favor of their moral character should be a
prerequisite to ordination, in hopes that by such means the
necessary purification of the clergy at least could be effected, while
the sharpest measures should be adopted to punish their
licentiousness.1381
All this was useless, and, in fact, it is difficult to imagine how any
one could expect a reform of this nature from a body composed of
prelates all whom were obliged by Pius IV., in a decree of September
4th, 1560, to solemnly swear to a profession of faith containing a
specific declaration that the vows of chastity assumed on entering
into holy orders or monastic life were to be strictly observed and
enforced.1382 The question thus was prejudged, and the council was
more likely to listen to Bartholomew a Martyribus, the Archbishop of
Bracara, who laid before them a paper containing the points which,
in his opinion, required reformation, among which were the revival
of the canons respecting concubinary bishops and priests, the
prohibition of sons succeeding to their father’s benefices, and the
excommunication of confessors who debauched their fair
penitents1383—though when the sturdy archbishop in a stormy
debate declared that “illustrissimi cardinales egent illustrissima
reformatione,” he doubtless was held to be a most uncourtly and
impracticable reformer.
Despite all the urgency from without, it was not until the 8th of
February, 1563, after the council had been in session for more than
a year, that the theologians at last arranged for disputation the
articles on matrimony, and laid them before the council for
discussion. They were divided into five classes, of which the fourth
was devoted to the bearing of the subject on the clergy, consisting
of two propositions artfully drawn up to justify rejection, while
preserving the appearance of presenting the subject for deliberation.
—That matrimony was preferable to celibacy, and that God bestowed
grace on the married rather than on the single.—That the priests of
the Western Church could lawfully contract marriage,
notwithstanding the canons; that to deny this was to condemn
matrimony, and that all were at liberty to marry who did not feel
themselves graced with the gift of chastity.1384
The disputation on the various questions connected with
matrimony commenced the next day, and was continued at intervals
for six months. By August 7th all the canons on the subject were
agreed to, except the one on clandestine marriages, which gave the
fathers much more trouble than the more important decision
respecting the retention of celibacy.1385 This latter, indeed, was a
foregone conclusion. In the minute account, transmitted from day to
day by Archbishop Calini to Cardinal Cornaro, in which all the details
of internal discussion and external intrigue attainable by a quick-
witted member of the council were reported, there is no allusion to
the subject. No debates or diversity of opinion are mentioned, no
intimation that the matter was regarded as open to a doubt, and
even the appeals made by the emperor and other potentates are
passed over in silence, for the very sufficient reason that the papal
legates, who controlled all the business of the council, refused to
allow them to be read.1386 In their reply to the emperor’s
remonstrances, indeed, they declared that to have such a subject
publicly broached in the council would create a fearful scandal
throughout Christendom, and Pius IV. approved of their answer as
the best that could be given.1387 It is no wonder, therefore, that in
the correspondence of the nuncio Visconti the only allusion to the
matter is a simple reference, under date of March 22, 1563, to the
demand previously made by the Duke of Bavaria.1388
In fact, when, on March 4th, the 5th and 6th articles were
reached, they were both unanimously pronounced heretical without
any prolonged debate. Doctor Juan de Ludegna pronounced a
“disputation” on the subject, the tone of which showed that the
result was already decided, and that the only disposition of the
council was to vilify those who desired the abrogation of
celibacy.1389 A discussion, however, then arose as to the power of
the pope to dispense the clergy, both regular and secular, from the
obligation of celibacy, and on this point there was considerable
diversity of opinion, occupying numerous successive meetings in its
settlement. The majority were in favor of the papal power; and its
exercise in the existing condition of the church was even
recommended by those who recognized the evils of the system, but
shrank from the responsibility of themselves introducing the
innovation. This was promptly rebuked by the conservatives,
according to Fra Paolo, with the remark that a prudent physician
would not attempt to cure one disease by bringing on a greater.1390
The legates, indeed, were blamed for allowing any discussion on so
dangerous a topic, since, if priests were permitted to marry, their
affections would be concentrated on family and country, in place of
the church; their subjection to the Holy See would be diminished,
the whole system of the hierarchy destroyed, and the pope himself
would eventually become a simple Bishop of Rome.1391 If such
consequences as these were anticipated by the able men who
represented the papal interests, we may readily believe that
Pallavicini speaks the sense of the managers of the council when he
remarks, concerning the princes who exerted themselves in favor of
sacerdotal marriage, that they seemed to consider that the council
had been convoked for the purpose not of condemning but of
contenting the heretics, whom they proposed to convert by
gratifying in place of repressing their contumacious desires.1392 If
this be so, the Protestants were amply justified in refusing to submit
their cause to a body so different in its objects from that free and
unbiased œcumenic council to which they had so often appealed
from their persecutors.
Yet, notwithstanding that the policy of the church was thus
immutable, there seems to have been no hesitation in holding out
fallacious hopes to the expectant populations. When, in the spring of
1563, the Bavarians, wearied with endless promises, rose in revolt
and demanded the use of the cup and priestly marriage, their duke
was obliged to make a promise to his Diet that if the required
concessions were not granted in June, by either the council or the
pope, he would himself give the desired permission. The threatened
defection of this Catholic stronghold caused such alarm that the
legates at Trent forthwith despatched Niccolo Ormanetto to the
duke, to persuade him to withdraw his promised reforms under a
pledge that the council would take such order as would satisfy the
demands of his people.1393
These promises were soon forgotten, though it was not until the
11th of November that the canons on matrimony were finally
adopted and formally published. Of these there are two relating to
our subject. The first one pronounced the dread anathema on all
who should dare to assert that clerks in holy orders, monks, or nuns
could contract marriage, or that such a marriage was valid, since
God would not deny the gift of chastity to those who rightly sought
it, nor would He expose us to temptation beyond our strength. The
other similarly anathematized all who dared to assert that the
married state was more worthy than virginity, or that it was not
better to live in celibacy than married.1394
Thus the church, in endeavoring to meet the novel exigencies
caused by the progress and enlightenment of mankind, in place of
making the concessions demanded by almost all beyond the narrow
pale of the papal court, devoted its energies to the miserable task of
separating itself as widely as possible from those who had left it.1395
Its rulers seemed to imagine that their only hope of safety lay in
intrenching themselves behind the exaggerations of those particular
points of policy which had afforded to their adversaries the fairest
chances of attack. The faithful throughout Germany might suffer
from the absence of the ministers of Christ, or might endure yet
more from the unrestrained passions of the wolves in sheep’s
clothing let loose among their wives and daughters, but the church
militant in this conjuncture dreaded even more to lose the aid of that
monastic army which, in theory at least, had no earthly object but
the service of St. Peter; it selfishly feared that the parish priest who
might legitimately see his fireside surrounded by a happy group of
wife and children would lose the devotion which a man without ties
should entertain for the prosperity and glory of the ecclesiastical
establishment; and perhaps, more than all, it saw with terror
avaricious princes eager for the secularization of that immense
property to which it owed so large a portion of the splendor which
dazzled mankind, of the influence which rendered it powerful, and of
the luxury which made its high places attractive to the ambitious and
able men who controlled its destiny. To put an end, therefore, at
once and forever, to the mutterings of dissatisfaction among those
who compared the calm and virtuous life of the Protestant pastors
with the reckless self-indulgence of the ministers of the old religion,
it was resolved to place the canon of celibacy in a position where
none of the orthodox should dare to attack it, and to accomplish this
the simple rule of discipline was elevated to the dignity of a point of
belief. As the church had already been forced, in defending the rule
from the assaults of the reformers, to attribute to it apostolic origin,
we may not perhaps be surprised that it was made a point of
doctrine, but we cannot easily appreciate the reasons that would
justify the anathema launched against all who regarded the marriage
Welcome to Our Bookstore - The Ultimate Destination for Book Lovers
Are you passionate about books 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!

ebookgate.com

You might also like