100% found this document useful (7 votes)
36 views

Fundamentals of Python First Programs 1st Edition Kenneth A. Lambert pdf download

The document provides information about the ebook 'Fundamentals of Python: First Programs' by Kenneth A. Lambert, which is available for download in various formats. It outlines the structure and content of the book, including chapters on computer science fundamentals, software development, control statements, and more. Additionally, it includes links to other programming-related ebooks and emphasizes the copyright and usage rights associated with the material.

Uploaded by

kugldgendo92
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
100% found this document useful (7 votes)
36 views

Fundamentals of Python First Programs 1st Edition Kenneth A. Lambert pdf download

The document provides information about the ebook 'Fundamentals of Python: First Programs' by Kenneth A. Lambert, which is available for download in various formats. It outlines the structure and content of the book, including chapters on computer science fundamentals, software development, control statements, and more. Additionally, it includes links to other programming-related ebooks and emphasizes the copyright and usage rights associated with the material.

Uploaded by

kugldgendo92
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/ 51

Fundamentals of Python First Programs 1st

Edition Kenneth A. Lambert pdf download

https://ebookname.com/product/fundamentals-of-python-first-
programs-1st-edition-kenneth-a-lambert/

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


Instant digital products (PDF, ePub, MOBI) available
Download now and explore formats that suit you...

Python High Performance Programming Boost the


performance of your Python programs using advanced
techniques 1st Edition Gabriele Lanaro

https://ebookname.com/product/python-high-performance-
programming-boost-the-performance-of-your-python-programs-using-
advanced-techniques-1st-edition-gabriele-lanaro/

Programming Fundamentals A Modular Structured Approach


Using C Kenneth Leroy Busbee

https://ebookname.com/product/programming-fundamentals-a-modular-
structured-approach-using-c-kenneth-leroy-busbee/

Reflections of a Technocrat Managing Defense Air and


Space Programs During the 1st Edition John L. & Kenneth
J. Alnwick & Lawrence

https://ebookname.com/product/reflections-of-a-technocrat-
managing-defense-air-and-space-programs-during-the-1st-edition-
john-l-kenneth-j-alnwick-lawrence/

Selected Letters of C G Jung 1909 1961 C. G. Jung


(Editor)

https://ebookname.com/product/selected-letters-of-c-g-
jung-1909-1961-c-g-jung-editor/
A season in hell the life of Arthur Rimbaud Carré

https://ebookname.com/product/a-season-in-hell-the-life-of-
arthur-rimbaud-carre/

Weapons of Mass Instruction A Schoolteacher s Journey


through the Dark World of Compulsory Schooling John
Taylor Gatto

https://ebookname.com/product/weapons-of-mass-instruction-a-
schoolteacher-s-journey-through-the-dark-world-of-compulsory-
schooling-john-taylor-gatto/

Vowels and consonants 3rd Edition Peter Ladefoged

https://ebookname.com/product/vowels-and-consonants-3rd-edition-
peter-ladefoged/

C Programming From Problem Analysis to Program Design


2nd Edition Barbara Doyle

https://ebookname.com/product/c-programming-from-problem-
analysis-to-program-design-2nd-edition-barbara-doyle/

Transitions and Learning through the Lifecourse 1st


Edition Kathryn Ecclestone (Editor)

https://ebookname.com/product/transitions-and-learning-through-
the-lifecourse-1st-edition-kathryn-ecclestone-editor/
Victory over cancer Updated Edition M.D. Matthias Rath

https://ebookname.com/product/victory-over-cancer-updated-
edition-m-d-matthias-rath/
Fundamentals of
Python:
First Programs

Kenneth A. Lambert
Martin Osborne, Contributing Author

Australia • Brazil • Japan • Korea • Mexico • Singapore • Spain • United Kingdom • United States

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
This is an electronic version of the print textbook. Due to electronic rights restrictions,
some third party content may be suppressed. Editorial review has deemed that any suppressed
content does not materially affect the overall learning experience. The publisher reserves the right
to remove content from this title at any time if subsequent rights restrictions require it. For
valuable information on pricing, previous editions, changes to current editions, and alternate
formats, please visit www.cengage.com/highered to search by ISBN#, author, title, or keyword for
materials in your areas of interest.

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Fundamentals of Python: First Programs © 2012 Course Technology, Cengage Learning
Kenneth A. Lambert ALL RIGHTS RESERVED. No part of this work covered by the copyright
herein may be reproduced, transmitted, stored or used in any form or by
Executive Editor: Marie Lee
any means graphic, electronic, or mechanical, including but not limited to
Acquisitions Editor: Brandi Shailer photocopying, recording, scanning, digitizing, taping, Web distribution,
Senior Product Manager: Alyssa Pratt information networks, or information storage and retrieval systems, except
Development Editor: Ann Shaffer as permitted under Section 107 or 108 of the 1976 United States Copyright
Act, without the prior written permission of the publisher.
Associate Product Manager: Stephanie
Lorenz
For product information and technology assistance, contact us at
Associate Marketing Manager: Shanna
Cengage Learning Customer & Sales Support, 1-800-354-9706
Shelton
For permission to use material from this text or product, submit all
Content Project Manager: Jennifer Feltri requests online at www.cengage.com/permissions
Art Director: Faith Brosnan Further permissions questions can be emailed to
permissionrequest@cengage.com
Image credit: © istockphoto/Pei Ling Hoo
Cover Designer: Wing-ip Ngan,
Ink design, Inc. Library of Congress Control Number: 2011920241
Compositor: GEX Publishing Services ISBN-13: 978-1-111-82270-5
ISBN-10: 1-111-82270-0

Course Technology
20 Channel Center
Boston, Massachusetts 02210
USA

Cengage Learning is a leading provider of customized learning solutions


with office locations around the globe, including Singapore, the United
Kingdom, Australia, Mexico, Brazil, and Japan. Locate your local office at:
international.cengage.com/region

Cengage Learning products are represented in Canada by Nelson


Education, Ltd.

For your lifelong learning solutions, visit course.cengage.com.

Purchase any of our products at your local college store or at our preferred
online store www.cengagebrain.com.

Some of the product names and company names used in this book have
been used for identification purposes only and may be trademarks or regis-
tered trademarks of their respective manufacturers and sellers.

Any fictional data related to persons or companies or URLs used through-


out this book is intended for instructional purposes only. At the time this
book was printed, any such data was fictional and not belonging to any real
persons or companies.

Course Technology, a part of Cengage Learning, reserves the right to revise this
publication and make changes from time to time in its content without notice.

The programs in this book are for instructional purposes only.


They have been tested with care, but are not guaranteed for any particular
intent beyond educational purposes. The author and the publisher do not
offer any warranties or representations, nor do they accept any liabilities
Printed in the United States of America with respect to the programs.
1 2 3 4 5 6 7 15 14 13 12 11

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Table of Contents
[CHAPTER] 1 INTRODUCTION 1
1.1 Two Fundamental Ideas of Computer Science: Algorithms and Information
Processing .................................................................................................................2
1.1.1 Algorithms ................................................................................................2
1.1.2 Information Processing............................................................................4
1.1 Exercises....................................................................................................................5
1.2 The Structure of a Modern Computer System .......................................................6
1.2.1 Computer Hardware ................................................................................6
1.2.2 Computer Software..................................................................................8
1.2 Exercises..................................................................................................................10
1.3 A Not-So-Brief History of Computing Systems...................................................10
1.3.1 Before Electronic Digital Computers ...................................................11
1.3.2 The First Electronic Digital Computers (1940–1950) .........................15
1.3.3 The First Programming Languages (1950–1965).................................16
1.3.4 Integrated Circuits, Interaction, and Timesharing (1965–1975) .........18
1.3.5 Personal Computing and Networks (1975–1990) ................................19
1.3.6 Consultation, Communication, and Ubiquitous Computing
(1990–Present)........................................................................................21
1.4 Getting Started with Python Programming..........................................................23
1.4.1 Running Code in the Interactive Shell .................................................23
1.4.2 Input, Processing, and Output...............................................................25
1.4.3 Editing, Saving, and Running a Script ..................................................28
1.4.4 Behind the Scenes: How Python Works ...............................................29
1.4 Exercises..................................................................................................................30
1.5 Detecting and Correcting Syntax Errors...............................................................31
1.5 Exercises..................................................................................................................32
Suggestions for Further Reading ...........................................................................32
Summary .................................................................................................................33
Review Questions ...................................................................................................35
Projects....................................................................................................................37

[CHAPTER] 2 SOFTWARE DEVELOPMENT, DATA TYPES, AND


EXPRESSIONS 39
2.1 The Software Development Process .....................................................................40
2.1 Exercises..................................................................................................................43
2.2 Case Study: Income Tax Calculator.......................................................................43
2.2.1 Request ...................................................................................................43
2.2.2 Analysis ...................................................................................................44
2.2.3 Design.....................................................................................................44
2.2.4 Implementation (Coding) ......................................................................45
2.2.5 Testing ....................................................................................................46

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
2.3 Strings, Assignment, and Comments.....................................................................47
2.3.1 Data Types..............................................................................................47
2.3.2 String Literals.........................................................................................48
2.3.3 Escape Sequences ...................................................................................50
2.3.4 String Concatenation .............................................................................50
2.3.5 Variables and the Assignment Statement ..............................................51
2.3.6 Program Comments and Docstrings.....................................................52
2.3 Exercises..................................................................................................................53
2.4 Numeric Data Types and Character Sets ..............................................................54
2.4.1 Integers ...................................................................................................54
2.4.2 Floating-Point Numbers........................................................................55
2.4.3 Character Sets ........................................................................................55
2.4 Exercises..................................................................................................................57
2.5 Expressions .............................................................................................................58
2.5.1 Arithmetic Expressions ..........................................................................58
2.5.2 Mixed-Mode Arithmetic and Type Conversions ..................................60
2.5 Exercises..................................................................................................................63
2.6 Using Functions and Modules ...............................................................................63
2.6.1 Calling Functions: Arguments and Return Values................................64
2.6.2 The math Module .................................................................................65
2.6.3 The Main Module..................................................................................66
2.6.4 Program Format and Structure .............................................................67
2.6.5 Running a Script from a Terminal Command Prompt ........................68
2.6 Exercises..................................................................................................................70
Summary .................................................................................................................70
Review Questions ...................................................................................................72
Projects....................................................................................................................73

[CHAPTER] 3 CONTROL STATEMENTS 75


3.1 Definite Iteration: The for Loop.........................................................................76
3.1.1 Executing a Statement a Given Number of Times ..............................76
3.1.2 Count-Controlled Loops .......................................................................77
3.1.3 Augmented Assignment .........................................................................79
3.1.4 Loop Errors: Off-by-One Error............................................................80
3.1.5 Traversing the Contents of a Data Sequence........................................80
3.1.6 Specifying the Steps in the Range .........................................................81
3.1.7 Loops That Count Down ......................................................................82
3.1 Exercises..................................................................................................................83
3.2 Formatting Text for Output ...................................................................................83
3.2 Exercises..................................................................................................................86
3.3 Case Study: An Investment Report........................................................................87
3.3.1 Request ...................................................................................................87
3.3.2 Analysis ...................................................................................................87
3.3.3 Design.....................................................................................................88
3.3.4 Implementation (Coding) ......................................................................88
3.3.5 Testing ....................................................................................................90
3.4 Selection: if and if-else Statements ...............................................................91
3.4.1 The Boolean Type, Comparisons, and Boolean Expressions ...............91
3.4.2 if-else Statements .............................................................................92

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
3.4.3 One-Way Selection Statements.............................................................94
3.4.4 Multi-way if Statements ......................................................................95
3.4.5 Logical Operators and Compound Boolean Expressions.....................97
3.4.6 Short-Circuit Evaluation .......................................................................99
3.4.7 Testing Selection Statements ...............................................................100
3.4 Exercises................................................................................................................101
3.5 Conditional Iteration: The while Loop ............................................................102
3.5.1 The Structure and Behavior of a while Loop ..................................102
3.5.2 Count Control with a while Loop....................................................104
3.5.3 The while True Loop and the break Statement ..........................105
3.5.4 Random Numbers................................................................................107
3.5.5 Loop Logic, Errors, and Testing .........................................................109
3.5 Exercises................................................................................................................109
3.6 Case Study: Approximating Square Roots...........................................................110
3.6.1 Request .................................................................................................110
3.6.2 Analysis .................................................................................................110
3.6.3 Design...................................................................................................110
3.6.4 Implementation (Coding) ....................................................................112
3.6.5 Testing ..................................................................................................113
Summary ...............................................................................................................113
Review Questions .................................................................................................116
Projects..................................................................................................................118

[CHAPTER] 4 STRINGS AND TEXT FILES 121


4.1 Accessing Characters and Substrings in Strings..................................................122
4.1.1 The Structure of Strings......................................................................122
4.1.2 The Subscript Operator.......................................................................123
4.1.3 Slicing for Substrings ...........................................................................124
4.1.4 Testing for a Substring with the in Operator ....................................125
4.1 Exercises................................................................................................................126
4.2 Data Encryption ...................................................................................................126
4.2 Exercises................................................................................................................129
4.3 Strings and Number Systems...............................................................................129
4.3.1 The Positional System for Representing Numbers............................130
4.3.2 Converting Binary to Decimal ............................................................131
4.3.3 Converting Decimal to Binary ............................................................132
4.3.4 Conversion Shortcuts...........................................................................133
4.3.5 Octal and Hexadecimal Numbers .......................................................134
4.3 Exercises................................................................................................................136
4.4 String Methods .....................................................................................................136
4.4 Exercises................................................................................................................140
4.5 Text Files...............................................................................................................141
4.5.1 Text Files and Their Format................................................................141
4.5.2 Writing Text to a File ..........................................................................142
4.5.3 Writing Numbers to a File ..................................................................142
4.5.4 Reading Text from a File .....................................................................143
4.5.5 Reading Numbers from a File .............................................................145
4.5.6 Accessing and Manipulating Files and Directories on Disk...............146

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
4.5 Exercises................................................................................................................148
4.6 Case Study: Text Analysis.....................................................................................148
4.6.1 Request .................................................................................................149
4.6.2 Analysis .................................................................................................149
4.6.3 Design...................................................................................................150
4.6.4 Implementation (Coding) ....................................................................151
4.6.5 Testing ..................................................................................................152
Summary ...............................................................................................................153
Review Questions .................................................................................................154
Projects..................................................................................................................156

[CHAPTER] 5 LISTS AND DICTIONARIES 159


5.1 Lists .......................................................................................................................160
5.1.1 List Literals and Basic Operators ........................................................160
5.1.2 Replacing an Element in a List ...........................................................163
5.1.3 List Methods for Inserting and Removing Elements .........................165
5.1.4 Searching a List....................................................................................167
5.1.5 Sorting a List........................................................................................168
5.1.6 Mutator Methods and the Value None ...............................................168
5.1.7 Aliasing and Side Effects......................................................................169
5.1.8 Equality: Object Identity and Structural Equivalence........................171
5.1.9 Example: Using a List to Find the Median of a Set of Numbers ......172
5.1.10 Tuples ...................................................................................................173
5.1 Exercises................................................................................................................174
5.2 Defining Simple Functions ..................................................................................175
5.2.1 The Syntax of Simple Function Definitions .......................................175
5.2.2 Parameters and Arguments..................................................................176
5.2.3 The return Statement.......................................................................177
5.2.4 Boolean Functions................................................................................177
5.2.5 Defining a main Function...................................................................178
5.2 Exercises................................................................................................................179
5.3 Case Study: Generating Sentences ......................................................................179
5.3.1 Request .................................................................................................179
5.3.2 Analysis .................................................................................................179
5.3.3 Design...................................................................................................180
5.3.4 Implementation (Coding) ....................................................................182
5.3.5 Testing ..................................................................................................183
5.4 Dictionaries...........................................................................................................183
5.4.1 Dictionary Literals ...............................................................................183
5.4.2 Adding Keys and Replacing Values .....................................................184
5.4.3 Accessing Values...................................................................................185
5.4.4 Removing Keys ....................................................................................186
5.4.5 Traversing a Dictionary .......................................................................186
5.4.6 Example: The Hexadecimal System Revisited....................................188
5.4.7 Example: Finding the Mode of a List of Values .................................189
5.4 Exercises................................................................................................................190

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
5.5 Case Study: Nondirective Psychotherapy ...........................................................191
5.5.1 Request .................................................................................................191
5.5.2 Analysis .................................................................................................191
5.5.3 Design...................................................................................................192
5.5.4 Implementation (Coding) ....................................................................193
5.5.5 Testing ..................................................................................................195
Summary ...............................................................................................................195
Review Questions .................................................................................................196
Projects..................................................................................................................198

[CHAPTER] 6 DESIGN WITH FUNCTIONS 201


6.1 Functions as Abstraction Mechanisms.................................................................202
6.1.1 Functions Eliminate Redundancy........................................................202
6.1.2 Functions Hide Complexity ................................................................203
6.1.3 Functions Support General Methods with Systematic Variations .....204
6.1.4 Functions Support the Division of Labor ...........................................205
6.1 Exercises................................................................................................................205
6.2 Problem Solving with Top-Down Design ...........................................................206
6.2.1 The Design of the Text-Analysis Program .........................................206
6.2.2 The Design of the Sentence-Generator Program ..............................207
6.2.3 The Design of the Doctor Program ...................................................209
6.2 Exercises................................................................................................................210
6.3 Design with Recursive Functions ........................................................................211
6.3.1 Defining a Recursive Function ............................................................211
6.3.2 Tracing a Recursive Function ..............................................................213
6.3.3 Using Recursive Definitions to Construct Recursive Functions .......214
6.3.4 Recursion in Sentence Structure .........................................................214
6.3.5 Infinite Recursion.................................................................................215
6.3.6 The Costs and Benefits of Recursion..................................................216
6.3 Exercises................................................................................................................218
6.4 Case Study: Gathering Information from a File System ....................................219
6.4.1 Request .................................................................................................219
6.4.2 Analysis .................................................................................................220
6.4.3 Design...................................................................................................222
6.4.4 Implementation (Coding) ....................................................................224
6.5 Managing a Program’s Namespace ......................................................................227
6.5.1 Module Variables, Parameters, and Temporary Variables ..................227
6.5.2 Scope.....................................................................................................228
6.5.3 Lifetime ................................................................................................229
6.5.4 Default (Keyword) Arguments ............................................................230
6.5 Exercises................................................................................................................232
6.6 Higher-Order Functions (Advanced Topic) ........................................................233
6.6.1 Functions as First-Class Data Objects ................................................233
6.6.2 Mapping................................................................................................234
6.6.3 Filtering ................................................................................................236
6.6.4 Reducing...............................................................................................237
6.6.5 Using lambda to Create Anonymous Functions...............................237
6.6.6 Creating Jump Tables ..........................................................................238

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
6.6 Exercises................................................................................................................239
Summary ...............................................................................................................240
Review Questions .................................................................................................242
Projects..................................................................................................................244

[CHAPTER] 7 SIMPLE GRAPHICS AND IMAGE PROCESSING 247


7.1 Simple Graphics ...................................................................................................248
7.1.1 Overview of Turtle Graphics ...............................................................248
7.1.2 Turtle Operations.................................................................................249
7.1.3 Object Instantiation and the turtle Module ...................................252
7.1.4 Drawing Two-Dimensional Shapes .....................................................254
7.1.5 Taking a Random Walk........................................................................255
7.1.6 Colors and the RGB System................................................................256
7.1.7 Example: Drawing with Random Colors ............................................257
7.1.8 Examining an Object’s Attributes ........................................................259
7.1.9 Manipulating a Turtle’s Screen ............................................................259
7.1.10 Setting up a cfg File and Running IDLE..........................................260
7.1 Exercises................................................................................................................261
7.2 Case Study: Recursive Patterns in Fractals..........................................................262
7.2.1 Request .................................................................................................263
7.2.2 Analysis .................................................................................................263
7.2.3 Design...................................................................................................264
7.2.4 Implementation (Coding) ....................................................................266
7.3 Image Processing .................................................................................................267
7.3.1 Analog and Digital Information .........................................................267
7.3.2 Sampling and Digitizing Images .........................................................268
7.3.3 Image File Formats ..............................................................................268
7.3.4 Image-Manipulation Operations .........................................................269
7.3.5 The Properties of Images ....................................................................270
7.3.6 The images Module ..........................................................................270
7.3.7 A Loop Pattern for Traversing a Grid ................................................274
7.3.8 A Word on Tuples................................................................................275
7.3.9 Converting an Image to Black and White ..........................................276
7.3.10 Converting an Image to Grayscale......................................................278
7.3.11 Copying an Image ................................................................................279
7.3.12 Blurring an Image ................................................................................280
7.3.13 Edge Detection ....................................................................................281
7.3.14 Reducing the Image Size .....................................................................282
7.3 Exercises................................................................................................................284
Summary ...............................................................................................................285
Review Questions .................................................................................................286
Projects..................................................................................................................288

[CHAPTER] 8 DESIGN WITH CLASSES 293


8.1 Getting Inside Objects and Classes .....................................................................294
8.1.1 A First Example: The Student Class................................................295
8.1.2 Docstrings ............................................................................................298
8.1.3 Method Definitions..............................................................................298

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
8.1.4 The __init__ Method and Instance Variables................................299
8.1.5 The __str__ Method........................................................................300
8.1.6 Accessors and Mutators .......................................................................300
8.1.7 The Lifetime of Objects ......................................................................301
8.1.8 Rules of Thumb for Defining a Simple Class.....................................302
8.1 Exercises................................................................................................................303
8.2 Case Study: Playing the Game of Craps .............................................................303
8.2.1 Request .................................................................................................303
8.2.2 Analysis .................................................................................................303
8.2.3 Design...................................................................................................304
8.2.4 Implementation (Coding) ....................................................................306
8.3 Data-Modeling Examples.....................................................................................309
8.3.1 Rational Numbers ................................................................................309
8.3.2 Rational Number Arithmetic and Operator Overloading..................311
8.3.3 Comparison Methods...........................................................................312
8.3.4 Equality and the __eq__ Method ......................................................314
8.3.5 Savings Accounts and Class Variables .................................................315
8.3.6 Putting the Accounts into a Bank........................................................317
8.3.7 Using pickle for Permanent Storage of Objects.............................319
8.3.8 Input of Objects and the try-except Statement............................320
8.3.9 Playing Cards .......................................................................................321
8.3 Exercises................................................................................................................325
8.4 Case Study: An ATM............................................................................................325
8.4.1 Request .................................................................................................325
8.4.2 Analysis .................................................................................................325
8.4.3 Design...................................................................................................327
8.4.4 Implementation (Coding) ....................................................................329
8.5 Structuring Classes with Inheritance and Polymorphism...................................331
8.5.1 Inheritance Hierarchies and Modeling ...............................................332
8.5.2 Example: A Restricted Savings Account..............................................333
8.5.3 Example: The Dealer and a Player in the Game of Blackjack ...........335
8.5.4 Polymorphic Methods..........................................................................340
8.5.5 Abstract Classes ...................................................................................340
8.5.6 The Costs and Benefits of Object-Oriented Programming...............341
8.5 Exercises................................................................................................................343
Summary ...............................................................................................................343
Review Questions .................................................................................................345
Projects..................................................................................................................346

[CHAPTER] 9 GRAPHICAL USER INTERFACES 349


9.1 The Behavior of Terminal-Based Programs and GUI-Based Programs............350
9.1.1 The Terminal-Based Version ...............................................................350
9.1.2 The GUI-Based Version......................................................................351
9.1.3 Event-Driven Programming................................................................353
9.1 Exercises................................................................................................................355
9.2 Coding Simple GUI-Based Programs .................................................................355
9.2.1 Windows and Labels............................................................................356
9.2.2 Displaying Images ................................................................................357
9.2.3 Command Buttons and Responding to Events...................................358
9.2.4 Viewing the Images of Playing Cards .................................................360

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
9.2.5 Entry Fields for the Input and Output of Text ...................................363
9.2.6 Using Pop-up Dialog Boxes ................................................................365
9.2 Exercises................................................................................................................366
9.3 Case Study: A GUI-Based ATM..........................................................................367
9.3.1 Request .................................................................................................367
9.3.2 Analysis .................................................................................................367
9.3.3 Design...................................................................................................368
9.3.4 Implementation (Coding) ....................................................................369
9.4 Other Useful GUI Resources ..............................................................................372
9.4.1 Colors ...................................................................................................373
9.4.2 Text Attributes......................................................................................373
9.4.3 Sizing and Justifying an Entry .............................................................374
9.4.4 Sizing the Main Window.....................................................................375
9.4.5 Grid Attributes .....................................................................................376
9.4.6 Using Nested Frames to Organize Components................................380
9.4.7 Multi-Line Text Widgets .....................................................................381
9.4.8 Scrolling List Boxes .............................................................................384
9.4.9 Mouse Events .......................................................................................387
9.4.10 Keyboard Events ..................................................................................388
9.4 Exercises................................................................................................................389
Summary ...............................................................................................................390
Review Questions .................................................................................................391
Projects..................................................................................................................392

[CHAPTER] 10 MULTITHREADING, NETWORKS, AND CLIENT/SERVER


PROGRAMMING 395
10.1 Threads and Processes .........................................................................................396
10.1.1 Threads.................................................................................................397
10.1.2 Sleeping Threads..................................................................................400
10.1.3 Producer, Consumer, and Synchronization ........................................402
10.1 Exercises................................................................................................................409
10.2 Networks, Clients, and Servers............................................................................409
10.2.1 IP Addresses .........................................................................................409
10.2.2 Ports, Servers, and Clients...................................................................411
10.2.3 Sockets and a Day/Time Client Script................................................412
10.2.4 A Day/Time Server Script ...................................................................414
10.2.5 A Two-Way Chat Script.......................................................................416
10.2.6 Handling Multiple Clients Concurrently ...........................................418
10.2.7 Setting Up Conversations for Others .................................................420
10.2 Exercises................................................................................................................422
10.3 Case Study: A Multi-Client Chat Room .............................................................423
10.3.1 Request ................................................................................................423
10.3.2 Analysis ................................................................................................423
10.3.3 Design...................................................................................................424
10.3.4 Implementation (Coding) ....................................................................425
Summary ...............................................................................................................427
Review Questions .................................................................................................428
Projects..................................................................................................................430

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
[ONLINE CHAPTER] 11 SEARCHING, SORTING, AND COMPLEXITY ANALYSIS

11.1 Measuring the Efficiency of Algorithms


11.1.1 Measuring the Run Time of an Algorithm
11.1.2 Counting Instructions
11.1.3 Measuring the Memory Used by an Algorithm
11.1 Exercises
11.2 Complexity Analysis
11.2.1 Orders of Complexity
11.2.2 Big-O Notation
11.2.3 The Role of the Constant of Proportionality
11.2 Exercises
11.3 Search Algorithms
11.3.1 Search for a Minimum
11.3.2 Linear Search of a List
11.3.3 Best-Case, Worst-Case, and Average-Case Performance
11.3.4 Binary Search of a List
11.3.5 Comparing Data Items
11.3 Exercises
11.4 Sort Algorithms
11.4.1 Selection Sort
11.4.2 Bubble Sort
11.4.3 Insertion Sort
11.4.4 Best-Case, Worst-Case, and Average-Case Performance Revisited
11.4 Exercises
11.5 An Exponential Algorithm: Recursive Fibonacci
11.6 Converting Fibonacci to a Linear Algorithm
11.7 Case Study: An Algorithm Profiler
11.7.1 Request
11.7.2 Analysis
11.7.3 Design
11.7.4 Implementation (Coding)
Summary
Review Questions
Projects

[APPENDIX] A PYTHON RESOURCES 433


A.1 Installing Python on Your Computer ..................................................................434
A.2 Using the Terminal Command Prompt, IDLE, and Other IDEs......................434

[APPENDIX] B INSTALLING THE images LIBRARY 437


[APPENDIX] C API FOR IMAGE PROCESSING 439
[APPENDIX] D TRANSITION FROM PYTHON TO JAVA AND C++ 441
GLOSSARY 443
INDEX 455
Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
PREFACE
Welcome to Fundamentals of Python: First Programs. This text is intended for a
course in programming and problem-solving. It covers the material taught in a
typical Computer Science 1 course (CS1) at the undergraduate level.
This book covers five major aspects of computing:
1 Programming Basics—Data types, control structures, algorithm devel-
opment, and program design with functions are basic ideas that you need
to master in order to solve problems with computers. This book exam-
ines these core topics in detail and gives you practice employing your
understanding of them to solve a wide range of problems.
2 Object-Oriented Programming (OOP)—Object-Oriented
Programming is the dominant programming paradigm used to develop
large software systems. This book introduces you to the fundamental
principles of OOP and enables you to apply them successfully.
3 Data and Information Processing—Most useful programs rely on data
structures to solve problems. These data structures include strings,
arrays, files, lists, and dictionaries. This book introduces you to these
commonly used data structures, with examples that illustrate criteria for
selecting the appropriate data structures for given problems.
4 Software Development Life Cycle—Rather than isolate software
development techniques in one or two chapters, this book deals with
them throughout in the context of numerous case studies. Among other
things, you’ll learn that coding a program is often not the most difficult
or challenging aspect of problem solving and software development.
5 Contemporary Applications of Computing—The best way to learn
about programming and problem solving is to create interesting programs
with real-world applications. In this book, you’ll begin by creating applica-
tions that involve numerical problems and text processing. For example,
you’ll learn the basics of encryption techniques such as those that are used
to make your credit card number and other information secure on the
Internet. But unlike many other introductory texts, this one does not
restrict itself to problems involving numbers and text. Most contemporary
applications involve graphical user interfaces, event-driven programming,
graphics, and network communications. These topics are presented in
optional, standalone chapters.

PREFACE [ xiii ]

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Why Python?
Computer technology and applications have become increasingly more sophisti-
cated over the past two decades, and so has the computer science curriculum, espe-
cially at the introductory level. Today’s students learn a bit of programming and
problem–solving, and are then expected to move quickly into topics like software
development, complexity analysis, and data structures that, twenty years ago, were
relegated to advanced courses. In addition, the ascent of object-oriented program-
ming as the dominant paradigm of problem solving has led instructors and text-
book authors to bring powerful, industrial-strength programming languages such as
C++ and Java into the introductory curriculum. As a result, instead of experiencing
the rewards and excitement of solving problems with computers, beginning com-
puter science students often become overwhelmed by the combined tasks of mas-
tering advanced concepts as well as the syntax of a programming language.
This book uses the Python programming language as a way of making the
first year of computer science more manageable and attractive for students and
instructors alike. Python has the following pedagogical benefits:
 Python has simple, conventional syntax. Python statements are very close to

those of pseudocode algorithms, and Python expressions use the conven-


tional notation found in algebra. Thus, students can spend less time learn-
ing the syntax of a programming language and more time learning to solve
interesting problems.
 Python has safe semantics. Any expression or statement whose meaning

violates the definition of the language produces an error message.


 Python scales well. It is very easy for beginners to write simple programs in

Python. Python also includes all of the advanced features of a modern pro-
gramming language, such as support for data structures and object-oriented
software development, for use when they become necessary.
 Python is highly interactive. Expressions and statements can be entered at

an interpreter’s prompts to allow the programmer to try out experimental


code and receive immediate feedback. Longer code segments can then be
composed and saved in script files to be loaded and run as modules or
standalone applications.
 Python is general purpose. In today’s context, this means that the language

includes resources for contemporary applications, including media comput-


ing and networks.
 Python is free and is in widespread use in industry. Students can download

Python to run on a variety of devices. There is a large Python user com-


munity, and expertise in Python programming has great resume value.

[ xiv ] PREFACE

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
To summarize these benefits, Python is a comfortable and flexible vehicle for
expressing ideas about computation, both for beginners and for experts as well. If
students learn these ideas well in the first course, they should have no problems
making a quick transition to other languages needed for courses later in the cur-
riculum. Most importantly, beginning students will spend less time staring at a
computer screen and more time thinking about interesting problems to solve.

Organization of the Book


The approach of this text is easygoing, with each new concept introduced only
when it is needed.
Chapter 1 introduces computer science by focusing on two fundamental
ideas, algorithms and information processing. A brief overview of computer hard-
ware and software, followed by an extended discussion of the history of comput-
ing, sets the context for computational problem solving.
Chapters 2 and 3 cover the basics of problem solving and algorithm develop-
ment using the standard control structures of expression evaluation, sequencing,
Boolean logic, selection, and iteration with the basic numeric data types.
Emphasis in these chapters is on problem solving that is both systematic and
experimental, involving algorithm design, testing, and documentation.
Chapters 4 and 5 introduce the use of the strings, text files, lists, and diction-
aries. These data structures are both remarkably easy to manipulate in Python
and support some interesting applications. Chapter 5 also introduces simple func-
tion definitions as a way of organizing algorithmic code.
Chapter 6 explores the technique and benefits of procedural abstraction with
function definitions. Top-down design, stepwise refinement, and recursive design
with functions are examined as means of structuring code to solve complex prob-
lems. Details of namespace organization (parameters, temporary variables, and
module variables) and communication among software components are discussed.
An optional section on functional programming with higher-order functions
shows how to exploit functional design patterns to simplify solutions.
Chapter 7 focuses on the use of existing objects and classes to compose pro-
grams. Special attention is paid to the interface, or set of methods, of a class of
objects and the manner in which objects cooperate to solve problems. This chapter
also introduces two contemporary applications of computing, graphics and image
processing—areas in which object-based programming is particularly useful.

PREFACE [ xv ]

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Chapter 8 introduces object-oriented design with class and method defini-
tions. Several examples of simple class definitions from different application
domains are presented. Some of these are then integrated into more realistic
applications, to show how object-oriented software components can be used to
build complex systems. Emphasis is on designing appropriate interfaces for
classes that exploit inheritance and polymorphism.
Chapters 9 and 10 cover advanced material related to two important areas of
computing: graphical user interfaces and networks. Although these two chapters
are entirely optional, they give students challenging experiences at the end of the
first course. Chapter 9 contrasts the event-driven model of GUI programs with
the process-driven model of terminal-based programs. The creation and layout of
GUI components are explored, as well as the decomposition of a GUI-based pro-
gram using the model/view/controller pattern. Chapter 10 introduces multi-
threaded programs and the construction of simple network-based client/server
applications.
Chapter 11 covers some topics addressed at the beginning of a traditional
CS2 course, and is available on the publisher’s Web site. This chapter introduces
complexity analysis with big-O notation. Enough material is presented to enable
you to perform simple analyses of the running time and memory usage of algo-
rithms and data structures, using search and sort algorithms as examples.

Special Features
This book explains and develops concepts carefully, using frequent examples and
diagrams. New concepts are then applied in complete programs to show how
they aid in solving problems. The chapters place an early and consistent emphasis
on good writing habits and neat, readable documentation.
The book includes several other important features:
 Case studies—These present complete Python programs ranging from the

simple to the substantial. To emphasize the importance and usefulness of


the software development life cycle, case studies are discussed in the frame-
work of a user request, followed by analysis, design, implementation, and
suggestions for testing, with well-defined tasks performed at each stage.
Some case studies are extended in end-of-chapter programming projects.
 Chapter objectives and chapter summaries—Each chapter begins with a set

of learning objectives and ends with a summary of the major concepts cov-
ered in the chapter.
 Key terms and a glossary—When a technical term is introduced in the text,

it appears in boldface. Definitions of the key terms are also collected in a


glossary.

[ xvi ] PREFACE

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
 Exercises—Most major sections of each chapter end with exercise ques-
tions that reinforce the reading by asking basic questions about the mate-
rial in the section. Each chapter ends with a set of review exercises.
 Programming projects—Each chapter ends with a set of programming
projects of varying difficulty.
 A software toolkit for image processing—This book comes with an open-
source Python toolkit for the easy image processing discussed in Chapter 7.
The toolkit can be obtained from the student downloads page on
www.course.com, or at http://home.wlu.edu/~lambertk/python/
 Appendices—Three appendices include information on obtaining Python
resources, installing the toolkit, and using the toolkit’s interface.

Supplemental Resources
The following supplemental materials are available when this book is used in a
classroom setting. All of the teaching tools available with this book are provided
to the instructor on a single CD-ROM.

Electronic Instructor’s Manual


The Instructor’s Manual that accompanies this textbook includes:
 Additional instructional material to assist in class preparation, including

suggestions for lecture topics.


 Solutions to all the end-of-chapter materials, including the Programming

Exercises.

ExamView®
This textbook is accompanied by ExamView, a powerful testing software package
that allows instructors to create and administer printed, computer (LAN-based),
and Internet exams. ExamView includes hundreds of questions that correspond to
the topics covered in this text, enabling students to generate detailed study guides
that include page references for further review. These computer-based and
Internet testing components allow students to take exams at their computers, and
save the instructor time because each exam is graded automatically.

PowerPoint Presentations
This book comes with Microsoft PowerPoint slides for each chapter. These are
included as a teaching aid either to make available to students on the network for
chapter review, or to be used during classroom presentations. Instructors can
modify slides or add their own slides to tailor their presentations.

PREFACE [ xvii ]

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Distance Learning
Course Technology is proud to offer online courses in WebCT and Blackboard.
For more information on how to bring distance learning to your course, contact
your local Cengage Learning sales representative.

Source Code
The source code is available at www.cengagebrain.com—and also is available on the
Instructor Resources CD-ROM. If an input file is needed to run a program, it is
included with the source code.

Solution files
The solution files for all programming exercises are available at www.cengagebrain.com
and are available on the Instructor Resources CD-ROM. If an input file is needed to
run a programming exercise, it is included with the solution file.

We Appreciate Your Feedback


We have tried to produce a high-quality text, but should you encounter any
errors, please report them to lambertk@wlu.edu or computerscience@cengage.com. A
list of errata, should they be found, as well as other information about the book,
will be posted on the Web site http://home.wlu.edu/~lambertk/python/ and with the
student resources at www.cengagebrain.com.

Acknowledgments
I would like to thank my contributing author, Martin Osborne, for many years of
advice, friendly criticism, and encouragement on several of my book projects. To
my colleague, Joshua Stough, and our students at Washington and Lee University for
classroom testing this book over several semesters.
In addition, I would like to thank the following reviewers for the time and
effort they contributed to Fundamentals of Python: Paul Albee, Central Michigan
University; Andrew Danner, Swarthmore College; Susan Fox, Macalester
College; Robert Franks, Central College; and Jim Slack, Minnesota State
University, Mankato. Also, thank you to the following reviewers who contributed
their thoughts on the original book proposal: Christian Blouin, Dalhousie
University; Margaret Iwobi, Binghamton University; Sam Midkiff, Purdue
University; and Ray Morehead, West Virginia University.

[ xviii ] PREFACE

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Also, thank you to the individuals at Course Technology who helped to assure
that the content of all data and solution files used for this text were correct and
accurate: Chris Scriver, MQA Project Leader and Serge Palladino, MQA Tester.
Finally, thanks to several other people whose work made this book possible:
Ann Shaffer, Developmental Editor; Brandi Shailer, Acquisitions Editor, Course
Technology; Alyssa Pratt, Senior Product Manager, Course Technology; and
Jennifer Feltri, Content Project Manager, Course Technology.

Dedication
To my students in Computer Science 111
Kenneth A. Lambert
Lexington, VA

PREFACE [ xix ]

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
[CHAPTER]
1 Introduction
After completing this chapter, you will be able to
 Describe the basic features of an algorithm
 Explain how hardware and software collaborate in a com-
puter’s architecture
 Give a brief history of computing
Compose and run a simple Python program


As a reader of this book, you almost certainly have played a


video game and listened to music on a CD player. It’s likely that you
have watched a movie on a DVD player and prepared a snack in a
microwave oven. Chances are that you have made at least one phone
call to or from a cell phone. You and your friends have most likely
used a desktop computer or a laptop computer, not to mention digi-
tal cameras and handheld music and video players.
All of these devices have something in common: they are or
contain computers. Computer technology makes them what they
are. Devices that rely on computer technology are almost every-
where, not only in our homes, but also in our schools, where we
work, and where we play. Computer technology plays an important
role in entertainment, education, medicine, manufacturing, commu-
nications, government, and commerce. It has been said that we have
digital lifestyles and that we live in an information age with an infor-
mation-based economy. Some people even claim that nature itself
performs computations on information structures present in DNA
and in the relationships among subatomic particles.
It’s difficult to imagine our world without computers, although
we don’t think about the actual computers very much. It’s also hard
to imagine that the human race did without computer technology

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
for thousands of years, and that the world as we know it has been so involved in
and with computer technology for only the past 25 years or so.
In the chapters that follow, you will learn about computer science, which is
the study of computation that has made this new technology and this new world
possible. You will also learn how to use computers effectively and appropriately to
enhance your own life and the lives of others.

1.1 Two Fundamental Ideas of Computer


Science: Algorithms and Information
Processing
Like most areas of study, computer science focuses on a broad set of interrelated
ideas. Two of the most basic ones are algorithms and information processing.
In this section, these ideas are introduced in an informal way. We will examine
them in more detail in later chapters.

1.1.1 Algorithms
People computed long before the invention of modern computing devices, and
many continue to use computing devices that we might consider primitive. For
example, consider how merchants made change for customers in marketplaces
before the existence of credit cards, pocket calculators, or cash registers. Making
change can be a complex activity. It probably took you some time to learn how to
do it, and it takes some mental effort to get it right every time. Let’s consider
what’s involved in this process.
The first step is to compute the difference between the purchase price and
the amount of money that the customer gives the merchant. The result of this
calculation is the total amount that the merchant must return to the purchaser.
For example, if you buy a dozen eggs at the farmers’ market for $2.39 and you
give the farmer a $10 bill, she should return $7.61 to you. To produce this
amount, the merchant selects the appropriate coins and bills that, when added to
$2.39, make $10.00.
Few people can subtract three-digit numbers without resorting to some man-
ual aids, such as pencil and paper. As you learned in grade school, you can carry
out subtraction with pencil and paper by following a sequence of well-defined
steps. You have probably done this many times but never made a list of the

[2] CHAPTER 1 Introduction

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
specific steps involved. Making such lists to solve problems is something com-
puter scientists do all the time. For example, the following list of steps describes
the process of subtracting two numbers using a pencil and paper:
Step 1 Write down the two numbers, with the larger number above the
smaller number and their digits aligned in columns from the right.
Step 2 Assume that you will start with the rightmost column of digits and
work your way left through the various columns.
Step 3 Write down the difference between the two digits in the current
column of digits, borrowing a 1 from the top number’s next column
to the left if necessary.
Step 4 If there is no next column to the left, stop. Otherwise, move to the
next column to the left, and go to Step 3.
If the computing agent (in this case a human being) follows each of these
simple steps correctly, the entire process results in a correct solution to the given
problem. We assume in Step 3 that the agent already knows how to compute the
difference between the two digits in any given column, borrowing if necessary.
To make change, most people can select the combination of coins and bills
that represent the correct change amount without any manual aids, other than
the coins and bills. But the mental calculations involved can still be described in a
manner similar to the preceding steps, and we can resort to writing them down
on paper if there is a dispute about the correctness of the change.
The sequence of steps that describes each of these computational processes is
called an algorithm. Informally, an algorithm is like a recipe. It provides a set of
instructions that tells us how to do something, such as make change, bake bread,
or put together a piece of furniture. More precisely, an algorithm describes a
process that ends with a solution to a problem. The algorithm is also one of the
fundamental ideas of computer science. An algorithm has the following features:
1 An algorithm consists of a finite number of instructions.
2 Each individual instruction in an algorithm is well defined. This means that
the action described by the instruction can be performed effectively or be
executed by a computing agent. For example, any computing agent capa-
ble of arithmetic can compute the difference between two digits. So an
algorithmic step that says “compute the difference between two digits”
would be well defined. On the other hand, a step that says “divide a number
by 0” is not well defined, because no computing agent could carry it out.

1.1 Two Fundamental Ideas of Computer Science: Algorithms and Information Processing [3]

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
3 An algorithm describes a process that eventually halts after arriving at a
solution to a problem. For example, the process of subtraction halts after
the computing agent writes down the difference between the two digits
in the leftmost column of digits.
4 An algorithm solves a general class of problems. For example, an algo-
rithm that describes how to make change should work for any two
amounts of money whose difference is greater than or equal to $0.00.
Creating a list of steps that describe how to make change might not seem like
a major accomplishment to you. But the ability to break a task down into its com-
ponent parts is one of the main jobs of a computer programmer. Once we write
an algorithm to describe a particular type of computation, a machine can be built
to do the computing. Put another way, if we can develop an algorithm to solve a
problem, we can automate the task of solving the problem. You might not feel
compelled to write a computer program to automate the task of making change,
because you can probably already make change yourself fairly easily. But suppose
you needed to do a more complicated task—such as sorting a list of 100 names.
In that case, a computer program would be very handy.
Computers can be designed to run a small set of algorithms for performing
specialized tasks such as operating a microwave oven. But we can also build com-
puters, like the one on your desktop, that are capable of performing a task
described by any algorithm. These computers are truly general-purpose problem-
solving machines. They are unlike any machines we have ever built before, and
they have formed the basis of the completely new world in which we live.
Later in this book, we introduce a notation for expressing algorithms and
some suggestions for designing algorithms. You will see that algorithms and algo-
rithmic thinking are critical underpinnings of any computer system.

1.1.2 Information Processing


Since human beings first learned to write several thousand years ago, they have
processed information. Information itself has taken many forms in its history, from
the marks impressed on clay tablets in ancient Mesopotamia, to the first written
texts in ancient Greece, to the printed words in the books, newspapers, and maga-
zines mass-produced since the European Renaissance, to the abstract symbols of
modern mathematics and science used during the past 350 years. Only recently,
however, have human beings developed the capacity to automate the processing of
information by building computers. In the modern world of computers, informa-
tion is also commonly referred to as data. But what is information?

[4] CHAPTER 1 Introduction

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Like mathematical calculations, information processing can be described with
algorithms. In our earlier example of making change, the subtraction steps
involved manipulating symbols used to represent numbers and money. In carry-
ing out the instructions of any algorithm, a computing agent manipulates infor-
mation. The computing agent starts with some given information (known as
input), transforms this information according to well-defined rules, and produces
new information, known as output.
It is important to recognize that the algorithms that describe information
processing can also be represented as information. Computer scientists have been
able to represent algorithms in a form that can be executed effectively and effi-
ciently by machines. They have also designed real machines, called electronic
digital computers, which are capable of executing algorithms.
Computer scientists more recently discovered how to represent many other
things, such as images, music, human speech, and video, as information. Many of
the media and communication devices that we now take for granted would be
impossible without this new kind of information processing. We examine many of
these achievements in more detail in later chapters.

1.1 Exercises
These short end-of-section exercises are intended to stimulate your thinking
about computing.
1 List three common types of computing agents.
2 Write an algorithm that describes the second part of the process of mak-
ing change (counting out the coins and bills).
3 Write an algorithm that describes a common task, such as baking a cake
or operating a DVD player.
4 Describe an instruction that is not well defined and thus could not be
included as a step in an algorithm. Give an example of such an instruction.
5 In what sense is a desktop computer a general-purpose problem-solving
machine?
6 List four devices that use computers and describe the information that
they process. (Hint: Think of the inputs and outputs of the devices.)

1.1 Two Fundamental Ideas of Computer Science: Algorithms and Information Processing [5]

Copyright 2011 Cengage Learning. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part. Due to electronic rights, some third party content may be suppressed from the eBook and/or eChapter(s).
Editorial review has deemed that any suppressed content does not materially affect the overall learning experience. Cengage Learning reserves the right to remove additional content at any time if subsequent rights restrictions require it.
Other documents randomly have
different content
THE TWO WAYS

The ways diverged—I wondered which I’d take,


And as I paused, I watched the people throng
Out of the Somewhere, each with hurrying feet,—
To right, to left, they hastened all day long!
They bore a heavy burden as they passed,
(With every single one it was the same),
And each was plainly marked, so all could read
(I marvelled greatly at the fact), “My Aim.”
And those who took the beaten path, I saw
Soon laid their burden down and gazed around.
Allured by vain enticements all about,
They left their “Aim” forgotten on the ground!
But those who took the other way pressed on,
Nor feared for pleasure’s sake their “Aim” to lose,—
I now perceived this path was Duty, so
No longer pondered which I ought to choose.
A WISE WAITING

A blushing little Mayflower


Turned away her head,
Too polite to let a weed
Hear a word she said.

“I don’t think it nice at all,


(I would make a fuss),
Goldenrod should bloom, of course,
In the spring with us!

“It is hard to wait so long,


Till midsummer hours;
I should get discouraged, quite,
Waiting so for flowers.”

Near the wall a modest plant


Twinkled in the dew;
She heard all that had been said,—
Mayflower never knew.

Soon she whispered to a robin;


He her secret told,—
“All this waiting means a changing
Into sunny gold!”
THE VISITANT

In middle age, before the hearth,


Deeply absorbed in counting o’er
Successes won, he hardly heard
The fall of footsteps on the floor.

Behind his chair a fair Youth stood,


In phantom shape, and listening heard:
“I’m happier now than when a boy!”—
The visitant neither turned nor stirred.

Tenderly sad, Lost Youth mused low,


“He’s gained at length Fortune’s bequest,—
When I slipped slowly from his grasp,
He cried, ‘My Boyhood days are best!’
But, no—though learned ’mid falling tears,—
One’s best days come with Manhood’s years!”
WORK AND WORRY

Discouraged and sad, Work came home, worn out,


(Only a part of his task was done),
And the Master asked in an anxious tone,
If he had been hindered by any one.
“A stranger stood by as I toiled,” he said,
“A being possessed of gigantic frame!”
“He’s stolen your strength,” the Master cried,
“And Worry—too true—is the monster’s name!”
THE PRIZE WINNER

“The world owes me a living,” p’r’aps you’ve heard a body say,


“It is best to take life easy—’tis, in fact, the only way.”
So with loiterers and sluggards he in base contentment lies,
While the man who works and struggles is the one who wins the
prize.

Some grope always in the valley—really can they ever stop


To consider what enchantment hovers round the mountain top?
But the man who clambers upward, step by step the weary rise,
Obtains vistas only dreamed of—he’s the one who wins the prize!

Some wait ever for the morrow—let the present hours slip by:
“So little can be done to-day, what’s the use to try?”
Notice, he who grasps the moments, lad, every one that flies,
Is the man in life’s sharp contest who obtains the victor’s prize.
TO-DAY AND TO-
MORROW

TO-DAY

A sunless sky,
Unaccomplished aim,
The flag of Hope at half mast furled,—
A bitter cry,
“I’ve tried—no gain,—
O empty, disappointing world!”

TO-MORROW

A rosy light,
Success attained,
The banner of Victory to the breezes hurled,—
A cry of might,
“The mastery gained,
Hail! glorious, God-given world!”
A BEAUTIFUL RESULT

A beautiful smile in His service,


A beautiful word of cheer,
A beautiful act unselfish,
A beautiful hint, “He’ll hear.”
A beautiful tear sympathetic,
A beautiful allaying of strife,
A beautiful touch of a brother,—
The result is a beautiful life.
THE CRIPPLED HERO
(A Cuban Incident)

Pedro Rionda and his sons,


Leandro and Ramé,
Had left th’ insurgent army
For a visit home that day.

And ere the time came to depart,


To join their ranks once more,
José, the little crippled son,
Chanced to glance out the door.

His pinched face suddenly grew white,—


Yet calm he turned about;
“Father, Leandro, Ramé—quick!
The Spanish are without!”

Pedro Rionda’s heart stood still,


He grasped his trusty gun,—
A Spanish army couldn’t make
A Cuban patriot run!

His breath came quick—he thought aloud,


“If we should face the band,
They are too many—there’d be three,—
Three less to save the land!”
“Oh, God! it is the only thing!
It’s one or three—José!

Think you could keep the devils back


Till we are safe away!”

“It may be death,” he spoke it soft,


“When they don’t find us here,—
Our country needs her able men;
Speak, José, have you fear?”

“No; father, no—quick, brothers, go!


It’s all I have to give,—
It matters not if I am shot,—
Our country—it must live!”

One long embrace—and they are off!


Bang! bang! ’twas José’s gun,—
The Spanish balls came whizzing fast,—
He met them, one by one.

And when his ammunition’s spent,


The three are safe away,—
The Spaniards, crazed at their repulse,
Rush in on brave José!

“Where, where,—and are the rebels fled,


Are they escaped through you?”
They madly grasped the crippled boy,
While flashing swords they drew.

All honor be to Cuba’s sons


(But let this not suffice)
Who perished on the field—there’s, too,
The cripple’s sacrifice!
MR. BUSHEL’S
HOSPITALITY

Four brothers by the name of Peck,


(All Mr. Bushel’s kin),
As often as one desires it,
Are taken by him in.

Eight sisters, the Misses Gallon,


When the four Peck brothers are out,
In Mr. Bushel’s quarters
Have room to move about.

Thirty-two cousins, the Quarts—ah, me!


What will Mr. Bushel do?
Polite and open, he smiles and says,
“I’m alone, so there’s room for you!”

A jingling crowd—the sixty-four Pints,


To shelter them, no fun!
Mr. Bushel laughs, “I’m empty now,
Walk in, come, every one!”

Two hundred and fifty-six baby Gills,


The tiniest friends and shy,—
“Can we all come in?” Mr. Bushel replies,
“I can hold you and not half try!”
A jolly good fellow to entertain all,
This Mr. Bushel must be!
He takes them only one group at a time,—
And each group makes him, you see!
THE WISH-MAN

A funny little Wish-Man came out of the Somewhere here,


(You really should have seen him, he looked so wondrous queer);
He had a pack upon his back, stuffed full as full could be,
Of wishes for the boys and girls—those living near to me.
He said he’d indirectly heard—he couldn’t tell just where,—
That in the town of Discontent were many dwelling there,
Who wished for this and wished for that (it really was too bad),
It made but little difference what, long’s ’t wasn’t what they had!

Accordingly, he stuffed his pack (and tied around a band),


With every single kind of wish now found within the land,
And fared he forth from house to house, to please the people all,
And dealt out every kind of wish for which he had a call.
To one ’twas wealth—a sordid wish; another called for joy;
One asked for ease; one beauty took—a worthless sort of toy!
And so he gave them this and that, and all seemed happy quite,
For which the Wish-Man naturally took very keen delight.

But when a stranger passed the town of Discontent, he saw


(’Twas just a short time after this) what filled him quite with awe;
No merry whistle, smile nor laugh could be perceived at all,—
What dire disaster could have brought upon the town this pall!
He called upon a wealthy youth, who said, “I’m all at sea,—
What stocks to buy, how to invest—it almost crazes me!
Before a rich man I became, I had all sorts of fun,
But since my wish, a moment’s joy I haven’t had, not one!”

And thus ’twas so all through the town. Each testified the same;
Not one was half so happy as before the Wish-Man came.
“Ah, ha!” Perhaps by this you’ve guessed who was the stranger man;
If not, by throwing out this hint, I’m very sure you can!
That night, when everything was still, there crept from room to
room,
Some one who gathered up each wish that caused such direful
gloom,
And when old Sol arose next day, and scattered sunbeams down,
They fell upon—the name was changed—upon Contented Town!
A LITTLE
MATHEMATICIAN

“Eight long furlongs I’ve gone to-day!”


With evident pride said Ethel May.

“Three hundred and twenty rods, you know,


Is what I’ve been,”—’twas brother Joe.

“One thousand, seven hundred and sixty—true!


So many yards I’ve walked,” said Prue.

“Five thousand, two hundred and eighty feet


I’ve gone,” said Ben, “and it can’t be beat!”

“Pooh!” laughed Ted, with a knowing smile,


“You’ve only gone, each one, a mile!”
THE CASTLE OF MY
DREAMS

The castle I love is not set on a hill,


No flag from its turret waves,
No water flows in its outer moat,
Nor its rock foundation laves.
My castle is old and its doors flap loose,
As though wringing in grief its hands,—
Out by the wall, near the cherry trees,
The barn of my childhood stands!

Empty the mows where from robbers fierce,


We hid in the days gone by,
Vacant the stall where Old Dolly stood,
And watched as we played “I-spy!”
Down in the bay only cobwebs now,—
To my child eyes once so deep,
Where secure from escape our prisoners found
Themselves in that dungeon-keep!

Sometimes on the clean-swept floor we spread


Our feasts (’twas baronial hall)
Of meats and wines from far over the seas,—
Bread and water composed them all!
But never did lord or lady show
Disrespect to the loyal host,
By a look that the board did not heavily groan
With all dainties the world could boast.
A heartless echo now only sounds
From rafter back to sill,
When I call as I did—was it yesterday?—
To Rachel and Tom and Will.
It seems that each beam sadly sighs with me
For the days we were wont to play,
Safe from temptation (you guarded us well,
Old barn,) on the new-mown hay!
THE PASTURE BARS

Down the lane to the pasture bars!


My prodigal thoughts once more
Go back to my father’s calling me
From the narrow back stairway door:
“It’s getting late, Bob; the milking’s done!”
(He never had more to say);
With a bound to the floor I hurriedly dressed,
To drive the cows away!

A nodded “Good morning” from wayside flower;


From every tree a song,
(A symphony rare of warbled joy),
As the cows slowly browsed along!
The sun gently kissed the mist away,
That over the valley hung,
While odors of incense floated high,
From an unseen censer swung.

Then, too, when the work in the field was o’er,


While heavier chores were done
By older men, I trudged along,
In the path of the setting sun,
Calling, “Co’ bos! co’ bos! co’ bos!”
And often the baby stars
Played hide-and-seek from behind a cloud,
Ere I left the pasture bars.

No more do I hear in the city’s din,


(And never shall I again),
The country sounds in the early morn,
As I trudged a-down the lane;
But I hope as I near the sunset hour,
No sorrow my pathway mars,
Greater than that when I called “Co’ bos!”
As a boy by the pasture bars!
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebookname.com

You might also like