Starting Out With Python: Global Edition Global Edition
Starting Out With Python: Global Edition Global Edition
Starting Out With Python: Global Edition Global Edition
EDITION EDITION
RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO
THIS INFORMATION, INCLUDING ALL WARRANTIES AND CONDITIONS OF MERCHANTABILITY,
Digital Resources for Students WHETHER EXPRESS, IMPLIED OR STATUTORY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
Your new textbook provides 12-month access to digital resources that may include WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
VideoNotes (step-by-step video tutorials on programming concepts), source code, web
WITH THE USE OR PERFORMANCE OF INFORMATION AVAILABLE FROM THE SERVICES. THE
chapters, quizzes, and more. Refer to the preface in the textbook for a detailed list of DOCUMENTS AND RELATED GRAPHICS CONTAINED HEREIN COULD INCLUDE TECHNICAL
resources. INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO
THE INFORMATION HEREIN. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS MAY MAKE
Follow the instructions below to register for the Companion Website for Tony Gaddis’ IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED
Starting Out with Python, Fourth Edition, Global Edition. HEREIN AT ANY TIME. PARTIAL SCREEN SHOTS MAY BE VIEWED IN FULL WITHIN THE SOFTWARE
VERSION SPECIFIED.
1. Go to www.pearsonglobaleditions.com/gaddis
2. Enter the title of your textbook or browse by author name.
3. Click Companion Website.
4. Click Register and follow the on-screen instructions to create a login name
and password.
ISSGPY-PRANK-CURRY-PIQUE-METIS-ROUSE
Use the login name and password you created during registration to start using the
online resources that accompany your textbook.
IMPORTANT:
This prepaid subscription does not include access to MyProgrammingLab, which is
available at www.myprogramminglab.com for purchase.
This subscription is valid for 12 months upon activation and is not transferable.
743
742 Index
P
defined, 261 Widgets
general format, 272 arrangement of, 630
how to use, 274–276 Button, 622, 630–633
®
and IPO charts, 276–277 Canvas, 622
randint and, 263–266 Checkbutton, 622, 648–650
random number generation, 262–271 defined, 622
randrange and, 269–270 Entry, 622, 633–636
returning multiple values, 282–283 Frame, 622, 629
return statement, 272–274 with frames, organizing, 627–630
for simplifying mathematical expressions, 274–276 Label, 622, 625–626, 629, 636–640
values, 261, 274 Listbox, 622
void functions and, 233 list of, 641
F OUR TH ED ITION writing, 272–283
Values
Menu, 622
Menubutton, 622
P
str data type, 69–70 as base classes, 574
str function defined, 574
defined, 326 in UML diagrams, 582–583
®
example use, 323 writing, 575
String comparisons, 144–147, 444–445, 463, 464 Supersets, 492
String concatenation SUV class, 580–581
defined, 90, 434 Symbols, flowchart, 56
example, 90 symmetric_difference method, 491
interactive sessions, 434 Symmetric difference of sets, 491
newline to, 319–320 Syntax
with + operator, 90 defined, 40
with += operator, 435 human language, 41
F OUR TH ED ITION String literals
defined, 59
Syntax errors
correcting, 54
GLOBA L EDITION enclosing in triple quotes, 60
Strings
defined, 41
reporting, 691
characters, accessing, 430–434 running programs and, 691
comparing, 144–148 System software, 28–29
defined, 59
extracting characters from, 438–440 T
as immutable, 435–436 tan() function, 285
Tony Gaddis
indexes, 432–433 Target variables
iterating with for loop, 430–432 defined, 192
list of, 366 inside for loops, 194–196
Haywood Community College method call format, 442 use example, 195
modification methods, 444–445 Terminal symbols, 56
operations, 429–436 Testing
raw, 314 dictionary values, 463–464
reading as input, 429 programs, 54–55
repetition operator (*) with, 450–451 set values, 488–489
returning, 280 string methods, 442–443
search and replace methods, 445–446 strings, 441
slicing, 437–438 Text
space character at end, 73 drawing with Canvas widget, 667–672
splitting, 451–452 displaying with Label widget, 624–627
storing with str data type, 69–70 editing, 687–688
stripping newline from, 320–322 font setting, 670–672
testing, 441 Text files
testing methods, 442–443 defined, 311
writing as output, 429 reading numbers from, 324
written to files, 316 Text widget, 622
StringVar object, 636–637 third-party modules, 705
strip() method, 444 Tkinter module
Stripping newline from string, 320–322 defined, 621
Structure charts. See Hierarchy charts programs using, 622
Subclasses widgets, 622
defined, 574 Top-down design
as derived classes, 574 defined, 240
method override, 588 process, 240–241
�)è“ÜÊÃ�ZãØ——ã �B—ô�xÊع �Bx�
Index 739
Running programs, 690–691 set method, 640, 647 Senior Vice President Courseware Portfolio Management: Marcia J. Horton
Running totals Sets Director, Portfolio Management: Engineering,
calculating, 201–204 adding elements, 486–487 Computer Science & Global Editions: Julian Partridge
defined, 201 creating, 485
Portfolio Manager: Matt Goldstein
elements for calculating, 201 defined, 484
example, 202 difference of, 490–491
Acquisitions Editor, Global Edition: Sourabh Maheshwari
logic for calculating, 201 duplicate elements, 485 Portfolio Management Assistant: Kristy Alaura
elements, as unique, 484 Field Marketing Manager: Demetrius Hall
S elements, number of, 486 Product Marketing Manager: Yvonne Vannatta
Samples, 34 elements, removing, 487–488 Managing Producer, ECS and Math: Scott Disanno
Saving programs, 690 intersection of, 490 Content Producer: Sandra L. Rodriguez
SavingsAccount class, 584, 585 for loop iteration over, 488
Project Editors, Global Edition: Tanima Ghosh and Neelakantan K.K.
Scale widget, 622 operations, 493–495
Scientific notation, 92 subsets, 492
Senior Manufacturing Controller, Global Edition: Jerry Kataria
Scope supersets, 492 Manager, Media Production, Global Edition: Vikram Kumar
defined, 245 symmetric difference of, 491 Cover Designer: Lumina Datamatics
local variables and, 245–247 union of, 489 Cover Photo: Africa Studio/Shutterstock
parameter variable, 249 unordered, 484
Credits and acknowledgments borrowed from other sources and reproduced, with permission, appear
Script mode, running programs in, 45 values, testing, 488–489
Scrollbar widget, 622 Settings. See Mutator methods
on the Credits page in the endmatter of this textbook.
Searching Showinfo function, 630 Pearson Education Limited
lists, 376–377 sin() function, 285
KAO Two
records, 339–341 Single alternative decision structures, 132
strings, 445–446 Slices KAO Park
Secondary storage defined, 373 Harlow
defined, 27 example use, 373–375 CM17 9NA
devices, 27–28 general format, 373 United Kingdom
Seeds, random number, 270–271 invalid indexes and, 375
Seed value, 270 list, 373–376 and Associated Companies throughout the world
Selection structures. See Decision structures start and end index, 374
Visit us on the World Wide Web at: www.pearsonglobaleditions.com
Sentinels string, 437–438
defined, 204, 205 Software © Pearson Education Limited 2019
using, 205–206 application, 29
values, 204–205 defined, 23 The rights of Tony Gaddis to be identified as the author of this work has been asserted by him in accor-
Separators developers. See Programmers dance with the Copyright, Designs and Patents Act 1988.
comma, 92–93 development tools, 29
item, 88–89 operating system, 28 Authorized adaptation from the United States edition, entitled Starting Out with Python, 4th Edition,
split method, 451–452 requirements, 55 ISBN 978-0-13-444432-1 by Tony Gaddis, published by Pearson Education © 2018.
Sequences. See also Lists system, 28–29
accepting as argument, 383–384 types of, 28 All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted
defined, 365 utility programs, 28 in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without either
length, returning, 369 Sorting, item list, 381–382 the prior written permission of the publisher or a license permitting restricted copying in the United Kingdom
tuples, 402–404 sort method, 378, 381–382
issued by the Copyright Licensing Agency Ltd, Sa ron House, 6–10 Kirby Street, London EC1N 8TS.
Sequence structures Source code. See Code
with decision structure, 147 Specialization, 573–574 All trademarks used herein are the property of their respective owners. The use of any trademark in this
defined, 131 split method, 451 text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor
example, 131 Splitting strings, 451–452
does the use of such trademarks imply any a liation with or endorsement of this book by such owners.
nested inside decision structure, 148 sqrt() function, 285
structure, 147, 148 startswith method, 445, 446
British Library Cataloguing-in-Publication Data
use in programming, 131–132 Statements
Serializing objects for, 190, 194, 196 A catalogue record for this book is available from the British Library
defined, 496 assignment, 62–65
10 9 8 7 6 5 4 3 2 1
example, 498–500, 542–544 in blocks, 133, 235
pickle module, 496–497 breaking into multiple lines, 86–87 ISBN 10: 1-292-22575-0
unserializing, 500–502, 543–544 converting math formulas to, 83–85 ISBN 13: 978-1-292-22575-3
ServiceQuote class, 563–565 defined, 40
set function, 485 del, 383 Typeset by iEnergizer Aptara®, Ltd.
Printed and bound in Malaysia
738 Index
7
Index 735 8 Contents
Chapter 8 More About Strings 429 not operator, 155, 157 multiplication (*), 76, 79, 367
8.1 Basic String Operations 429 Nouns, list refining, 557–560 not in. See Not in operator
8.2 String Slicing 437 Numbers or, 155–157, 159, 160
advanced storage, 34 precedence, 79
8.3 Testing, Searching, and Manipulating Strings 441
binary, 31–32 relational, 133–134, 145–146
Review Questions 453 factorial of, 603–605 remainder (%), 76, 79, 82–83
Programming Exercises 456 Fibonacci, 607–609 repetition (*), 367, 450–451
floating-point, 33, 94 subtraction (−), 76, 79
Chapter 9 Dictionaries and Sets 461 formatting, 90–91 Optical devices, 28
9.1 Dictionaries 461 pseudorandom, 270–271 or operator, 155–157, 159, 160
9.2 Sets 484 random, 262–271 Output
9.3 Serializing Objects 496 running totals, 201–204 in computer program process, 57–58
storage, 31–33 data, 87–95
Review Questions 502
Numeric literals, 69 defined, 28
Programming Exercises 507 Numeric ranges, with logical operators, 160 displaying, 58–61
Output devices, 28
Chapter 10 Classes and Object-Oriented Programming 511 Output files, 310, 311, 315, 322, 326
10.1 Procedural and Object-Oriented Programming 511 O
Overhead, 602
Object-oriented programming (OOP)
10.2 Classes 515 class design, 554–565
Overriding, method, 588
10.3 Working with Instances 532 classes, 515–532
10.4 Techniques for Designing Classes 554 data hiding, 512
P
pack method, 625–627, 629, 634
Review Questions 565 defined, 512
Parameter lists, 252
Programming Exercises 568 encapsulation, 512
Parentheses, grouping with, 80
instances, 515, 532–554
Pascal, 39
Chapter 11 Inheritance 573 Objects, 629. See also Classes
Passing arguments. See also Arguments
11.1 Introduction to Inheritance 573 characteristics description, 515
to function, 248–251
11.2 Polymorphism 588 defined, 512
function parameter variable, 253–255
dictionary, 461–484
Review Questions 594 to index method, 379–381
everyday example of, 513–514
Programming Exercises 596 list as function, 389–390
exception, 359 multiple, 251–253
file, 316–317 and objects, 540–541
Chapter 12 Recursion 599 list, 365, 366 by position, 252
12.1 Introduction to Recursion 599 “is a” relationship, 574 by value, 255
12.2 Problem Solving with Recursion 602 passing as arguments, 540–541 Passwords, validating characters in, 446–449
12.3 Examples of Recursive Algorithms 606 pickling, 542–544 Pattern printing using nested loops, 215–218
Review Questions 614 reusability, 513 Percentages, calculations, 77–78
Programming Exercises 616 sequence, 365 Pickle module, 497–498, 542, 547
serializing, 496–502 Pickling, 496–498, 500, 542–544
Chapter 13 GUI Programming 619 set, 484–496 pi variable, 285
storing in dictionaries, 544–554 pie chart, plotting, 418–420
13.1 Graphical User Interfaces 619
storing in lists, 538–540 pip utility, 705
13.2 Using the tkinter Module 621 StringVar, 636–637 Pixels, 34
13.3 Display Text with Label Widgets 624 unpickling, 543–544 plot() function, 406–407
13.4 Organizing Widgets with Frames 627 open function, 313, 314, 318 Polymorphism
13.5 Button Widgets and Info Dialog Boxes 630 Operands, 76 behavior, ingredients of, 588
13.6 Getting Input with the Entry Widget 633 Operating systems, 28 defined, 588
Operators isinstance function, 591–594
13.7 Using Labels as Output Fields 636
and, 156–158 popitem method, 473, 477
13.8 Radio Buttons and Check Buttons 644 in. See In operator pop method, 472, 720
13.9 Drawing Shapes with the Canvas Widget 651 addition (+), 76, 79, 90 Positional arguments, 257
Review Questions 673 assignment, 135, 203–204 Precedence, operator, 79
Programming Exercises 676 augmented assignment, 203–204 Predefined names colors, 695–699
exponent (**), 76, 80–82 Pretest loops
logical. See Logical operators defined, 186
math, 75–76 while loops as, 186–187
Index 733 10 Contents
Error handlers, 209 defined, 607–608 The new Turtle Graphics sections are designed with flexibility in mind. They can be
Error messages, 41, 44 recursive function calculation, 608–609 assigned as optional material, incorporated into your existing syllabus, or skipped
default, displaying, 355–356 Field widths
altogether.
loop displaying, 208–209 columns, 93
traceback, 349, 351 minimum, specifying, 93–94 ● Chapter 2 has a new section on named constants. Although Python does not support
Errors. See Exceptions File modes, 317 true constants, you can create variable names that symbolize values that should not
Error traps, 209 Filename extensions, 312
change as the program executes. This section teaches the student to avoid the use
Escape characters, 89–90 File objects
Event handlers, callback functions as, 630 close method, 315, 497 of “magic numbers,” and to create symbolic names that make his or her code more
Exception handling defined, 312 self-documenting and easier to maintain.
defined, 352 read method, 316–319 ● Chapter 7 has a new section on using the matplotlib package to plot charts and graphs
multiple exceptions, 352–355 variable name referencing, 312–314 from lists. The new section describes how to install the matplotlib package, and use it to
with try/except statement, 357–358 writelines method, 395–398
plot line graphs, bar charts, and pie charts.
Exception objects, 359 write method, 314
Exceptions finally clause, with try/except statement, 358
● Chapter 13 has a new section on creating graphics in a GUI application with the
catching all, with one except clause, 354–355 Finally suite, 358 Canvas widget. The new section describes how to use the Canvas widget to draw lines,
code response to, 348 find method, 446 rectangles, ovals, arcs, polygons, and text.
default error message display, 355–356 Flags, 162 ● Several new, more challenging, programming problems have been added throughout
defined, 75, 346 Flash drives, 28 the book.
IndexError, 368–369, 433 Flash memory, 28
IOError, 351–352, 354, 358 float data type, 69, 85–86
● Appendix E is a new appendix that discusses the various forms of the import statement.
KeyError, 463, 465, 487 float() function, 73, 74, 75, 86
● Appendix F is a new appendix that discusses installing third-party modules with the
multiple, 352–354 Floating-point division, 78, 79 pip utility.
unhandled, 358–359 Floating-point notation, 33
ValueError, 349–350, 354, 355, Floating-point numbers, 94
356, 358, 382 floor() function, 285 Brief Overview of Each Chapter
ZeroDivisionError, 358 Floppy disk drives, 27
Execution, 223 Flowchart, 56
in fetch-decode-execute cycle, 36 clock simulator, 213
Chapter 1: Introduction to Computers and Programming
pausing, 244 decision structure, 132, 133, 137 This chapter begins by giving a very concrete and easy-to-understand explanation of how
Python interpreter, 686–687 dual alternative decision structure, 130
computers work, how data is stored and manipulated, and why we write programs in high-
try/except statement, 349 input validation loop, 208
while loop, 209 logic for file end detection, 328 level languages. An introduction to Python, interactive mode, script mode, and the IDLE
Exercises nested decision structure, 149, 152 environment are also given.
decision structures, 173–179 pay calculating program, 57
dictionaries and sets, 507–510 program development cycle, 53
files and exceptions, 366–368 running total calculation, 201 Chapter 2: Input, Processing, and Output
functions, 302–308 sequence structure nested inside decision
This chapter introduces the program development cycle, variables, data types, and simple
GUI programming, 676–679 structure, 148
inheritance, 596–597 sequence structures with decision structure, 147–148 programs that are written as sequence structures. The student learns to write simple pro-
input, processing, and output, 126–130 while loop, 183 grams that read input from the keyboard, perform mathematical operations, and produce
introduction, 50–51 Font class, 670–672 screen output. Pseudocode and flowcharts are also introduced as tools for designing pro-
lists and tuples, 424–428 keyword arguments for, 671 grams. The chapter also includes an optional introduction to the turtle graphics library.
programming, 568–572 for loops. See also Loops
recursion, 616–617 as count-controlled loops, 190–200
repetition structures, 265–267 defined, 190–191 Chapter 3: Decision Structures and Boolean Logic
strings, 456–460 in turtle graphics, 219
exp() function, 285 iterating lists with, 368 In this chapter, the student learns about relational operators and Boolean expressions and is
Exponent (**) operator, 76, 80–82 iterating over dictionaries with, 468–469 shown how to control the flow of a program with decision structures. The if, if-else, and
iterating over list of strings with, 192 if-elif-else statements are covered. Nested decision structures and logical operators are
F iterating over sets, 488
discussed as well. The chapter also includes an optional turtle graphics section, with a discus-
Factorial function, 604–605 iterations, 198–200
Factorials iterations, user control, 198–200 sion of how to use decision structures to test the state of the turtle.
calculation with recursion, 602–606 range function with, 190–194
definition rules, 606, 609 target variables, 194–198
Fetch-decode-execute cycle, 36–37 format function, 91, 94
Chapter 4: Repetition Structures
Fibonacci series Format specifiers, 91–94 This chapter shows the student how to create repetition structures using the while loop and
for loop. Counters, accumulators, running totals, and sentinels are discussed, as well as
Preface 15 728 Index
techniques for writing input validation loops. The chapter also includes an optional section create_polygon method, 665–667 defined, 461
on using loops to draw designs with the turtle graphics library. optional arguments to, 667 elements, adding, 464
create_rectangle method, 655–657 elements, deleting, 465, 469
optional arguments to, 657 elements, display order, 462
Chapter 5: Functions create_text method, 667–672 elements, number of, 465–466
optional arguments to, 669 empty, creating, 467–468
In this chapter, the student first learns how to write and call void functions. The chapter C# programming language, 39 example, 474–477, 477–483
shows the benefits of using functions to modularize programs and discusses the top-down Customer class, 561–562 iteration, 468–469
design approach. Then, the student learns to pass arguments to functions. Common library keys, 461, 462
functions, such as those for generating random numbers, are discussed. After learning how D key-value pairs, 461, 464
Data methods, 469–474
to call library functions and use their return value, the student learns to define and call his mixing data types in, 466–467
appending to files, 322
or her own functions. Then the student learns how to use modules to organize functions. An binary file, 311 parts of, 461
optional section includes a discussion of modularizing turtle graphics code with functions. digital, 34 retrieving value from, 462–463
hiding, 512 storing objects in, 544–554
output, 87–95 values, 463–464
Chapter 6: Files and Exceptions processing, 333–346 Dictionary views
reading from files, 310–311, 316–319 defined, 470
This chapter introduces sequential file input and output. The student learns to read and write
text file, 311 elements, 470
large sets of data and store data as fields and records. The chapter concludes by discussing keys returned as, 471
writing to files, 310, 314–316
exceptions and shows the student how to write exception-handling code. Data attributes, 512 values returned as, 473–474
hidden, 513 dict() method, 468
hiding, 522–525 difference method, 490–491
Chapter 7: Lists and Tuples Digital data, 34
initializing, 518
This chapter introduces the student to the concept of a sequence in Python and explores the instance, 532–554 Digital devices, 34
Data storage, 29–33 Direct access files, 312, 343, 346
use of two common Python sequences: lists and tuples. The student learns to use lists for
characters, 33 Direct recursion, 606
arraylike operations, such as storing objects in a list, iterating over a list, searching for items music, 34 discard method, 487
in a list, and calculating the sum and average of items in a list. The chapter discusses slic- Data types Disk drives
ing and many of the list methods. One- and two-dimensional lists are covered. The chapter bool, 161 defined, 27
also includes a discussion of the matplotlib package, and how to use it to plot charts and conversion and mixed-type expressions, 85–86 program storage on, 36
graphs from lists. and literals, 68–69 Divide and conquer approach, 232
mixing, 466–467 Division
str, 69–70 floating-point, 78
Chapter 8: More About Strings Debugging, 54, 154 integer, 76, 78
global variables and, 258–259 / operator, 76, 78, 79
In this chapter, the student learns to process strings at a detailed level. String slicing and Decision structures, 132 Dog class, 589–590
algorithms that step through the individual characters in a string are discussed, and several actions performed in, 132–133 Dot notation, 263, 285
built-in functions and string methods for character and text processing are introduced. combining sequence structures with, 147–148 Dual alternative decision structure,
dual alternative, 140 139–140
in flowcharts, 132 dump method, 497
Chapter 9: Dictionaries and Sets if-elif-else statement, 153–154 DVD drives, 28
if-else statement, 140–143 DVDs (digital versatile discs), 28
This chapter introduces the dictionary and set data structures. The student learns to store data if statement, 131–139
as key-value pairs in dictionaries, search for values, change existing values, add new key-value inside, 148 E
pairs, and delete key-value pairs. The student learns to store values as unique elements in sets nested, 147–155 else clause, 143, 150
and perform common set operations such as union, intersection, di erence, and symmetric single alternative, 132 execution, 140
degrees() function, 285 with try/except statement, 357–358
di erence. The chapter concludes with a discussion of object serialization and introduces the
del statement, 383 else suite, 357
student to the Python pickle module. Depth of recursion, 602 Encapsulation, 512
Derived classes, 574 end–of–file, 500–501, 543
Chapter 10: Classes and Object-Oriented Programming Dialog boxes endswith method, 445, 446
defined, 619 ENIAC computer, 25, 26
This chapter compares procedural and object-oriented programming practices. It covers the illustrated, 620–621 Entry widget
fundamental concepts of classes and objects. Attributes, methods, encapsulation and data info, 630–633 defined, 622, 633
Dictionaries getting input with, 633–636
hiding, _ _init_ _ functions (which are similar to constructors), accessors, and mutators are
creating, 462 use example, 634–636
discussed. The student learns how to model classes with UML and how to find the classes
in a particular problem.
Index 727 16 Preface
VideoNotes Online videos developed specifically for this book are available
for viewing at www.pearsonglobaleditions.com/gaddis. Icons appear
throughout the text alerting the student to videos about specific
topics.
Notes Notes appear at several places throughout the text. They are
short explanations of interesting or often misunderstood points
relevant to the topic at hand.
Index Tips Tips advise the student on the best techniques for approaching
di erent programming problems.
Warnings Warnings caution students about programming techniques or
practices that can lead to malfunctioning programs or lost data.
Checkpoints Checkpoints are questions placed at intervals throughout each
chapter. They are designed to query the student’s knowledge
Symbols defined, 134 quickly after learning a new topic.
!= operator in string comparisons, 144
defined, 136 use example, 138 Review Questions Each chapter presents a thorough and diverse set of review
example use, 136, 138 > operator questions and exercises. They include Multiple Choice, True/
" (double-quote marks), 60 defined, 134 False, Algorithm Workbench, and Short Answer.
""" or "' (triple quotes), 60 in string comparisons, 146
# character, 61 use example, 134, 135–136 Programming Each chapter o ers a pool of programming exercises designed
% (remainder) operator >= operator Exercises to solidify the student’s knowledge of the topics currently being
defined, 76, 82 defined, 134 studied.
function of, 281 in superset determination, 492
%= operator, 203 relationship testing, 135
& operator, for intersection of sets, 490 >>> prompt, 43, 44
Supplements
' (single-quote marks), 59–60 ^ operator, 491
* operator _ _init_ _ method, 521, 555, 561, 563, 583 Student Online Resources
multiplication, 76 {}(curly braces), 462
Many student resources are available for this book from the publisher. The following items
repetition, 367
are available at www.pearsonglobaleditions.com/gaddis
** (exponent) operator, 76, 80–82 A
*= operator, 203 Accessor methods, 537 ● The source code for each example program in the book
+ operator acos(x) function, 285 ● Access to the book’s companion VideoNotes
defined, 76 Actions
displaying multiple items with, 90 conditionally executed, 132
in list concatenation, 371 in decision structures, 133 Instructor Resources
+= operator Ada programming language, 39
defined, 203
The following supplements are available to qualified instructors only:
Addition (+) operator
in list concatenation, 372 defined, 76 ● Answers to all of the Review Questions
in string concatenation, 435 displaying multiple items with, 90 ● Solutions for the exercises
− (subtraction) operator, 76 precedence, 79
_ _str_ _ method, 529–532 add method, 486
● PowerPoint presentation slides for each chapter
−= operator, 203 Algebraic expressions, 83–84 ● Test bank
/ (division) operator, 76, 78 Algorithms
// (integer division) operator, 76, 78 defined, 55 Visit the Pearson Instructor Resource Center (www.pearsonglobaleditions.com/gaddis) or
/= operator, 203 example, 55 contact your local Pearson campus representative for information on how to access them.
= operator recursive, 602, 603, 606–613
defined, 134 and operator
in subset determination, 492 defined, 156
relationship testing, 135 false, 158
= (assignment) operator, 135 short-circuit evaluation, 157
== operator truth table, 156
assignment operator versus, 136 Appending data, 322
725
Preface 19 724 Appendix G Answers to Checkpoints
I would like to thank the following faculty reviewers for their insight, expertise, and thought- 13.16 You would use check buttons.
ful recommendations: 13.17 When you create a group of Radiobuttons, you associate them all with
Sonya Dennis Anita Sutton the same IntVar object. You also assign a unique integer value to each
Morehouse College Germanna Community College Radiobutton widget. When one of the Radiobutton widgets is selected,
it stores its unique integer value in the IntVar object.
Diane Innes Christopher Urban
Sandhills Community College SUNY Institute of Technology 13.18 You associate a different IntVar object with each Checkbutton. When a
Checkbutton is selected, its associated IntVar object will hold the value 1.
John Kinuthia Nanette Veilleux When a Checkbutton is deselected, its associated IntVar object will hold the
Nazareth College of Rochester Simmons College value 0.
Frank Liu Brent Wilson 13.19 (0, 0)
Sam Houston State University George Fox University
13.20 (139, 479)
Haris Ribic
SUNY at Binghamton 13.21 With the Canvas widget, the point (0, 0) is in the upper-left corner of the
window. In turtle graphics, the point (0, 0) is in the center of the window.
Reviewers of Previous Editions Also, with the Canvas widget, the Y coordinates increase as you move down
Paul Amer Shyamal Mitra the screen. In turtle graphics, the Y coordinates decrease as you move down
University of Delaware University of Texas at Austin the screen.
Chapter 12 I would also like to thank my family and friends for their support in all of my projects.
I am extremely fortunate to have Matt Goldstein as my editor, and Kristy Alaura as edito-
12.1 A recursive algorithm requires multiple method calls. Each method call rial assistant. Their guidance and encouragement make it a pleasure to write chapters and
requires several actions to be performed by the JVM. These actions include meet deadlines. I am also fortunate to have Demetrius Hall as my marketing manager. His
allocating memory for parameters and local variables and storing the address hard work is truly inspiring, and he does a great job of getting this book out to the academic
of the program location where control returns after the method terminates. community. The production team, led by Sandra Rodriguez, worked tirelessly to make this
All these actions are known as overhead. In an iterative algorithm, which book a reality. Thanks to you all!
uses a loop, such overhead is unnecessary.
12.2 A case in which the problem can be solved without recursion Acknowledgments for the Global Edition
12.3 Cases in which the problem is solved using recursion Pearson would like to thank and acknowledge the following for their contributions to the
12.4 When it reaches the base case Global Edition.
12.5 In direct recursion, a recursive method calls itself. In indirect recursion, Contributor
method A calls method B, which in turn calls method A. Gregory Baatard, Edith Cowan University
Kenneth Eustace, Charles Sturt University
Chapter 13 Reviewers
Lindsay Ward, James Cook University
13.1 The part of a computer and its operating system with which the user
Ajay Mittal, University Institute of Engineering and Technology
interacts
Khyat Sharma
13.2 A command line interface typically displays a prompt, and the user types a
command, which is then executed. About the Author
13.3 The program Tony Gaddis is the principal author of the Starting Out with series of textbooks. Tony has
13.4 A program that responds to events that take place, such as the user clicking a nearly two decades of experience teaching computer science courses at Haywood Com-
button munity College. He is a highly acclaimed instructor who was previously selected as the
North Carolina Community College “Teacher of the Year” and has received the Teaching
13.5 a) Label—An area that displays one line of text or an image Excellence award from the National Institute for Sta and Organizational Development.
b) Entry—An area in which the user may type a single line of input from the The Starting Out with series includes introductory books covering C++, Java™, Microsoft®
keyboard Visual Basic®, Microsoft® C#®, Python®, Programming Logic and Design, Alice, and App
c) Button—A button that can cause an action to occur when it is clicked Inventor, all published by Pearson.
d) Frame—A container that can hold other widgets
13.6 You create an instance of the tkinter module’s Tk class.
13.7 This function runs like an infinite loop until you close the main window.
13.8 The pack method arranges a widget in its proper position, and it makes the
widget visible when the main window is displayed.
13.9 One will be stacked on top of the other.
13.10 side=–left—
13.11 You use an Entry widget’s get method to retrieve the data that the user has
typed into the widget.
13.12 It is a string.
13.13 tkinter
13.14 Any value that is stored in the StringVar object will automatically be
displayed in the Label widget.
722 Appendix G Answers to Checkpoints
Chapter 11
11.1 A superclass is a general class, and a subclass is a specialized class.
11.2 When one object is a specialized version of another object, there is an “is a”
relationship between them. The specialized object “is a” version of the
general object.
11.3 It inherits all the superclass’s attributes.
11.4 Bird is the superclass, and Canary is the subclass.
9.25 If the specified element to delete is not in the set, the remove method raises a
KeyError exception, but the discard method does not raise an exception.
9.26 You can use the in operator to test for the element.
9.27 {10, 20, 30, 100, 200, 300}
9.28 {3, 4}
9.29 {1, 2}
9.30 {5, 6}
9.33 The process of converting the object to a stream of bytes that can be saved to
a file for later retrieval.
9.34 'wb'
9.35 'rb'
9.38 pickle.load
Chapter 9
9.1 Key and value
9.2 The key
9.3 The string 'start' is the key, and the integer 1472 is the value.
Introduction to Computers
CHAPTE R
1
9.4 It stores the key-value pair 'id' : 54321 in the employee dictionary.
Computers can perform such a wide variety of tasks because they can be programmed. This 9.18 The set will contain one element: 25.
means that computers are not designed to do just one job, but to do any job that their pro-
9.19 The set will contain these elements (in no particular order): 'w', ' ', 'x',
grams tell them to do. A program is a set of instructions that a computer follows to perform
'y', and 'z'.
a task. For example, Figure 1-1 shows screens using Microsoft Word and PowerPoint, two
commonly used programs. 9.20 The set will contain these elements (in no particular order): 1, 2, 3, and 4.
Programs are commonly referred to as software. Software is essential to a computer because 9.21 The set will contain these elements (in no particular order): 'www', 'xxx',
it controls everything the computer does. All of the software that we use to make our com- 'yyy', and 'zzz'.
puters useful is created by individuals working as programmers or software developers. A
9.22 You pass the set as an argument to the len function.
programmer, or software developer, is a person with the training and skills necessary to
design, create, and test computer programs. Computer programming is an exciting and 9.23 The set will contain these elements (in no particular order): 10, 9, 8, 1, 2,
rewarding career. Today, you will find programmers’ work used in business, medicine, gov- and 3.
ernment, law enforcement, agriculture, academics, entertainment, and many other fields. 9.24 The set will contain these elements (in no particular order): 10, 9, 8, 'a',
This book introduces you to the fundamental concepts of computer programming using the 'b', and 'c'.
Python language. The Python language is a good choice for beginners because it is easy to learn
23
Appendix G Answers to Checkpoints 719 24 Chapter 1 Introduction to Computers and Programming
Then, each element in the list will become a slice in the pie chart. The size of Figure 1-1 A word processing program and an image editing program
a slice represents that element’s value as a percentage of the whole.
Chapter 8
8.1 for letter in name:
print(letter)
8.2 0
8.3 9
8.4 An IndexError exception will occur if you try to use an index that is out of
range for a particular string.
8.5 Use the built-in len function.
8.6 The second statement attempts to assign a value to an individual character
in the string. Strings are immutable, however, so the expression animal[0]
cannot appear on the left side of an assignment operator.
8.7 cde and programs can be written quickly using it. Python is also a powerful language, popular with
professional software developers. In fact, it has been reported that Python is used by Google,
8.8 defg NASA, YouTube, various game companies, the New York Stock Exchange, and many others.
8.9 abc Before we begin exploring the concepts of programming, you need to understand a few
8.10 abcdefg basic things about computers and how they work. This chapter will build a solid founda-
tion of knowledge that you will continually rely on as you study computer science. First,
8.11 if 'd' in mystring: we will discuss the physical components of which computers are commonly made. Next, we
print('Yes, it is there.')
will look at how computers store data and execute programs. Finally, you will get a quick
8.12 little = big.upper() introduction to the software that you will use to write Python programs.
8.13 if ch.isdigit():
print('Digit')
else: 1.2 Hardware and Software
print('No digit')
8.14 a A CONCEPT : The physical devices of which a computer is made are referred to as the
computer’s hardware. The programs that run on a computer are referred
8.15 again = input('Do you want to repeat ' + to as software.
'the program or quit? (R/Q) ')
while again.upper() != 'R' and again.upper() != 'Q': Hardware
again = input('Do you want to repeat the ' +
'program or quit? (R/Q) ') The term hardware refers to all of the physical devices, or components, of which a computer
is made. A computer is not one single device, but a system of devices that all work toge-
8.16 $ ther. Like the different instruments in a symphony orchestra, each device in a computer
8.17 for letter in mystring: plays its own part.
if letter.isupper(): If you have ever shopped for a computer, you’ve probably seen sales literature listing compo-
count += 1
nents such as microprocessors, memory, disk drives, video displays, graphics cards, and so on.
8.18 my_list = days.split() Unless you already know a lot about computers, or at least have a friend that does, under-
standing what these different components do might be challenging. As shown in Figure 1-2, a
8.19 my_list = values.split('$')
typical computer system consists of the following major components:
The central processing unit (CPU)
Main memory
1.2 Hardware and Software 25 718 Appendix G Answers to Checkpoints
Figure 1-2 Typical components of a computer system 7.17 You would use statement b, names.append('Wendy'). This is because
element 0 does not exist. If you try to use statement a, an error will occur.
7.18 a) The index method searches for an item in the list and returns the index of
the first element containing that item.
b) The insert method inserts an item into the list at a specified index.
Shutterstock
Central Processing c) The sort method sorts the items in the list to appear in ascending order.
Shutterstock
Unit
d) The reverse method reverses the order of the items in the list.
iko/Shutterstock
7.19 The list contains 4 rows and 2 columns.
Shutterstock
Feng Yu/Shutterstock
Output
Aquila/ Devices 7.20 mylist = [[0, 0, 0, 0], [0, 0, 0, 0],
[0, 0, 0, 0], [0, 0, 0, 0]]
Chiyacat/
Shutterstock 7.21 for r in range(4):
Peter Guess/
Shutterstock
for c in range(2):
Input
Devices
print(numbers[r][c])
jocic/Shutterstock
7.22 The primary difference between tuples and lists is that tuples are immutable.
Eikostas/Shutterstock
That means that once a tuple is created, it cannot be changed.
Main Memory
(RAM) 7.23 Here are three reasons:
Lusoimages/Shutterstock
Processing a tuple is faster than processing a list, so tuples are good
tkemot/Shutterstock Secondary
Storage Devices choices when you are processing lots of data and that data will not be
modified.
Tuples are safe. Because you are not allowed to change the contents of a
tuple, you can store data in one and rest assured that it will not be modified
(accidentally or otherwise) by any code in your program.
There are certain operations in Python that require the use of a tuple.
Vitaly Korovin/Shutterstock Andre Nitsievsky/Shutterstock.
7.24 my_tuple = tuple(my_list)
Secondary storage devices 7.25 my_list = list(my_tuple)
Input devices
Output devices 7.26 Two lists: one holding the X coordinates of the data points, and the other
holding the Y coordinates.
Let’s take a closer look at each of these components.
7.27 A line graph
The CPU 7.28 Use the xlabel and ylabel functions.
When a computer is performing the tasks that a program tells it to do, we say that the 7.29 Call the xlim and ylim functions, passing values for the xmin, xmax, ymin,
computer is running or executing the program. The central processing unit, or CPU, is the and ymax keyword arguments.
part of a computer that actually runs programs. The CPU is the most important component
7.30 Call the xticks and yticks functions. You pass two arguments to these
in a computer because without it, the computer could not run software.
functions. The first argument is a list of tick-mark locations, and the second
In the earliest computers, CPUs were huge devices made of electrical and mechanical com- argument is a list of labels to display at the specified locations.
ponents such as vacuum tubes and switches. Figure 1-3 shows such a device. The two
7.31 Two lists: one containing the X coordinates of each bar’s left edge, and
women in the photo are working with the historic ENIAC computer. The ENIAC, which
another containing the heights of each bar, along the Y axis.
is considered by many to be the world’s first programmable electronic computer, was built
in 1945 to calculate artillery ballistic tables for the U.S. Army. This machine, which was 7.32 The bars will be red, blue, red, and blue.
primarily one big CPU, was 8 feet tall, 100 feet long, and weighed 30 tons. 7.33 You pass a list of values as an argument. The pie function will calculate
Today, CPUs are small chips known as microprocessors. Figure 1-4 shows a photo of a lab the sum of the values in the list, then use that sum as the value of the whole.
technician holding a modern microprocessor. In addition to being much smaller than the old
electromechanical CPUs in early computers, microprocessors are also much more powerful.
Appendix G Answers to Checkpoints 717 26 Chapter 1 Introduction to Computers and Programming
6.18 You copy all the original file’s records to the temporary file, except for the Figure 1-3 The ENIAC computer
record that is to be deleted. The temporary file then takes the place of the
original file. You delete the original file and rename the temporary file, giving
it the name that the original file had on the computer’s disk.
6.19 An exception is an error that occurs while a program is running. In most
cases, an exception causes a program to abruptly halt.
6.20 The program halts.
6.21 IOError
6.22 ValueError
Chapter 7
7.1 [1, 2, 99, 4, 5]
7.2 [0, 1, 2]
7.4 1
courtesy of U.S. Army Historic Computer Images
3
5
7
9
Figure 1-4 A lab technician holds a modern microprocessor
7.5 4
7.8 [1, 2, 3]
[10, 20, 30, 1, 2, 3]
7.9 [2, 3]
7.10 [2, 3]
7.11 [1]
7.12 [1, 2, 3, 4, 5]
7.13 [3, 4, 5]
7.15 The remove method searches for and removes an element containing a
Creativa/Shutterstock
specific value. The del statement removes an element at a specific index.
7.16 You can use the built-in min and max functions.
1.2 Hardware and Software 27 716 Appendix G Answers to Checkpoints
Main Memory has not been converted to text. As a consequence, you cannot view the con-
tents of a binary file with a text editor.
You can think of main memory as the computer’s work area. This is where the computer
stores a program while the program is running, as well as the data that the program is 6.5 Sequential and direct access. When you work with a sequential access file,
working with. For example, suppose you are using a word processing program to write an you access data from the beginning of the file to the end of the file. When
essay for one of your classes. While you do this, both the word processing program and the you work with a direct access file, you can jump directly to any piece of data
essay are stored in main memory. in the file without reading the data that comes before it.
Main memory is commonly known as random-access memory, or RAM. It is called this 6.6 The file’s name on the disk and the name of a variable that references a file
because the CPU is able to quickly access data stored at any random location in RAM. object.
RAM is usually a volatile type of memory that is used only for temporary storage while
6.7 The file’s contents are erased.
a program is running. When the computer is turned off, the contents of RAM are erased.
Inside your computer, RAM is stored in chips, similar to the ones shown in Figure 1-5. 6.8 Opening a file creates a connection between the file and the program. It also
creates an association between the file and a file object.
6.9 Closing a file disconnects the program from the file.
Figure 1-5 Memory chips
6.10 A file’s read position marks the location of the next item that will be read
from the file. When an input file is opened, its read position is initially set to
the first item in the file.
6.11 You open the file in append mode. When you write data to a file in append
mode, the data is written to the end of the file’s existing contents.
Garsya/Shutterstock 6.12 outfile = open('numbers.txt', 'w')
for num in range(1, 11):
outfile.write(str(num) + '\n')
outfile.close()
Secondary Storage Devices
6.13 The readline method returns an empty string ('') when it has attempted to
Secondary storage is a type of memory that can hold data for long periods of time, even
read beyond the end of a file.
when there is no power to the computer. Programs are normally stored in secondary mem-
ory and loaded into main memory as needed. Important data, such as word processing 6.14 infile = open('numbers.txt', 'r')
documents, payroll data, and inventory records, is saved to secondary storage as well. line = infile.readline()
while line != '':
The most common type of secondary storage device is the disk drive. A traditional disk
print(line)
drive stores data by magnetically encoding it onto a spinning circular disk. Solid-state
line = infile.readline()
drives, which store data in solid-state memory, are increasingly becoming popular. A solid-
state drive has no moving parts and operates faster than a traditional disk drive. Most in le.close()
computers have some sort of secondary storage device, either a traditional disk drive or a 6.15 infile = open('data.txt', 'r')
solid-state drive, mounted inside their case. External storage devices, which connect to one for line in infile:
of the computer’s communication ports, are also available. External storage devices can print(line)
be used to create backup copies of important data or to move data to another computer. infile.close()
In addition to external storage devices, many types of devices have been created for copy- 6.16 A record is a complete set of data that describes one item, and a field is a
ing data and for moving it to other computers. For example, USB drives are small devices single piece of data within a record.
that plug into the computer’s USB (universal serial bus) port and appear to the system as
a disk drive. These drives do not actually contain a disk, however. They store data in a 6.17 You copy all the original file's records to the temporary file, but when you
special type of memory known as flash memory. USB drives, which are also known as get to the record that is to be modified, you do not write its old contents
memory sticks and flash drives, are inexpensive, reliable, and small enough to be carried to the temporary file. Instead, you write its new, modified values to the
in your pocket. temporary file. Then, you finish copying any remaining records from the
original file to the temporary file.
Appendix G Answers to Checkpoints 715 28 Chapter 1 Introduction to Computers and Programming
be changed during the program’s execution, you do not have to worry about Optical devices such as the CD (compact disc) and the DVD (digital versatile disc) are
its value being altered. also popular for data storage. Data is not recorded magnetically on an optical disc, but is
encoded as a series of pits on the disc surface. CD and DVD drives use a laser to detect
5.21 The difference is that a value returning function returns a value back to the
the pits and thus read the encoded data. Optical discs hold large amounts of data, and
statement that called it. A simple function does not return a value.
for that reason, recordable CD and DVD drives are commonly used for creating backup
5.22 A prewritten function that performs some commonly needed task copies of data.
5.23 The term “black box” is used to describe any mechanism that accepts input,
performs some operation (that cannot be seen) using the input, and produces Input Devices
output.
Input is any data the computer collects from people and from other devices. The compo-
5.24 It assigns a random integer in the range of 1 through 100 to the variable x. nent that collects the data and sends it to the computer is called an input device. Common
5.25 It prints a random integer in the range of 1 through 20. input devices are the keyboard, mouse, touchscreen, scanner, microphone, and digital cam-
era. Disk drives and optical drives can also be considered input devices, because programs
5.26 It prints a random integer in the range of 10 through 19. and data are retrieved from them and loaded into the computer’s memory.
5.27 It prints a random floating-point number in the range of 0.0 up to, but not
including, 1.0.
Output Devices
5.28 It prints a random floating-point number in the range of 0.1 through 0.5.
Output is any data the computer produces for people or for other devices. It might be
5.29 It uses the system time, retrieved from the computer’s internal clock. a sales report, a list of names, or a graphic image. The data is sent to an output device,
5.30 If the same seed value were always used, the random number functions which formats and presents it. Common output devices are video displays and printers.
would always generate the same series of pseudorandom numbers. Disk drives can also be considered output devices because the system sends data to them
in order to be saved.
5.31 It returns a value back to the part of the program that called it.
Software Development Tools Software development tools are the programs that pro- 5.5 When a program is developed as a set of functions in which each performs
grammers use to create, modify, and test software. Assemblers, compilers, and interpret- an individual task, then different programmers can be assigned the job of
ers are examples of programs that fall into this category. writing different functions.
5.6 A function definition has two parts: a header and a block. The header
Application Software indicates the starting point of the function, and the block is a list of
statements that belong to the function.
Programs that make a computer useful for everyday tasks are known as application soft-
ware. These are the programs that people normally spend most of their time running on 5.7 To call a function means to execute the function.
their computers. Figure 1-1, at the beginning of this chapter, shows screens from two com- 5.8 When the end of the function is reached, the computer returns back to the
monly used applications: Microsoft Word, a word processing program, and PowerPoint, a part of the program that called the function, and the program resumes
presentation program. Some other examples of application software are spreadsheet pro- execution at that point.
grams, email programs, web browsers, and game programs.
5.9 Because the Python interpreter uses the indentation to determine where a
block begins and ends
Checkpoint
5.10 A local variable is a variable that is declared inside a function. It belongs to
1.1 What is a program?
the function in which it is declared, and only statements in the same function
1.2 What is hardware? can access it.
1.3 List the five major components of a computer system.
5.11 The part of a program in which a variable may be accessed
1.4 What part of the computer actually runs programs?
5.12 Yes, it is permissible.
1.5 What part of the computer serves as a work area to store a program and its data
while the program is running? 5.13 Arguments
1.6 What part of the computer holds data for long periods of time, even when there is 5.14 Parameters
no power to the computer?
5.15 A parameter variable’s scope is the entire function in which the parameter is
1.7 What part of the computer collects data from people and from other devices?
declared.
1.8 What part of the computer formats and presents data for people or other devices?
5.16 No, it does not.
1.9 What fundamental set of programs control the internal operations of the
computer’s hardware? 5.17 a. passes by keyword argument
1.10 What do you call a program that performs a specialized task, such as a virus b. passes by position
scanner, a file compression program, or a data backup program? 5.18 The entire program
1.11 Word processing programs, spreadsheet programs, email programs, web browsers,
5.19 Here are three:
and game programs belong to what category of software?
Global variables make debugging difficult. Any statement in a program can
change the value of a global variable. If you find that the wrong value is being
stored in a global variable, you have to track down every statement that
1.3 How Computers Store Data accesses it to determine where the bad value is coming from. In a program
with thousands of lines of code, this can be difficult.
CONCEPT: All data that is stored in a computer is converted to sequences of 0s Functions that use global variables are usually dependent on those variables.
and 1s. If you want to use such a function in a different program, you will most likely
have to redesign it so it does not rely on the global variable.
A computer’s memory is divided into tiny storage locations known as bytes. One byte is Global variables make a program hard to understand. A global variable
only enough memory to store a letter of the alphabet or a small number. In order to do can be modified by any statement in the program. If you are to understand
anything meaningful, a computer has to have lots of bytes. Most computers today have any part of the program that uses a global variable, you have to be aware
millions, or even billions, of bytes of memory. of all the other parts of the program that access the global variable.
Each byte is divided into eight smaller storage locations known as bits. The term bit stands 5.20 A global constant is a name that is available to every function in the
for binary digit. Computer scientists usually think of bits as tiny switches that can be either program. It is permissible to use global constants. Because their value cannot
Appendix G Answers to Checkpoints 713 30 Chapter 1 Introduction to Computers and Programming
4.13 A variable that is used to accumulate the total of a series of numbers on or off. Bits aren’t actual “switches,” however, at least not in the conventional sense. In
most computer systems, bits are tiny electrical components that can hold either a positive
4.14 Yes, it should be initialized with the value 0. This is because values are added
or a negative charge. Computer scientists think of a positive charge as a switch in the on
to the accumulator by a loop. If the accumulator does not start at the value 0,
position, and a negative charge as a switch in the off position. Figure 1-6 shows the way
it will not contain the correct total of the numbers that were added to it when
that a computer scientist might think of a byte of memory: as a collection of switches that
the loop ends.
are each flipped to either the on or off position.
4.15 15
4.16 15
Figure 1-6 Think of a byte as eight switches
5
4.17 a) quantity += 1 ON ON ON ON
b) days_left −= 5
c) price *= 10
d) price /= 2
4.18 A sentinel is a special value that marks the end of a list of items.
4.19 A sentinel value must be unique enough that it will not be mistaken as a OFF OFF OFF OFF
regular value in the list.
4.20 It means that if bad data (garbage) is provided as input to a program, the
program will produce bad data (garbage) as output. When a piece of data is stored in a byte, the computer sets the eight bits to an on/off
4.21 When input is given to a program, it should be inspected before it is pattern that represents the data. For example, the pattern on the left in Figure 1-7 shows
processed. If the input is invalid, then it should be discarded and the user how the number 77 would be stored in a byte, and the pattern on the right shows how the
should be prompted to enter the correct data. letter A would be stored in a byte. We explain below how these patterns are determined.
4.22 The input is read, then a pretest loop is executed. If the input data is invalid,
the body of the loop executes. In the body of the loop, an error message is Figure 1-7 Bit patterns for the number 77 and the letter A
displayed so the user will know that the input was invalid, and then the
input read again. The loop repeats as long as the input is invalid. ON ON ON ON ON ON
4.23 It is the input operation that takes place just before an input validation loop.
The purpose of the priming read is to get the first input value.
4.24 None OFF
OFF OFF OFF OFF OFF OFF OFF OFF OFF
The position of each digit in a binary number has a value assigned to it. Starting with 3.26 You use the turtle.pencolor() function to determine the pen color.
the rightmost digit and moving left, the position values are 20, 21, 22, 23, and so forth, as You use the turtle.fillcolor() function to determine the current fill
shown in Figure 1-8. Figure 1-9 shows the same diagram with the position values calcu- color. You use the turtle.bgcolor() function to determine the current
lated. Starting with the rightmost digit and moving left, the position values are 1, 2, 4, 8, background color of the turtle’s graphics window.
and so forth.
3.27 You use the turtle.pensize() function.
3.28 You use the turtle.speed() function.
Figure 1-8 The values of binary digits as powers of 2
10011101 Chapter 4
0 4.1 A structure that causes a section of code to repeat
2
21 4.2 A loop that uses a true/false condition to control the number of times that it
22
23 repeats
24
25 4.3 A loop that repeats a specific number of times
26
27 4.4 An execution of the statements in the body of the loop
4.5 Before
Figure 1-9 The values of binary digits 4.6 None. The condition count < 0 will be false to begin with.
4.7 A loop that has no way of stopping and repeats until the program is
10011101 interrupted.
1 4.8 for x in range(6):
2
4 print('I love to program!')
8
16 4.9 0
32 1
64
128
2
3
4
5
To determine the value of a binary number, you simply add up the position values of all the
1s. For example, in the binary number 10011101, the position values of the 1s are 1, 4, 8, 4.10 2
16, and 128. This is shown in Figure 1-10. The sum of all of these position values is 157. 3
So, the value of the binary number 10011101 is 157. 4
5
3.13 if number == 1: Figure 1-11 shows how you can picture the number 157 stored in a byte of memory. Each
print('One') 1 is represented by a bit in the on position, and each 0 is represented by a bit in the off
elif number == 2: position.
print('Two')
elif number == 3:
print('Three') Figure 1-11 The bit pattern for 157
else:
print('Unknown')
Any piece of data that is stored in a computer’s memory must be stored as a binary num- 2.39 turtle.setup(500, 200)
ber. That includes characters, such as letters and punctuation marks. When a character is 2.40 turtle.goto(100, 50)
stored in memory, it is first converted to a numeric code. The numeric code is then stored
in memory as a binary number. 2.41 turtle.pos()
Over the years, different coding schemes have been developed to represent characters in 2.42 turtle.speed(10)
computer memory. Historically, the most important of these coding schemes is ASCII, 2.43 turtle.speed(0)
which stands for the American Standard Code for Information Interchange. ASCII is a set
of 128 numeric codes that represent the English letters, various punctuation marks, and 2.44 To fill a shape with a color, you use the turtle.begin_fill() command
other characters. For example, the ASCII code for the uppercase letter A is 65. When you before drawing the shape, then you use the turtle.end_fill() command
type an uppercase A on your computer keyboard, the number 65 is stored in memory (as after the shape is drawn. When the turtle.end_fill() command executes,
a binary number, of course). This is shown in Figure 1-13. the shape will be filled with the current fill color.
2.45 With the turtle.write()command
Figure 1-13 The letter A is stored in memory as the number 65
Chapter 3
1 1
A
3.1 A logical design that controls the order in which a set of statements execute
65 3.2 It is a program structure that can execute a set of statements only under
0 0 0 0 0 0
certain circumstances.
3.3 A decision structure that provides a single alternative path of execution.
If the condition that is being tested is true, the program takes the alternative
TIP : The acronym ASCII is pronounced “askee.” path.
3.4 An expression that can be evaluated as either true or false
In case you are curious, the ASCII code for uppercase B is 66, for uppercase C is 67, and so 3.5 You can determine whether one value is greater than, less than, greater than
forth. Appendix C shows all of the ASCII codes and the characters they represent. or equal to, less than or equal to, equal to, or not equal to another value.
The ASCII character set was developed in the early 1960s and was eventually adopted by 3.6 if y == 20:
almost all computer manufacturers. ASCII is limited, however, because it defines codes for x = 0
only 128 characters. To remedy this, the Unicode character set was developed in the early 3.7 if sales >= 10000:
1990s. Unicode is an extensive encoding scheme that is compatible with ASCII, but can commissionRate = 0.2
also represent characters for many of the languages in the world. Today, Unicode is quickly
becoming the standard character set used in the computer industry. 3.8 A dual alternative decision structure has two possible paths of execution;
one path is taken if a condition is true, and the other path is taken if the
condition is false.
Advanced Number Storage 3.9 if-else
Earlier, you read about numbers and how they are stored in memory. While reading that 3.10 When the condition is false
section, perhaps it occurred to you that the binary numbering system can be used to repre-
sent only integer numbers, beginning with 0. Negative numbers and real numbers (such as 3.11 z is not less than a.
3.14159) cannot be represented using the simple binary numbering technique we discussed. 3.12 Boston
Computers are able to store negative numbers and real numbers in memory, but to do so New York
they use encoding schemes along with the binary numbering system. Negative numbers are
encoded using a technique known as two’s complement, and real numbers are encoded in
floating-point notation. You don’t need to know how these encoding schemes work, only
that they are used to convert negative numbers and real numbers to binary format.
Appendix G Answers to Checkpoints 709 34 Chapter 1 Introduction to Computers and Programming
01
0
2.20 4
00
10
101
101
2.21 1
2.22 If you do not want the print function to start a new line of output when it
finishes displaying its output, you can pass the special argument end = ' '
to the function.
The music that you play on your CD player, iPod, or MP3 player is also digital. A digital
2.23 You can pass the argument sep= to the print function, specifying the song is broken into small pieces known as samples. Each sample is converted to a binary
desired character. number, which can be stored in memory. The more samples that a song is divided into, the
2.24 It is the newline escape character. more it sounds like the original music when it is played back. A CD quality song is divided
into more than 44,000 samples per second!
2.25 It is the string concatenation operator, which joins two strings together.
2.26 65.43 Checkpoint
2.27 987,654.13 1.12 What amount of memory is enough to store a letter of the alphabet or a small
number?
2.28 (1) Named constants make programs more self-explanatory, (2) widespread
changes can easily be made to the program, and (3) they help to prevent the 1.13 What do you call a tiny “switch” that can be set to either on or off?
typographical errors that are common when using magic numbers. 1.14 In what numbering system are all numeric values written as sequences of 0s and 1s?
2.35 turtle.circle(100) CONCEPT : A computer’s CPU can only understand instructions that are written in
machine language. Because people find it very difficult to write entire
2.36 turtle.pensize(8)
programs in machine language, other programming languages have been
2.37 turtle.pencolor('blue') invented.
1.4 How a Program Works 35 708 Appendix G Answers to Checkpoints
Earlier, we stated that the CPU is the most important component in a computer because it is 1.18 Machine language
the part of the computer that runs programs. Sometimes the CPU is called the “computer’s
1.19 Main memory, or RAM
brain” and is described as being “smart.” Although these are common metaphors, you
should understand that the CPU is not a brain, and it is not smart. The CPU is an electronic 1.20 The fetch-decode-execute cycle
device that is designed to do specific things. In particular, the CPU is designed to perform
1.21 It is an alternative to machine language. Instead of using binary numbers
operations such as the following:
for instructions, assembly language uses short words that are known as
Reading a piece of data from main memory mnemonics.
Adding two numbers
1.22 A high-level language
Subtracting one number from another number
Multiplying two numbers 1.23 Syntax
Dividing one number by another number
1.24 A compiler
Moving a piece of data from one memory location to another
Determining whether one value is equal to another value 1.25 An interpreter
As you can see from this list, the CPU performs simple operations on pieces of data. The 1.26 A syntax error
CPU does nothing on its own, however. It has to be told what to do, and that’s the purpose
of a program. A program is nothing more than a list of instructions that cause the CPU to
perform operations. Chapter 2
Each instruction in a program is a command that tells the CPU to perform a specific opera- 2.1 Any person, group, or organization that is asking you to write a program
tion. Here’s an example of an instruction that might appear in a program: 2.2 A single function that the program must perform in order to satisfy the
10110000 customer
To you and me, this is only a series of 0s and 1s. To a CPU, however, this is an instruction 2.3 A set of well-defined logical steps that must be taken to perform a task
to perform an operation.1 It is written in 0s and 1s because CPUs only understand instruc- 2.4 An informal language that has no syntax rules and is not meant to be
tions that are written in machine language, and machine language instructions always have compiled or executed. Instead, programmers use pseudocode to create
an underlying binary structure. models, or “mock-ups,” of programs.
A machine language instruction exists for each operation that a CPU is capable of perform- 2.5 A diagram that graphically depicts the steps that take place in a program
ing. For example, there is an instruction for adding numbers, there is an instruction for
subtracting one number from another, and so forth. The entire set of instructions that a 2.6 Ovals are terminal symbols. Parallelograms are either output or input
CPU can execute is known as the CPU’s instruction set. symbols. Rectangles are processing symbols.
2.7 print('Jimmy Smith')
The machine language instruction that was previously shown is an example of only one
instruction. It takes a lot more than one instruction, however, for the computer to do any-
thing meaningful. Because the operations that a CPU knows how to perform are so basic in
nature, a meaningful task can be accomplished only if the CPU performs many operations.
For example, if you want your computer to calculate the amount of interest that you will
APP ENDIX
earn from your savings account this year, the CPU will have to perform a large number of
G
instructions, carried out in the proper sequence. It is not unusual for a program to contain
Answers to Checkpoints thousands or even millions of machine language instructions.
Programs are usually stored on a secondary storage device such as a disk drive. When you
install a program on your computer, the program is typically copied to your computer’s disk
drive from a CD-ROM, or downloaded from a website.
Although a program can be stored on a secondary storage device such as a disk drive,
it has to be copied into main memory, or RAM, each time the CPU executes it. For
example, suppose you have a word processing program on your computer’s disk. To
execute the program, you use the mouse to double-click the program’s icon. This causes
Chapter 1
the program to be copied from the disk into main memory. Then, the computer’s CPU
1.1 A program is a set of instructions that a computer follows to perform a task. executes the copy of the program that is in main memory. This process is illustrated in
1.2 Hardware is all the physical devices, or components, of which a computer is Figure 1-15.
made.
1.3 The central processing unit (CPU), main memory, secondary storage devices, Figure 1-15 A program is copied into main memory and then executed
input devices, and output devices
The program is copied
1.4 The CPU The CPU executes
from secondary storage
the program in
to main memory.
1.5 Main memory main memory.
Main memory
1.6 Secondary storage (RAM)
1.7 Input device
1.8 Output device
1.9 The operating system Disk drive CPU
707
1.4 How a Program Works 37
10100001
Fetch the next instruction
1
in the program.
10100001
10111000 Decode the instruction
10011110 2 to determine which
00011010 operation to perform.
11011100
and so forth... CPU
Execute the instruction
3
(perform the operation).
Main memory
(RAM)
N OTE : There are many different versions of assembly language. It was mentioned
earlier that each brand of CPU has its own machine language instruction set. Each
brand of CPU typically has its own assembly language as well.
Assembly language programs cannot be executed by the CPU, however. The CPU only
understands machine language, so a special program known as an assembler is used to
translate an assembly language program to a machine language program. This process is
shown in Figure 1-17. The machine language program that is created by the assembler can
then be executed by the CPU.
2
The first assembly language was most likely that developed in the 1940s at Cambridge University
for use with a historic computer known as the EDSAC.
38 Chapter 1 Introduction to Computers and Programming
F
mov eax, Z 10100001
add eax, 2
mov Y, eax 10111000
High-Level Languages
Although assembly language makes it unnecessary to write binary machine language instruc-
The Python standard library provides classes and functions that your programs can use to tions, it is not without difficulties. Assembly language is primarily a direct substitute for
perform basic operations, as well as many advanced tasks. There are operations, however, machine language, and like machine language, it requires that you know a lot about the
that the standard library cannot perform. When you need to do something that is beyond CPU. Assembly language also requires that you write a large number of instructions for even
the scope of the standard library, you have two choices: write the code yourself, or use code the simplest program. Because assembly language is so close in nature to machine language,
that someone else has already written. it is referred to as a low-level language.
Fortunately, there are thousands of Python modules, written by independent programmers, In the 1950s, a new generation of programming languages known as high-level languages
that provide capabilities that the standard Python library does not offer. These are known began to appear. A high-level language allows you to create powerful and complex pro-
as third-party modules. A large collection of third-party modules exists at the website pypi. grams without knowing how the CPU works and without writing large numbers of low-level
python.org, which is known as the Python Package Index, or PyPI. instructions. In addition, most high-level languages use words that are easy to understand.
For example, if a programmer were using COBOL (which was one of the early high-level
The modules that are available at PyPI are organized as packages. A package is simply a coll- languages created in the 1950s), he or she would write the following instruction to display
ection of one or more related modules. The easiest way to download and install a package the message Hello world on the computer screen:
is with the pip utility. The pip utility is a program that is part of the standard Python
installation, beginning with Python 3.4. To install a package on a Windows system with DISPLAY "Hello world"
the pip utility, you must open a command prompt window, and type a command following Python is a modern, high-level programming language that we will use in this book. In
this format: Python you would display the message Hello world with the following instruction:
pip install package_name print('Hello world')
package_name is the name of a package that you want to download and install. If you are
Doing the same thing in assembly language would require several instructions and an inti-
running a Mac or a Linux system, you must use the pip3 command instead of the pip com-
mate knowledge of how the CPU interacts with the computer’s output device. As you can see
mand. In addition, you will need superuser privileges to execute the pip3 command on a
from this example, high-level languages allow programmers to concentrate on the tasks they
Mac or Linux system, so you will have to prefix the command with sudo, as shown here: want to perform with their programs, rather than the details of how the CPU will execute
sudo pip3 install package_name those programs.
Once you enter the command, the pip utility will start downloading and installing the Since the 1950s, thousands of high-level languages have been created. Table 1-1 lists several
package. Depending on the size of the package, it may take a few minutes to complete the of the more well-known languages.
installation process. Once the process is finished, you can typically verify that the package
was correctly installed by starting IDLE and entering the command
Key Words, Operators, and Syntax: An Overview
>>> import package_name
Each high-level language has its own set of predefined words that the programmer must
where package_name is the name of the package that you installed. If you do not see an use to write a program. The words that make up a high-level programming language are
error message, you can assume the package was successfully installed. known as key words or reserved words. Each key word has a specific meaning, and cannot
In Chapter 7, you will explore a popular third-party package named matplotlib. You can be used for any other purpose. Table 1-2 shows all of the Python key words.
use the matplotlib package to create charts and graphs.
705
1.4 How a Program Works 39
Using an Alias In addition to key words, programming languages have operators that perform various
operations on data. For example, all programming languages have math operators that
You can use the as keyword to assign an alias to a module when you import it. The follow- perform arithmetic. In Python, as well as most other languages, the + sign is an operator
ing statement shows an example: that adds two numbers. The following adds 12 and 75:
import math as mt 12 + 75
This statement loads the math module into memory, assigning the module the alias mt. There are numerous other operators in the Python language, many of which you will learn
To use any of the items that are in the module, you prefix the item’s name with the alias, about as you progress through this text.
followed by a dot. For example, to call the sqrt function, you would use the name
mt.sqrt. The following interactive session shows an example: In addition to key words and operators, each language also has its own syntax, which is a
set of rules that must be strictly followed when writing a program. The syntax rules dictate
>>> import math as mt how key words, operators, and various punctuation characters must be used in a program.
>>> x = mt.sqrt(25) When you are learning a programming language, you must learn the syntax rules for that
>>> a = mt.radians(180) particular language.
>>> print(x)
5.0 The individual instructions that you use to write a program in a high-level programming
>>> print(a) language are called statements. A programming statement can consist of key words, oper-
3.141592653589793 ators, punctuation, and other allowable programming elements, arranged in the proper
>>> sequence to perform an operation.
You can also assign an alias to a specific function or class when you import it. The follow-
ing statement imports the sqrt function from the math module, and assigns the function Compilers and Interpreters
the alias square_root:
Because the CPU understands only machine language instructions, programs that are writ-
from math import sqrt as square_root ten in a high-level language must be translated into machine language. Depending on the
language in which a program has been written, the programmer will use either a compiler
After using this import statement, you would use the name square_root to call the sqrt
or an interpreter to make the translation.
function. The following interactive session shows an example:
A compiler is a program that translates a high-level language program into a separate
>>> from math import sqrt as square_root
machine language program. The machine language program can then be executed any time
>>> x = square_root(25)
it is needed. This is shown in Figure 1-18. As shown in the figure, compiling and executing
>>> print(x)
are two different processes.
5.0
>>> Figure 1-18 Compiling a high-level program and executing it
In the following interactive session, we import two functions from the math module, giving
High-level language Machine language
each of them an alias. The sqrt function is imported as square_root, and the tan func- program
program
tion is imported as tangent:
The compiler is used 10100001
print ("Hello
>>> from math import sqrt as square_root, tan as tangent 1 to translate the high-level Earthling") 10111000
language program to a Compiler
>>> x = square_root(25) 10011110
machine language program. and so forth... and so forth...
>>> y = tangent(45)
>>> print(x)
5.0
>>> print(y)
1.6197751905438615
Machine language
CPU
program
The machine language 10100001
2 program can be executed 10111000
at any time, without using 10011110
the compiler. and so forth...
1.4 How a Program Works 41 702 Appendix E More About the import Statement
The Python language uses an interpreter, which is a program that both translates and This statement causes only the sqrt function to be imported from the math module. It also
executes the instructions in a high-level language program. As the interpreter reads allows you to call the sqrt function without prefixing the function’s name with the name
each individual instruction in the program, it converts it to machine language instruc- of the module. The following interactive session shows an example:
tions then immediately executes them. This process repeats for every instruction in
>>> from math import sqrt
the program. This process is illustrated in Figure 1-19. Because interpreters combine
>>> x = sqrt(25)
translation and execution, they typically do not create separate machine language
>>> print(x)
programs.
5.0
>>>
Figure 1-19 Executing a high-level program with an interpreter You can specify the names of multiple items, separated with commas, when you use this
form of the import statement. For example, the import statement in the following interac-
High-level language tive session imports only the sqrt function and the radians function from the math
program CPU module:
Machine language
print ("Hello instruction
>>> from math import sqrt, radians
Earthling") Interpreter 10100001
>>> x = sqrt(25)
and so forth... >>> a = radians(180)
>>> print(x)
5.0
The interpreter translates each high-level instruction to
>>> print(a)
its equivalent machine language instructions then 3.141592653589793
immediately executes them. >>>
This process is repeated for each high-level instruction.
Wildcard Imports
The statements that a programmer writes in a high-level language are called source A wildcard import statement loads the entire contents of a module. Here is an example:
code, or simply code. Typically, the programmer types a program’s code into a text
editor then saves the code in a file on the computer’s disk. Next, the programmer uses from math import *
a compiler to translate the code into a machine language program, or an interpreter to The difference between this statement and the import math statement is that the wildcard
translate and execute the code. If the code contains a syntax error, however, it cannot import statement does not require you to use the qualified names of the items in the mod-
be translated. A syntax error is a mistake such as a misspelled key word, a missing ule. For example, here is an interactive session that uses a wildcard import statement:
punctuation character, or the incorrect use of an operator. When this happens, the
compiler or interpreter displays an error message indicating that the program contains >>> from math import*
a syntax error. The programmer corrects the error then attempts once again to translate >>> x = sqrt(25)
the program. >>> a = radians(180)
>>>
And, here is an interactive session that uses the regular import statement:
N OTE : Human languages also have syntax rules. Do you remember when you took >>> import math
your first English class, and you learned all those rules about commas, apostrophes, >>> x = math.sqrt(25)
capitalization, and so forth? You were learning the syntax of the English language. >>> a = math.radians(180)
>>>
Although people commonly violate the syntax rules of their native language when
speaking and writing, other people usually understand what they mean. Unfortunately, Typically, you should avoid using the wildcard import statement because it can lead to
compilers and interpreters do not have this ability. If even a single syntax error appears name clashes when you are importing several modules. A name clash occurs when a
in a program, the program cannot be compiled or executed. When an interpreter program imports two modules that have functions or classes with the same name. Name
encounters a syntax error, it stops executing the program. clashes do not occur when you are using the qualified names of a module’s functions
and/or classes.
42 Chapter 1 Introduction to Computers and Programming
Checkpoint
1.18 A CPU understands instructions that are written only in what language?
1.19 A program has to be copied into what type of memory each time the CPU
executes it?
1.20 When a CPU executes the instructions in a program, it is engaged in what process?
More About the import
APP ENDIX
E
1.21 What is assembly language?
1.22 What type of programming language allows you to create powerful and complex
Statement 1.23
programs without knowing how the CPU works?
Each language has a set of rules that must be strictly followed when writing a
program. What is this set of rules called?
1.24 What do you call a program that translates a high-level language program into a
separate machine language program?
1.25 What do you call a program that both translates and executes the instructions in
A module is a Python source code file that contains functions and/or classes. Many of the a high-level language program?
functions in the Python standard library are stored in modules. For example, the math mod- 1.26 What type of mistake is usually caused by a misspelled key word, a missing
ule contains various mathematical functions, and the random module contains functions for punctuation character, or the incorrect use of an operator?
working with random numbers.
In order to use the functions and/or classes that are stored in a module, you must import the
module. To import a module, you write an import statement at the top of your program.
1.5 Using Python
Here is an import statement that imports the math module:
CONCEPT : The Python interpreter can run Python programs that are saved in files
import math
or interactively execute Python statements that are typed at the keyboard.
This statement causes the Python interpreter to load the contents of the math module into Python comes with a program named IDLE that simplifies the process of
memory, making the functions and/or classes that are stored in the math module available writing, executing, and testing programs.
to the program. To use any item that is in the module, you must use the item’s qualified
name. This means that you must prefix the item’s name with the name of the module, fol-
lowed by a dot. For example, the math module has a function named sqrt that returns the Installing Python
square root of a number. To call the sqrt function, you would use the name math.sqrt. Before you can try any of the programs shown in this book, or write any programs of your
The following interactive session shows an example: own, you need to make sure that Python is installed on your computer and properly con-
>>> import math
figured. If you are working in a computer lab, this has probably been done already. If you
>>> x = math.sqrt(25)
are using your own computer, you can follow the instructions in Appendix A to download
>>> print(x)
and install Python.
5.0
>>> The Python Interpreter
You learned earlier that Python is an interpreted language. When you install the Python
language on your computer, one of the items that is installed is the Python interpreter. The
Importing a Specific Function or Class Python interpreter is a program that can read Python programming statements and execute
The previously shown form of the import statement loads the entire contents of a module them. (Sometimes, we will refer to the Python interpreter simply as the interpreter.)
into memory. Sometimes you want to import only a specific function or class from a mod-
You can use the interpreter in two modes: interactive mode and script mode. In interac-
ule. When this is the case, you can use the from keyword with the import statement, as
tive mode, the interpreter waits for you to type Python statements on the keyboard. Once
shown here:
you type a statement, the interpreter executes it and then waits for you to type another
from math import sqrt statement. In script mode, the interpreter reads the contents of a file that contains Python
statements. Such a file is known as a Python program or a Python script. The interpreter
executes each statement in the Python program as it reads it.
701
1.5 Using Python 43
Interactive Mode
Once Python has been installed and set up on your system, you start the interpreter in
interactive mode by going to the operating system’s command line and typing the follow-
ing command:
python
If you are using Windows, you can alternatively type python in the Windows search box.
In the search results, you will see a program named something like Python 3.5. (The “3.5”
is the version of Python that is installed. At the time this is being written, Python 3.5 is
the latest version.) Clicking this item will start the Python interpreter in interactive mode.
When the Python interpreter starts in interactive mode, you will see something like the fol-
lowing displayed in a console window:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48)
[MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license"
for more information. This page intentionally left blank
>>>
The >>> that you see is a prompt that indicates the interpreter is waiting for you to type
a Python statement. Let’s try it out. One of the simplest things that you can do in Python
is print a message on the screen. For example, the following statement prints the message
Python programming is fun! on the screen:
print('Python programming is fun!')
You can think of this as a command that you are sending to the Python interpreter. If
you type the statement exactly as it is shown, the message Python programming is fun! is
printed on the screen. Here is an example of how you type this statement at the interpreter’s
prompt:
>>> print('Python programming is fun!') Enter
After typing the statement, you press the Enter key, and the Python interpreter executes the
statement, as shown here:
>>> print('Python programming is fun!') Enter
Python programming is fun!
>>>
Appendix D Predefined Named Colors 699 44 Chapter 1 Introduction to Computers and Programming
'gray3' 'gray4' 'gray5' After the message is displayed, the >>> prompt appears again, indicating the interpreter is
'gray6' 'gray7' 'gray8' waiting for you to enter another statement. Let’s look at another example. In the following
sample session, we have entered two statements:
'gray9' 'gray10' 'gray11'
>>> print('To be or not to be') Enter
'gray12' 'gray13' 'gray14'
To be or not to be
'gray15' 'gray16' 'gray17' >>> print('That is the question.') Enter
'gray18' 'gray19' 'gray20' That is the question.
>>>
'gray21' 'gray22' 'gray23'
'gray24' 'gray25' 'gray26' If you incorrectly type a statement in interactive mode, the interpreter will display an error
message. This will make interactive mode useful to you while you learn Python. As you
'gray27' 'gray28' 'gray29'
learn new parts of the Python language, you can try them out in interactive mode and get
'gray30' 'gray31' 'gray32' immediate feedback from the interpreter.
'gray33' 'gray34' 'gray35' To quit the Python interpreter in interactive mode on a Windows computer, press Ctrl-Z
'gray36' 'gray37' 'gray38' (pressing both keys together) followed by Enter. On a Mac, Linux, or UNIX computer,
press Ctrl-D.
'gray39' 'gray40' 'gray42'
'gray43' 'gray44' 'gray45'
'gray46' 'gray47' 'gray48' N O TE : In Chapter 2, we will discuss the details of statements like the ones previously
shown. If you want to try them now in interactive mode, make sure you type them exactly
'gray49' 'gray50' 'gray51'
as shown.
'gray52' 'gray53' 'gray54'
'gray55' 'gray56' 'gray57'
'gray58' 'gray59' 'gray60' Writing Python Programs and Running
'gray61' 'gray62' 'gray63' Them in Script Mode
'gray64' 'gray65' 'gray66' Although interactive mode is useful for testing code, the statements that you enter in interac-
tive mode are not saved as a program. They are simply executed and their results displayed on
'gray67' 'gray68' 'gray69'
the screen. If you want to save a set of Python statements as a program, you save those state-
'gray70' 'gray71' 'gray72' ments in a file. Then, to execute the program, you use the Python interpreter in script mode.
'gray73' 'gray74' 'gray75' For example, suppose you want to write a Python program that displays the following three
'gray76' 'gray77' 'gray78' lines of text:
'gray79' 'gray80' 'gray81' Nudge nudge
'gray82' 'gray83' 'gray84' Wink wink
Know what I mean?
'gray85' 'gray86' 'gray87'
'gray88' 'gray89' 'gray90'
To write the program you would use a simple text editor like Notepad (which is installed
on all Windows computers) to create a file containing the following statements:
'gray91' 'gray92' 'gray93'
print('Nudge nudge')
'gray94' 'gray95' 'gray97'
print('Wink wink')
'gray98' 'gray99' print('Know what I mean?')
N O TE : It is possible to use a word processor to create a Python program, but you must
be sure to save the program as a plain text file. Otherwise, the Python interpreter will
not be able to read its contents.
GLOBAL GLOBAL
EDITION EDITION
RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO
THIS INFORMATION, INCLUDING ALL WARRANTIES AND CONDITIONS OF MERCHANTABILITY,
Digital Resources for Students WHETHER EXPRESS, IMPLIED OR STATUTORY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
Your new textbook provides 12-month access to digital resources that may include WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
VideoNotes (step-by-step video tutorials on programming concepts), source code, web
WITH THE USE OR PERFORMANCE OF INFORMATION AVAILABLE FROM THE SERVICES. THE
chapters, quizzes, and more. Refer to the preface in the textbook for a detailed list of DOCUMENTS AND RELATED GRAPHICS CONTAINED HEREIN COULD INCLUDE TECHNICAL
resources. INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO
THE INFORMATION HEREIN. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS MAY MAKE
Follow the instructions below to register for the Companion Website for Tony Gaddis’ IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED
Starting Out with Python, Fourth Edition, Global Edition. HEREIN AT ANY TIME. PARTIAL SCREEN SHOTS MAY BE VIEWED IN FULL WITHIN THE SOFTWARE
VERSION SPECIFIED.
1. Go to www.pearsonglobaleditions.com/gaddis
2. Enter the title of your textbook or browse by author name.
3. Click Companion Website.
4. Click Register and follow the on-screen instructions to create a login name
and password.
ISSGPY-PRANK-CURRY-PIQUE-METIS-ROUSE
Use the login name and password you created during registration to start using the
online resources that accompany your textbook.
IMPORTANT:
This prepaid subscription does not include access to MyProgrammingLab, which is
available at www.myprogramminglab.com for purchase.
This subscription is valid for 12 months upon activation and is not transferable.
743
742 Index
P
defined, 261 Widgets
general format, 272 arrangement of, 630
how to use, 274–276 Button, 622, 630–633
®
and IPO charts, 276–277 Canvas, 622
randint and, 263–266 Checkbutton, 622, 648–650
random number generation, 262–271 defined, 622
randrange and, 269–270 Entry, 622, 633–636
returning multiple values, 282–283 Frame, 622, 629
return statement, 272–274 with frames, organizing, 627–630
for simplifying mathematical expressions, 274–276 Label, 622, 625–626, 629, 636–640
values, 261, 274 Listbox, 622
void functions and, 233 list of, 641
F OUR TH ED ITION writing, 272–283
Values
Menu, 622
Menubutton, 622
P
str data type, 69–70 as base classes, 574
str function defined, 574
defined, 326 in UML diagrams, 582–583
®
example use, 323 writing, 575
String comparisons, 144–147, 444–445, 463, 464 Supersets, 492
String concatenation SUV class, 580–581
defined, 90, 434 Symbols, flowchart, 56
example, 90 symmetric_difference method, 491
interactive sessions, 434 Symmetric difference of sets, 491
newline to, 319–320 Syntax
with + operator, 90 defined, 40
with += operator, 435 human language, 41
F OUR TH ED ITION String literals
defined, 59
Syntax errors
correcting, 54
GLOBA L EDITION enclosing in triple quotes, 60
Strings
defined, 41
reporting, 691
characters, accessing, 430–434 running programs and, 691
comparing, 144–148 System software, 28–29
defined, 59
extracting characters from, 438–440 T
as immutable, 435–436 tan() function, 285
Tony Gaddis
indexes, 432–433 Target variables
iterating with for loop, 430–432 defined, 192
list of, 366 inside for loops, 194–196
Haywood Community College method call format, 442 use example, 195
modification methods, 444–445 Terminal symbols, 56
operations, 429–436 Testing
raw, 314 dictionary values, 463–464
reading as input, 429 programs, 54–55
repetition operator (*) with, 450–451 set values, 488–489
returning, 280 string methods, 442–443
search and replace methods, 445–446 strings, 441
slicing, 437–438 Text
space character at end, 73 drawing with Canvas widget, 667–672
splitting, 451–452 displaying with Label widget, 624–627
storing with str data type, 69–70 editing, 687–688
stripping newline from, 320–322 font setting, 670–672
testing, 441 Text files
testing methods, 442–443 defined, 311
writing as output, 429 reading numbers from, 324
written to files, 316 Text widget, 622
StringVar object, 636–637 third-party modules, 705
strip() method, 444 Tkinter module
Stripping newline from string, 320–322 defined, 621
Structure charts. See Hierarchy charts programs using, 622
Subclasses widgets, 622
defined, 574 Top-down design
as derived classes, 574 defined, 240
method override, 588 process, 240–241
�)è“ÜÊÃ�ZãØ——ã �B—ô�xÊع �Bx�
Index 739
Running programs, 690–691 set method, 640, 647 Senior Vice President Courseware Portfolio Management: Marcia J. Horton
Running totals Sets Director, Portfolio Management: Engineering,
calculating, 201–204 adding elements, 486–487 Computer Science & Global Editions: Julian Partridge
defined, 201 creating, 485
Portfolio Manager: Matt Goldstein
elements for calculating, 201 defined, 484
example, 202 difference of, 490–491
Acquisitions Editor, Global Edition: Sourabh Maheshwari
logic for calculating, 201 duplicate elements, 485 Portfolio Management Assistant: Kristy Alaura
elements, as unique, 484 Field Marketing Manager: Demetrius Hall
S elements, number of, 486 Product Marketing Manager: Yvonne Vannatta
Samples, 34 elements, removing, 487–488 Managing Producer, ECS and Math: Scott Disanno
Saving programs, 690 intersection of, 490 Content Producer: Sandra L. Rodriguez
SavingsAccount class, 584, 585 for loop iteration over, 488
Project Editors, Global Edition: Tanima Ghosh and Neelakantan K.K.
Scale widget, 622 operations, 493–495
Scientific notation, 92 subsets, 492
Senior Manufacturing Controller, Global Edition: Jerry Kataria
Scope supersets, 492 Manager, Media Production, Global Edition: Vikram Kumar
defined, 245 symmetric difference of, 491 Cover Designer: Lumina Datamatics
local variables and, 245–247 union of, 489 Cover Photo: Africa Studio/Shutterstock
parameter variable, 249 unordered, 484
Credits and acknowledgments borrowed from other sources and reproduced, with permission, appear
Script mode, running programs in, 45 values, testing, 488–489
Scrollbar widget, 622 Settings. See Mutator methods
on the Credits page in the endmatter of this textbook.
Searching Showinfo function, 630 Pearson Education Limited
lists, 376–377 sin() function, 285
KAO Two
records, 339–341 Single alternative decision structures, 132
strings, 445–446 Slices KAO Park
Secondary storage defined, 373 Harlow
defined, 27 example use, 373–375 CM17 9NA
devices, 27–28 general format, 373 United Kingdom
Seeds, random number, 270–271 invalid indexes and, 375
Seed value, 270 list, 373–376 and Associated Companies throughout the world
Selection structures. See Decision structures start and end index, 374
Visit us on the World Wide Web at: www.pearsonglobaleditions.com
Sentinels string, 437–438
defined, 204, 205 Software © Pearson Education Limited 2019
using, 205–206 application, 29
values, 204–205 defined, 23 The rights of Tony Gaddis to be identified as the author of this work has been asserted by him in accor-
Separators developers. See Programmers dance with the Copyright, Designs and Patents Act 1988.
comma, 92–93 development tools, 29
item, 88–89 operating system, 28 Authorized adaptation from the United States edition, entitled Starting Out with Python, 4th Edition,
split method, 451–452 requirements, 55 ISBN 978-0-13-444432-1 by Tony Gaddis, published by Pearson Education © 2018.
Sequences. See also Lists system, 28–29
accepting as argument, 383–384 types of, 28 All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted
defined, 365 utility programs, 28 in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without either
length, returning, 369 Sorting, item list, 381–382 the prior written permission of the publisher or a license permitting restricted copying in the United Kingdom
tuples, 402–404 sort method, 378, 381–382
issued by the Copyright Licensing Agency Ltd, Sa ron House, 6–10 Kirby Street, London EC1N 8TS.
Sequence structures Source code. See Code
with decision structure, 147 Specialization, 573–574 All trademarks used herein are the property of their respective owners. The use of any trademark in this
defined, 131 split method, 451 text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor
example, 131 Splitting strings, 451–452
does the use of such trademarks imply any a liation with or endorsement of this book by such owners.
nested inside decision structure, 148 sqrt() function, 285
structure, 147, 148 startswith method, 445, 446
British Library Cataloguing-in-Publication Data
use in programming, 131–132 Statements
Serializing objects for, 190, 194, 196 A catalogue record for this book is available from the British Library
defined, 496 assignment, 62–65
10 9 8 7 6 5 4 3 2 1
example, 498–500, 542–544 in blocks, 133, 235
pickle module, 496–497 breaking into multiple lines, 86–87 ISBN 10: 1-292-22575-0
unserializing, 500–502, 543–544 converting math formulas to, 83–85 ISBN 13: 978-1-292-22575-3
ServiceQuote class, 563–565 defined, 40
set function, 485 del, 383 Typeset by iEnergizer Aptara®, Ltd.
Printed and bound in Malaysia
738 Index
7
Index 735 8 Contents
Chapter 8 More About Strings 429 not operator, 155, 157 multiplication (*), 76, 79, 367
8.1 Basic String Operations 429 Nouns, list refining, 557–560 not in. See Not in operator
8.2 String Slicing 437 Numbers or, 155–157, 159, 160
advanced storage, 34 precedence, 79
8.3 Testing, Searching, and Manipulating Strings 441
binary, 31–32 relational, 133–134, 145–146
Review Questions 453 factorial of, 603–605 remainder (%), 76, 79, 82–83
Programming Exercises 456 Fibonacci, 607–609 repetition (*), 367, 450–451
floating-point, 33, 94 subtraction (−), 76, 79
Chapter 9 Dictionaries and Sets 461 formatting, 90–91 Optical devices, 28
9.1 Dictionaries 461 pseudorandom, 270–271 or operator, 155–157, 159, 160
9.2 Sets 484 random, 262–271 Output
9.3 Serializing Objects 496 running totals, 201–204 in computer program process, 57–58
storage, 31–33 data, 87–95
Review Questions 502
Numeric literals, 69 defined, 28
Programming Exercises 507 Numeric ranges, with logical operators, 160 displaying, 58–61
Output devices, 28
Chapter 10 Classes and Object-Oriented Programming 511 Output files, 310, 311, 315, 322, 326
10.1 Procedural and Object-Oriented Programming 511 O
Overhead, 602
Object-oriented programming (OOP)
10.2 Classes 515 class design, 554–565
Overriding, method, 588
10.3 Working with Instances 532 classes, 515–532
10.4 Techniques for Designing Classes 554 data hiding, 512
P
pack method, 625–627, 629, 634
Review Questions 565 defined, 512
Parameter lists, 252
Programming Exercises 568 encapsulation, 512
Parentheses, grouping with, 80
instances, 515, 532–554
Pascal, 39
Chapter 11 Inheritance 573 Objects, 629. See also Classes
Passing arguments. See also Arguments
11.1 Introduction to Inheritance 573 characteristics description, 515
to function, 248–251
11.2 Polymorphism 588 defined, 512
function parameter variable, 253–255
dictionary, 461–484
Review Questions 594 to index method, 379–381
everyday example of, 513–514
Programming Exercises 596 list as function, 389–390
exception, 359 multiple, 251–253
file, 316–317 and objects, 540–541
Chapter 12 Recursion 599 list, 365, 366 by position, 252
12.1 Introduction to Recursion 599 “is a” relationship, 574 by value, 255
12.2 Problem Solving with Recursion 602 passing as arguments, 540–541 Passwords, validating characters in, 446–449
12.3 Examples of Recursive Algorithms 606 pickling, 542–544 Pattern printing using nested loops, 215–218
Review Questions 614 reusability, 513 Percentages, calculations, 77–78
Programming Exercises 616 sequence, 365 Pickle module, 497–498, 542, 547
serializing, 496–502 Pickling, 496–498, 500, 542–544
Chapter 13 GUI Programming 619 set, 484–496 pi variable, 285
storing in dictionaries, 544–554 pie chart, plotting, 418–420
13.1 Graphical User Interfaces 619
storing in lists, 538–540 pip utility, 705
13.2 Using the tkinter Module 621 StringVar, 636–637 Pixels, 34
13.3 Display Text with Label Widgets 624 unpickling, 543–544 plot() function, 406–407
13.4 Organizing Widgets with Frames 627 open function, 313, 314, 318 Polymorphism
13.5 Button Widgets and Info Dialog Boxes 630 Operands, 76 behavior, ingredients of, 588
13.6 Getting Input with the Entry Widget 633 Operating systems, 28 defined, 588
Operators isinstance function, 591–594
13.7 Using Labels as Output Fields 636
and, 156–158 popitem method, 473, 477
13.8 Radio Buttons and Check Buttons 644 in. See In operator pop method, 472, 720
13.9 Drawing Shapes with the Canvas Widget 651 addition (+), 76, 79, 90 Positional arguments, 257
Review Questions 673 assignment, 135, 203–204 Precedence, operator, 79
Programming Exercises 676 augmented assignment, 203–204 Predefined names colors, 695–699
exponent (**), 76, 80–82 Pretest loops
logical. See Logical operators defined, 186
math, 75–76 while loops as, 186–187
Index 733 10 Contents
Error handlers, 209 defined, 607–608 The new Turtle Graphics sections are designed with flexibility in mind. They can be
Error messages, 41, 44 recursive function calculation, 608–609 assigned as optional material, incorporated into your existing syllabus, or skipped
default, displaying, 355–356 Field widths
altogether.
loop displaying, 208–209 columns, 93
traceback, 349, 351 minimum, specifying, 93–94 ● Chapter 2 has a new section on named constants. Although Python does not support
Errors. See Exceptions File modes, 317 true constants, you can create variable names that symbolize values that should not
Error traps, 209 Filename extensions, 312
change as the program executes. This section teaches the student to avoid the use
Escape characters, 89–90 File objects
Event handlers, callback functions as, 630 close method, 315, 497 of “magic numbers,” and to create symbolic names that make his or her code more
Exception handling defined, 312 self-documenting and easier to maintain.
defined, 352 read method, 316–319 ● Chapter 7 has a new section on using the matplotlib package to plot charts and graphs
multiple exceptions, 352–355 variable name referencing, 312–314 from lists. The new section describes how to install the matplotlib package, and use it to
with try/except statement, 357–358 writelines method, 395–398
plot line graphs, bar charts, and pie charts.
Exception objects, 359 write method, 314
Exceptions finally clause, with try/except statement, 358
● Chapter 13 has a new section on creating graphics in a GUI application with the
catching all, with one except clause, 354–355 Finally suite, 358 Canvas widget. The new section describes how to use the Canvas widget to draw lines,
code response to, 348 find method, 446 rectangles, ovals, arcs, polygons, and text.
default error message display, 355–356 Flags, 162 ● Several new, more challenging, programming problems have been added throughout
defined, 75, 346 Flash drives, 28 the book.
IndexError, 368–369, 433 Flash memory, 28
IOError, 351–352, 354, 358 float data type, 69, 85–86
● Appendix E is a new appendix that discusses the various forms of the import statement.
KeyError, 463, 465, 487 float() function, 73, 74, 75, 86
● Appendix F is a new appendix that discusses installing third-party modules with the
multiple, 352–354 Floating-point division, 78, 79 pip utility.
unhandled, 358–359 Floating-point notation, 33
ValueError, 349–350, 354, 355, Floating-point numbers, 94
356, 358, 382 floor() function, 285 Brief Overview of Each Chapter
ZeroDivisionError, 358 Floppy disk drives, 27
Execution, 223 Flowchart, 56
in fetch-decode-execute cycle, 36 clock simulator, 213
Chapter 1: Introduction to Computers and Programming
pausing, 244 decision structure, 132, 133, 137 This chapter begins by giving a very concrete and easy-to-understand explanation of how
Python interpreter, 686–687 dual alternative decision structure, 130
computers work, how data is stored and manipulated, and why we write programs in high-
try/except statement, 349 input validation loop, 208
while loop, 209 logic for file end detection, 328 level languages. An introduction to Python, interactive mode, script mode, and the IDLE
Exercises nested decision structure, 149, 152 environment are also given.
decision structures, 173–179 pay calculating program, 57
dictionaries and sets, 507–510 program development cycle, 53
files and exceptions, 366–368 running total calculation, 201 Chapter 2: Input, Processing, and Output
functions, 302–308 sequence structure nested inside decision
This chapter introduces the program development cycle, variables, data types, and simple
GUI programming, 676–679 structure, 148
inheritance, 596–597 sequence structures with decision structure, 147–148 programs that are written as sequence structures. The student learns to write simple pro-
input, processing, and output, 126–130 while loop, 183 grams that read input from the keyboard, perform mathematical operations, and produce
introduction, 50–51 Font class, 670–672 screen output. Pseudocode and flowcharts are also introduced as tools for designing pro-
lists and tuples, 424–428 keyword arguments for, 671 grams. The chapter also includes an optional introduction to the turtle graphics library.
programming, 568–572 for loops. See also Loops
recursion, 616–617 as count-controlled loops, 190–200
repetition structures, 265–267 defined, 190–191 Chapter 3: Decision Structures and Boolean Logic
strings, 456–460 in turtle graphics, 219
exp() function, 285 iterating lists with, 368 In this chapter, the student learns about relational operators and Boolean expressions and is
Exponent (**) operator, 76, 80–82 iterating over dictionaries with, 468–469 shown how to control the flow of a program with decision structures. The if, if-else, and
iterating over list of strings with, 192 if-elif-else statements are covered. Nested decision structures and logical operators are
F iterating over sets, 488
discussed as well. The chapter also includes an optional turtle graphics section, with a discus-
Factorial function, 604–605 iterations, 198–200
Factorials iterations, user control, 198–200 sion of how to use decision structures to test the state of the turtle.
calculation with recursion, 602–606 range function with, 190–194
definition rules, 606, 609 target variables, 194–198
Fetch-decode-execute cycle, 36–37 format function, 91, 94
Chapter 4: Repetition Structures
Fibonacci series Format specifiers, 91–94 This chapter shows the student how to create repetition structures using the while loop and
for loop. Counters, accumulators, running totals, and sentinels are discussed, as well as
Preface 15 728 Index
techniques for writing input validation loops. The chapter also includes an optional section create_polygon method, 665–667 defined, 461
on using loops to draw designs with the turtle graphics library. optional arguments to, 667 elements, adding, 464
create_rectangle method, 655–657 elements, deleting, 465, 469
optional arguments to, 657 elements, display order, 462
Chapter 5: Functions create_text method, 667–672 elements, number of, 465–466
optional arguments to, 669 empty, creating, 467–468
In this chapter, the student first learns how to write and call void functions. The chapter C# programming language, 39 example, 474–477, 477–483
shows the benefits of using functions to modularize programs and discusses the top-down Customer class, 561–562 iteration, 468–469
design approach. Then, the student learns to pass arguments to functions. Common library keys, 461, 462
functions, such as those for generating random numbers, are discussed. After learning how D key-value pairs, 461, 464
Data methods, 469–474
to call library functions and use their return value, the student learns to define and call his mixing data types in, 466–467
appending to files, 322
or her own functions. Then the student learns how to use modules to organize functions. An binary file, 311 parts of, 461
optional section includes a discussion of modularizing turtle graphics code with functions. digital, 34 retrieving value from, 462–463
hiding, 512 storing objects in, 544–554
output, 87–95 values, 463–464
Chapter 6: Files and Exceptions processing, 333–346 Dictionary views
reading from files, 310–311, 316–319 defined, 470
This chapter introduces sequential file input and output. The student learns to read and write
text file, 311 elements, 470
large sets of data and store data as fields and records. The chapter concludes by discussing keys returned as, 471
writing to files, 310, 314–316
exceptions and shows the student how to write exception-handling code. Data attributes, 512 values returned as, 473–474
hidden, 513 dict() method, 468
hiding, 522–525 difference method, 490–491
Chapter 7: Lists and Tuples Digital data, 34
initializing, 518
This chapter introduces the student to the concept of a sequence in Python and explores the instance, 532–554 Digital devices, 34
Data storage, 29–33 Direct access files, 312, 343, 346
use of two common Python sequences: lists and tuples. The student learns to use lists for
characters, 33 Direct recursion, 606
arraylike operations, such as storing objects in a list, iterating over a list, searching for items music, 34 discard method, 487
in a list, and calculating the sum and average of items in a list. The chapter discusses slic- Data types Disk drives
ing and many of the list methods. One- and two-dimensional lists are covered. The chapter bool, 161 defined, 27
also includes a discussion of the matplotlib package, and how to use it to plot charts and conversion and mixed-type expressions, 85–86 program storage on, 36
graphs from lists. and literals, 68–69 Divide and conquer approach, 232
mixing, 466–467 Division
str, 69–70 floating-point, 78
Chapter 8: More About Strings Debugging, 54, 154 integer, 76, 78
global variables and, 258–259 / operator, 76, 78, 79
In this chapter, the student learns to process strings at a detailed level. String slicing and Decision structures, 132 Dog class, 589–590
algorithms that step through the individual characters in a string are discussed, and several actions performed in, 132–133 Dot notation, 263, 285
built-in functions and string methods for character and text processing are introduced. combining sequence structures with, 147–148 Dual alternative decision structure,
dual alternative, 140 139–140
in flowcharts, 132 dump method, 497
Chapter 9: Dictionaries and Sets if-elif-else statement, 153–154 DVD drives, 28
if-else statement, 140–143 DVDs (digital versatile discs), 28
This chapter introduces the dictionary and set data structures. The student learns to store data if statement, 131–139
as key-value pairs in dictionaries, search for values, change existing values, add new key-value inside, 148 E
pairs, and delete key-value pairs. The student learns to store values as unique elements in sets nested, 147–155 else clause, 143, 150
and perform common set operations such as union, intersection, di erence, and symmetric single alternative, 132 execution, 140
degrees() function, 285 with try/except statement, 357–358
di erence. The chapter concludes with a discussion of object serialization and introduces the
del statement, 383 else suite, 357
student to the Python pickle module. Depth of recursion, 602 Encapsulation, 512
Derived classes, 574 end–of–file, 500–501, 543
Chapter 10: Classes and Object-Oriented Programming Dialog boxes endswith method, 445, 446
defined, 619 ENIAC computer, 25, 26
This chapter compares procedural and object-oriented programming practices. It covers the illustrated, 620–621 Entry widget
fundamental concepts of classes and objects. Attributes, methods, encapsulation and data info, 630–633 defined, 622, 633
Dictionaries getting input with, 633–636
hiding, _ _init_ _ functions (which are similar to constructors), accessors, and mutators are
creating, 462 use example, 634–636
discussed. The student learns how to model classes with UML and how to find the classes
in a particular problem.
Index 727 16 Preface
VideoNotes Online videos developed specifically for this book are available
for viewing at www.pearsonglobaleditions.com/gaddis. Icons appear
throughout the text alerting the student to videos about specific
topics.
Notes Notes appear at several places throughout the text. They are
short explanations of interesting or often misunderstood points
relevant to the topic at hand.
Index Tips Tips advise the student on the best techniques for approaching
di erent programming problems.
Warnings Warnings caution students about programming techniques or
practices that can lead to malfunctioning programs or lost data.
Checkpoints Checkpoints are questions placed at intervals throughout each
chapter. They are designed to query the student’s knowledge
Symbols defined, 134 quickly after learning a new topic.
!= operator in string comparisons, 144
defined, 136 use example, 138 Review Questions Each chapter presents a thorough and diverse set of review
example use, 136, 138 > operator questions and exercises. They include Multiple Choice, True/
" (double-quote marks), 60 defined, 134 False, Algorithm Workbench, and Short Answer.
""" or "' (triple quotes), 60 in string comparisons, 146
# character, 61 use example, 134, 135–136 Programming Each chapter o ers a pool of programming exercises designed
% (remainder) operator >= operator Exercises to solidify the student’s knowledge of the topics currently being
defined, 76, 82 defined, 134 studied.
function of, 281 in superset determination, 492
%= operator, 203 relationship testing, 135
& operator, for intersection of sets, 490 >>> prompt, 43, 44
Supplements
' (single-quote marks), 59–60 ^ operator, 491
* operator _ _init_ _ method, 521, 555, 561, 563, 583 Student Online Resources
multiplication, 76 {}(curly braces), 462
Many student resources are available for this book from the publisher. The following items
repetition, 367
are available at www.pearsonglobaleditions.com/gaddis
** (exponent) operator, 76, 80–82 A
*= operator, 203 Accessor methods, 537 ● The source code for each example program in the book
+ operator acos(x) function, 285 ● Access to the book’s companion VideoNotes
defined, 76 Actions
displaying multiple items with, 90 conditionally executed, 132
in list concatenation, 371 in decision structures, 133 Instructor Resources
+= operator Ada programming language, 39
defined, 203
The following supplements are available to qualified instructors only:
Addition (+) operator
in list concatenation, 372 defined, 76 ● Answers to all of the Review Questions
in string concatenation, 435 displaying multiple items with, 90 ● Solutions for the exercises
− (subtraction) operator, 76 precedence, 79
_ _str_ _ method, 529–532 add method, 486
● PowerPoint presentation slides for each chapter
−= operator, 203 Algebraic expressions, 83–84 ● Test bank
/ (division) operator, 76, 78 Algorithms
// (integer division) operator, 76, 78 defined, 55 Visit the Pearson Instructor Resource Center (www.pearsonglobaleditions.com/gaddis) or
/= operator, 203 example, 55 contact your local Pearson campus representative for information on how to access them.
= operator recursive, 602, 603, 606–613
defined, 134 and operator
in subset determination, 492 defined, 156
relationship testing, 135 false, 158
= (assignment) operator, 135 short-circuit evaluation, 157
== operator truth table, 156
assignment operator versus, 136 Appending data, 322
725
Preface 19 724 Appendix G Answers to Checkpoints
I would like to thank the following faculty reviewers for their insight, expertise, and thought- 13.16 You would use check buttons.
ful recommendations: 13.17 When you create a group of Radiobuttons, you associate them all with
Sonya Dennis Anita Sutton the same IntVar object. You also assign a unique integer value to each
Morehouse College Germanna Community College Radiobutton widget. When one of the Radiobutton widgets is selected,
it stores its unique integer value in the IntVar object.
Diane Innes Christopher Urban
Sandhills Community College SUNY Institute of Technology 13.18 You associate a different IntVar object with each Checkbutton. When a
Checkbutton is selected, its associated IntVar object will hold the value 1.
John Kinuthia Nanette Veilleux When a Checkbutton is deselected, its associated IntVar object will hold the
Nazareth College of Rochester Simmons College value 0.
Frank Liu Brent Wilson 13.19 (0, 0)
Sam Houston State University George Fox University
13.20 (139, 479)
Haris Ribic
SUNY at Binghamton 13.21 With the Canvas widget, the point (0, 0) is in the upper-left corner of the
window. In turtle graphics, the point (0, 0) is in the center of the window.
Reviewers of Previous Editions Also, with the Canvas widget, the Y coordinates increase as you move down
Paul Amer Shyamal Mitra the screen. In turtle graphics, the Y coordinates decrease as you move down
University of Delaware University of Texas at Austin the screen.
Chapter 12 I would also like to thank my family and friends for their support in all of my projects.
I am extremely fortunate to have Matt Goldstein as my editor, and Kristy Alaura as edito-
12.1 A recursive algorithm requires multiple method calls. Each method call rial assistant. Their guidance and encouragement make it a pleasure to write chapters and
requires several actions to be performed by the JVM. These actions include meet deadlines. I am also fortunate to have Demetrius Hall as my marketing manager. His
allocating memory for parameters and local variables and storing the address hard work is truly inspiring, and he does a great job of getting this book out to the academic
of the program location where control returns after the method terminates. community. The production team, led by Sandra Rodriguez, worked tirelessly to make this
All these actions are known as overhead. In an iterative algorithm, which book a reality. Thanks to you all!
uses a loop, such overhead is unnecessary.
12.2 A case in which the problem can be solved without recursion Acknowledgments for the Global Edition
12.3 Cases in which the problem is solved using recursion Pearson would like to thank and acknowledge the following for their contributions to the
12.4 When it reaches the base case Global Edition.
12.5 In direct recursion, a recursive method calls itself. In indirect recursion, Contributor
method A calls method B, which in turn calls method A. Gregory Baatard, Edith Cowan University
Kenneth Eustace, Charles Sturt University
Chapter 13 Reviewers
Lindsay Ward, James Cook University
13.1 The part of a computer and its operating system with which the user
Ajay Mittal, University Institute of Engineering and Technology
interacts
Khyat Sharma
13.2 A command line interface typically displays a prompt, and the user types a
command, which is then executed. About the Author
13.3 The program Tony Gaddis is the principal author of the Starting Out with series of textbooks. Tony has
13.4 A program that responds to events that take place, such as the user clicking a nearly two decades of experience teaching computer science courses at Haywood Com-
button munity College. He is a highly acclaimed instructor who was previously selected as the
North Carolina Community College “Teacher of the Year” and has received the Teaching
13.5 a) Label—An area that displays one line of text or an image Excellence award from the National Institute for Sta and Organizational Development.
b) Entry—An area in which the user may type a single line of input from the The Starting Out with series includes introductory books covering C++, Java™, Microsoft®
keyboard Visual Basic®, Microsoft® C#®, Python®, Programming Logic and Design, Alice, and App
c) Button—A button that can cause an action to occur when it is clicked Inventor, all published by Pearson.
d) Frame—A container that can hold other widgets
13.6 You create an instance of the tkinter module’s Tk class.
13.7 This function runs like an infinite loop until you close the main window.
13.8 The pack method arranges a widget in its proper position, and it makes the
widget visible when the main window is displayed.
13.9 One will be stacked on top of the other.
13.10 side=–left—
13.11 You use an Entry widget’s get method to retrieve the data that the user has
typed into the widget.
13.12 It is a string.
13.13 tkinter
13.14 Any value that is stored in the StringVar object will automatically be
displayed in the Label widget.
722 Appendix G Answers to Checkpoints
Chapter 11
11.1 A superclass is a general class, and a subclass is a specialized class.
11.2 When one object is a specialized version of another object, there is an “is a”
relationship between them. The specialized object “is a” version of the
general object.
11.3 It inherits all the superclass’s attributes.
11.4 Bird is the superclass, and Canary is the subclass.
9.25 If the specified element to delete is not in the set, the remove method raises a
KeyError exception, but the discard method does not raise an exception.
9.26 You can use the in operator to test for the element.
9.27 {10, 20, 30, 100, 200, 300}
9.28 {3, 4}
9.29 {1, 2}
9.30 {5, 6}
9.33 The process of converting the object to a stream of bytes that can be saved to
a file for later retrieval.
9.34 'wb'
9.35 'rb'
9.38 pickle.load
Chapter 9
9.1 Key and value
9.2 The key
9.3 The string 'start' is the key, and the integer 1472 is the value.
Introduction to Computers
CHAPTE R
1
9.4 It stores the key-value pair 'id' : 54321 in the employee dictionary.
Computers can perform such a wide variety of tasks because they can be programmed. This 9.18 The set will contain one element: 25.
means that computers are not designed to do just one job, but to do any job that their pro-
9.19 The set will contain these elements (in no particular order): 'w', ' ', 'x',
grams tell them to do. A program is a set of instructions that a computer follows to perform
'y', and 'z'.
a task. For example, Figure 1-1 shows screens using Microsoft Word and PowerPoint, two
commonly used programs. 9.20 The set will contain these elements (in no particular order): 1, 2, 3, and 4.
Programs are commonly referred to as software. Software is essential to a computer because 9.21 The set will contain these elements (in no particular order): 'www', 'xxx',
it controls everything the computer does. All of the software that we use to make our com- 'yyy', and 'zzz'.
puters useful is created by individuals working as programmers or software developers. A
9.22 You pass the set as an argument to the len function.
programmer, or software developer, is a person with the training and skills necessary to
design, create, and test computer programs. Computer programming is an exciting and 9.23 The set will contain these elements (in no particular order): 10, 9, 8, 1, 2,
rewarding career. Today, you will find programmers’ work used in business, medicine, gov- and 3.
ernment, law enforcement, agriculture, academics, entertainment, and many other fields. 9.24 The set will contain these elements (in no particular order): 10, 9, 8, 'a',
This book introduces you to the fundamental concepts of computer programming using the 'b', and 'c'.
Python language. The Python language is a good choice for beginners because it is easy to learn
23
Appendix G Answers to Checkpoints 719 24 Chapter 1 Introduction to Computers and Programming
Then, each element in the list will become a slice in the pie chart. The size of Figure 1-1 A word processing program and an image editing program
a slice represents that element’s value as a percentage of the whole.
Chapter 8
8.1 for letter in name:
print(letter)
8.2 0
8.3 9
8.4 An IndexError exception will occur if you try to use an index that is out of
range for a particular string.
8.5 Use the built-in len function.
8.6 The second statement attempts to assign a value to an individual character
in the string. Strings are immutable, however, so the expression animal[0]
cannot appear on the left side of an assignment operator.
8.7 cde and programs can be written quickly using it. Python is also a powerful language, popular with
professional software developers. In fact, it has been reported that Python is used by Google,
8.8 defg NASA, YouTube, various game companies, the New York Stock Exchange, and many others.
8.9 abc Before we begin exploring the concepts of programming, you need to understand a few
8.10 abcdefg basic things about computers and how they work. This chapter will build a solid founda-
tion of knowledge that you will continually rely on as you study computer science. First,
8.11 if 'd' in mystring: we will discuss the physical components of which computers are commonly made. Next, we
print('Yes, it is there.')
will look at how computers store data and execute programs. Finally, you will get a quick
8.12 little = big.upper() introduction to the software that you will use to write Python programs.
8.13 if ch.isdigit():
print('Digit')
else: 1.2 Hardware and Software
print('No digit')
8.14 a A CONCEPT : The physical devices of which a computer is made are referred to as the
computer’s hardware. The programs that run on a computer are referred
8.15 again = input('Do you want to repeat ' + to as software.
'the program or quit? (R/Q) ')
while again.upper() != 'R' and again.upper() != 'Q': Hardware
again = input('Do you want to repeat the ' +
'program or quit? (R/Q) ') The term hardware refers to all of the physical devices, or components, of which a computer
is made. A computer is not one single device, but a system of devices that all work toge-
8.16 $ ther. Like the different instruments in a symphony orchestra, each device in a computer
8.17 for letter in mystring: plays its own part.
if letter.isupper(): If you have ever shopped for a computer, you’ve probably seen sales literature listing compo-
count += 1
nents such as microprocessors, memory, disk drives, video displays, graphics cards, and so on.
8.18 my_list = days.split() Unless you already know a lot about computers, or at least have a friend that does, under-
standing what these different components do might be challenging. As shown in Figure 1-2, a
8.19 my_list = values.split('$')
typical computer system consists of the following major components:
The central processing unit (CPU)
Main memory
1.2 Hardware and Software 25 718 Appendix G Answers to Checkpoints
Figure 1-2 Typical components of a computer system 7.17 You would use statement b, names.append('Wendy'). This is because
element 0 does not exist. If you try to use statement a, an error will occur.
7.18 a) The index method searches for an item in the list and returns the index of
the first element containing that item.
b) The insert method inserts an item into the list at a specified index.
Shutterstock
Central Processing c) The sort method sorts the items in the list to appear in ascending order.
Shutterstock
Unit
d) The reverse method reverses the order of the items in the list.
iko/Shutterstock
7.19 The list contains 4 rows and 2 columns.
Shutterstock
Feng Yu/Shutterstock
Output
Aquila/ Devices 7.20 mylist = [[0, 0, 0, 0], [0, 0, 0, 0],
[0, 0, 0, 0], [0, 0, 0, 0]]
Chiyacat/
Shutterstock 7.21 for r in range(4):
Peter Guess/
Shutterstock
for c in range(2):
Input
Devices
print(numbers[r][c])
jocic/Shutterstock
7.22 The primary difference between tuples and lists is that tuples are immutable.
Eikostas/Shutterstock
That means that once a tuple is created, it cannot be changed.
Main Memory
(RAM) 7.23 Here are three reasons:
Lusoimages/Shutterstock
Processing a tuple is faster than processing a list, so tuples are good
tkemot/Shutterstock Secondary
Storage Devices choices when you are processing lots of data and that data will not be
modified.
Tuples are safe. Because you are not allowed to change the contents of a
tuple, you can store data in one and rest assured that it will not be modified
(accidentally or otherwise) by any code in your program.
There are certain operations in Python that require the use of a tuple.
Vitaly Korovin/Shutterstock Andre Nitsievsky/Shutterstock.
7.24 my_tuple = tuple(my_list)
Secondary storage devices 7.25 my_list = list(my_tuple)
Input devices
Output devices 7.26 Two lists: one holding the X coordinates of the data points, and the other
holding the Y coordinates.
Let’s take a closer look at each of these components.
7.27 A line graph
The CPU 7.28 Use the xlabel and ylabel functions.
When a computer is performing the tasks that a program tells it to do, we say that the 7.29 Call the xlim and ylim functions, passing values for the xmin, xmax, ymin,
computer is running or executing the program. The central processing unit, or CPU, is the and ymax keyword arguments.
part of a computer that actually runs programs. The CPU is the most important component
7.30 Call the xticks and yticks functions. You pass two arguments to these
in a computer because without it, the computer could not run software.
functions. The first argument is a list of tick-mark locations, and the second
In the earliest computers, CPUs were huge devices made of electrical and mechanical com- argument is a list of labels to display at the specified locations.
ponents such as vacuum tubes and switches. Figure 1-3 shows such a device. The two
7.31 Two lists: one containing the X coordinates of each bar’s left edge, and
women in the photo are working with the historic ENIAC computer. The ENIAC, which
another containing the heights of each bar, along the Y axis.
is considered by many to be the world’s first programmable electronic computer, was built
in 1945 to calculate artillery ballistic tables for the U.S. Army. This machine, which was 7.32 The bars will be red, blue, red, and blue.
primarily one big CPU, was 8 feet tall, 100 feet long, and weighed 30 tons. 7.33 You pass a list of values as an argument. The pie function will calculate
Today, CPUs are small chips known as microprocessors. Figure 1-4 shows a photo of a lab the sum of the values in the list, then use that sum as the value of the whole.
technician holding a modern microprocessor. In addition to being much smaller than the old
electromechanical CPUs in early computers, microprocessors are also much more powerful.
Appendix G Answers to Checkpoints 717 26 Chapter 1 Introduction to Computers and Programming
6.18 You copy all the original file’s records to the temporary file, except for the Figure 1-3 The ENIAC computer
record that is to be deleted. The temporary file then takes the place of the
original file. You delete the original file and rename the temporary file, giving
it the name that the original file had on the computer’s disk.
6.19 An exception is an error that occurs while a program is running. In most
cases, an exception causes a program to abruptly halt.
6.20 The program halts.
6.21 IOError
6.22 ValueError
Chapter 7
7.1 [1, 2, 99, 4, 5]
7.2 [0, 1, 2]
7.4 1
courtesy of U.S. Army Historic Computer Images
3
5
7
9
Figure 1-4 A lab technician holds a modern microprocessor
7.5 4
7.8 [1, 2, 3]
[10, 20, 30, 1, 2, 3]
7.9 [2, 3]
7.10 [2, 3]
7.11 [1]
7.12 [1, 2, 3, 4, 5]
7.13 [3, 4, 5]
7.15 The remove method searches for and removes an element containing a
Creativa/Shutterstock
specific value. The del statement removes an element at a specific index.
7.16 You can use the built-in min and max functions.
1.2 Hardware and Software 27 716 Appendix G Answers to Checkpoints
Main Memory has not been converted to text. As a consequence, you cannot view the con-
tents of a binary file with a text editor.
You can think of main memory as the computer’s work area. This is where the computer
stores a program while the program is running, as well as the data that the program is 6.5 Sequential and direct access. When you work with a sequential access file,
working with. For example, suppose you are using a word processing program to write an you access data from the beginning of the file to the end of the file. When
essay for one of your classes. While you do this, both the word processing program and the you work with a direct access file, you can jump directly to any piece of data
essay are stored in main memory. in the file without reading the data that comes before it.
Main memory is commonly known as random-access memory, or RAM. It is called this 6.6 The file’s name on the disk and the name of a variable that references a file
because the CPU is able to quickly access data stored at any random location in RAM. object.
RAM is usually a volatile type of memory that is used only for temporary storage while
6.7 The file’s contents are erased.
a program is running. When the computer is turned off, the contents of RAM are erased.
Inside your computer, RAM is stored in chips, similar to the ones shown in Figure 1-5. 6.8 Opening a file creates a connection between the file and the program. It also
creates an association between the file and a file object.
6.9 Closing a file disconnects the program from the file.
Figure 1-5 Memory chips
6.10 A file’s read position marks the location of the next item that will be read
from the file. When an input file is opened, its read position is initially set to
the first item in the file.
6.11 You open the file in append mode. When you write data to a file in append
mode, the data is written to the end of the file’s existing contents.
Garsya/Shutterstock 6.12 outfile = open('numbers.txt', 'w')
for num in range(1, 11):
outfile.write(str(num) + '\n')
outfile.close()
Secondary Storage Devices
6.13 The readline method returns an empty string ('') when it has attempted to
Secondary storage is a type of memory that can hold data for long periods of time, even
read beyond the end of a file.
when there is no power to the computer. Programs are normally stored in secondary mem-
ory and loaded into main memory as needed. Important data, such as word processing 6.14 infile = open('numbers.txt', 'r')
documents, payroll data, and inventory records, is saved to secondary storage as well. line = infile.readline()
while line != '':
The most common type of secondary storage device is the disk drive. A traditional disk
print(line)
drive stores data by magnetically encoding it onto a spinning circular disk. Solid-state
line = infile.readline()
drives, which store data in solid-state memory, are increasingly becoming popular. A solid-
state drive has no moving parts and operates faster than a traditional disk drive. Most in le.close()
computers have some sort of secondary storage device, either a traditional disk drive or a 6.15 infile = open('data.txt', 'r')
solid-state drive, mounted inside their case. External storage devices, which connect to one for line in infile:
of the computer’s communication ports, are also available. External storage devices can print(line)
be used to create backup copies of important data or to move data to another computer. infile.close()
In addition to external storage devices, many types of devices have been created for copy- 6.16 A record is a complete set of data that describes one item, and a field is a
ing data and for moving it to other computers. For example, USB drives are small devices single piece of data within a record.
that plug into the computer’s USB (universal serial bus) port and appear to the system as
a disk drive. These drives do not actually contain a disk, however. They store data in a 6.17 You copy all the original file's records to the temporary file, but when you
special type of memory known as flash memory. USB drives, which are also known as get to the record that is to be modified, you do not write its old contents
memory sticks and flash drives, are inexpensive, reliable, and small enough to be carried to the temporary file. Instead, you write its new, modified values to the
in your pocket. temporary file. Then, you finish copying any remaining records from the
original file to the temporary file.
Appendix G Answers to Checkpoints 715 28 Chapter 1 Introduction to Computers and Programming
be changed during the program’s execution, you do not have to worry about Optical devices such as the CD (compact disc) and the DVD (digital versatile disc) are
its value being altered. also popular for data storage. Data is not recorded magnetically on an optical disc, but is
encoded as a series of pits on the disc surface. CD and DVD drives use a laser to detect
5.21 The difference is that a value returning function returns a value back to the
the pits and thus read the encoded data. Optical discs hold large amounts of data, and
statement that called it. A simple function does not return a value.
for that reason, recordable CD and DVD drives are commonly used for creating backup
5.22 A prewritten function that performs some commonly needed task copies of data.
5.23 The term “black box” is used to describe any mechanism that accepts input,
performs some operation (that cannot be seen) using the input, and produces Input Devices
output.
Input is any data the computer collects from people and from other devices. The compo-
5.24 It assigns a random integer in the range of 1 through 100 to the variable x. nent that collects the data and sends it to the computer is called an input device. Common
5.25 It prints a random integer in the range of 1 through 20. input devices are the keyboard, mouse, touchscreen, scanner, microphone, and digital cam-
era. Disk drives and optical drives can also be considered input devices, because programs
5.26 It prints a random integer in the range of 10 through 19. and data are retrieved from them and loaded into the computer’s memory.
5.27 It prints a random floating-point number in the range of 0.0 up to, but not
including, 1.0.
Output Devices
5.28 It prints a random floating-point number in the range of 0.1 through 0.5.
Output is any data the computer produces for people or for other devices. It might be
5.29 It uses the system time, retrieved from the computer’s internal clock. a sales report, a list of names, or a graphic image. The data is sent to an output device,
5.30 If the same seed value were always used, the random number functions which formats and presents it. Common output devices are video displays and printers.
would always generate the same series of pseudorandom numbers. Disk drives can also be considered output devices because the system sends data to them
in order to be saved.
5.31 It returns a value back to the part of the program that called it.
Software Development Tools Software development tools are the programs that pro- 5.5 When a program is developed as a set of functions in which each performs
grammers use to create, modify, and test software. Assemblers, compilers, and interpret- an individual task, then different programmers can be assigned the job of
ers are examples of programs that fall into this category. writing different functions.
5.6 A function definition has two parts: a header and a block. The header
Application Software indicates the starting point of the function, and the block is a list of
statements that belong to the function.
Programs that make a computer useful for everyday tasks are known as application soft-
ware. These are the programs that people normally spend most of their time running on 5.7 To call a function means to execute the function.
their computers. Figure 1-1, at the beginning of this chapter, shows screens from two com- 5.8 When the end of the function is reached, the computer returns back to the
monly used applications: Microsoft Word, a word processing program, and PowerPoint, a part of the program that called the function, and the program resumes
presentation program. Some other examples of application software are spreadsheet pro- execution at that point.
grams, email programs, web browsers, and game programs.
5.9 Because the Python interpreter uses the indentation to determine where a
block begins and ends
Checkpoint
5.10 A local variable is a variable that is declared inside a function. It belongs to
1.1 What is a program?
the function in which it is declared, and only statements in the same function
1.2 What is hardware? can access it.
1.3 List the five major components of a computer system.
5.11 The part of a program in which a variable may be accessed
1.4 What part of the computer actually runs programs?
5.12 Yes, it is permissible.
1.5 What part of the computer serves as a work area to store a program and its data
while the program is running? 5.13 Arguments
1.6 What part of the computer holds data for long periods of time, even when there is 5.14 Parameters
no power to the computer?
5.15 A parameter variable’s scope is the entire function in which the parameter is
1.7 What part of the computer collects data from people and from other devices?
declared.
1.8 What part of the computer formats and presents data for people or other devices?
5.16 No, it does not.
1.9 What fundamental set of programs control the internal operations of the
computer’s hardware? 5.17 a. passes by keyword argument
1.10 What do you call a program that performs a specialized task, such as a virus b. passes by position
scanner, a file compression program, or a data backup program? 5.18 The entire program
1.11 Word processing programs, spreadsheet programs, email programs, web browsers,
5.19 Here are three:
and game programs belong to what category of software?
Global variables make debugging difficult. Any statement in a program can
change the value of a global variable. If you find that the wrong value is being
stored in a global variable, you have to track down every statement that
1.3 How Computers Store Data accesses it to determine where the bad value is coming from. In a program
with thousands of lines of code, this can be difficult.
CONCEPT: All data that is stored in a computer is converted to sequences of 0s Functions that use global variables are usually dependent on those variables.
and 1s. If you want to use such a function in a different program, you will most likely
have to redesign it so it does not rely on the global variable.
A computer’s memory is divided into tiny storage locations known as bytes. One byte is Global variables make a program hard to understand. A global variable
only enough memory to store a letter of the alphabet or a small number. In order to do can be modified by any statement in the program. If you are to understand
anything meaningful, a computer has to have lots of bytes. Most computers today have any part of the program that uses a global variable, you have to be aware
millions, or even billions, of bytes of memory. of all the other parts of the program that access the global variable.
Each byte is divided into eight smaller storage locations known as bits. The term bit stands 5.20 A global constant is a name that is available to every function in the
for binary digit. Computer scientists usually think of bits as tiny switches that can be either program. It is permissible to use global constants. Because their value cannot
Appendix G Answers to Checkpoints 713 30 Chapter 1 Introduction to Computers and Programming
4.13 A variable that is used to accumulate the total of a series of numbers on or off. Bits aren’t actual “switches,” however, at least not in the conventional sense. In
most computer systems, bits are tiny electrical components that can hold either a positive
4.14 Yes, it should be initialized with the value 0. This is because values are added
or a negative charge. Computer scientists think of a positive charge as a switch in the on
to the accumulator by a loop. If the accumulator does not start at the value 0,
position, and a negative charge as a switch in the off position. Figure 1-6 shows the way
it will not contain the correct total of the numbers that were added to it when
that a computer scientist might think of a byte of memory: as a collection of switches that
the loop ends.
are each flipped to either the on or off position.
4.15 15
4.16 15
Figure 1-6 Think of a byte as eight switches
5
4.17 a) quantity += 1 ON ON ON ON
b) days_left −= 5
c) price *= 10
d) price /= 2
4.18 A sentinel is a special value that marks the end of a list of items.
4.19 A sentinel value must be unique enough that it will not be mistaken as a OFF OFF OFF OFF
regular value in the list.
4.20 It means that if bad data (garbage) is provided as input to a program, the
program will produce bad data (garbage) as output. When a piece of data is stored in a byte, the computer sets the eight bits to an on/off
4.21 When input is given to a program, it should be inspected before it is pattern that represents the data. For example, the pattern on the left in Figure 1-7 shows
processed. If the input is invalid, then it should be discarded and the user how the number 77 would be stored in a byte, and the pattern on the right shows how the
should be prompted to enter the correct data. letter A would be stored in a byte. We explain below how these patterns are determined.
4.22 The input is read, then a pretest loop is executed. If the input data is invalid,
the body of the loop executes. In the body of the loop, an error message is Figure 1-7 Bit patterns for the number 77 and the letter A
displayed so the user will know that the input was invalid, and then the
input read again. The loop repeats as long as the input is invalid. ON ON ON ON ON ON
4.23 It is the input operation that takes place just before an input validation loop.
The purpose of the priming read is to get the first input value.
4.24 None OFF
OFF OFF OFF OFF OFF OFF OFF OFF OFF
The position of each digit in a binary number has a value assigned to it. Starting with 3.26 You use the turtle.pencolor() function to determine the pen color.
the rightmost digit and moving left, the position values are 20, 21, 22, 23, and so forth, as You use the turtle.fillcolor() function to determine the current fill
shown in Figure 1-8. Figure 1-9 shows the same diagram with the position values calcu- color. You use the turtle.bgcolor() function to determine the current
lated. Starting with the rightmost digit and moving left, the position values are 1, 2, 4, 8, background color of the turtle’s graphics window.
and so forth.
3.27 You use the turtle.pensize() function.
3.28 You use the turtle.speed() function.
Figure 1-8 The values of binary digits as powers of 2
10011101 Chapter 4
0 4.1 A structure that causes a section of code to repeat
2
21 4.2 A loop that uses a true/false condition to control the number of times that it
22
23 repeats
24
25 4.3 A loop that repeats a specific number of times
26
27 4.4 An execution of the statements in the body of the loop
4.5 Before
Figure 1-9 The values of binary digits 4.6 None. The condition count < 0 will be false to begin with.
4.7 A loop that has no way of stopping and repeats until the program is
10011101 interrupted.
1 4.8 for x in range(6):
2
4 print('I love to program!')
8
16 4.9 0
32 1
64
128
2
3
4
5
To determine the value of a binary number, you simply add up the position values of all the
1s. For example, in the binary number 10011101, the position values of the 1s are 1, 4, 8, 4.10 2
16, and 128. This is shown in Figure 1-10. The sum of all of these position values is 157. 3
So, the value of the binary number 10011101 is 157. 4
5
3.13 if number == 1: Figure 1-11 shows how you can picture the number 157 stored in a byte of memory. Each
print('One') 1 is represented by a bit in the on position, and each 0 is represented by a bit in the off
elif number == 2: position.
print('Two')
elif number == 3:
print('Three') Figure 1-11 The bit pattern for 157
else:
print('Unknown')
Any piece of data that is stored in a computer’s memory must be stored as a binary num- 2.39 turtle.setup(500, 200)
ber. That includes characters, such as letters and punctuation marks. When a character is 2.40 turtle.goto(100, 50)
stored in memory, it is first converted to a numeric code. The numeric code is then stored
in memory as a binary number. 2.41 turtle.pos()
Over the years, different coding schemes have been developed to represent characters in 2.42 turtle.speed(10)
computer memory. Historically, the most important of these coding schemes is ASCII, 2.43 turtle.speed(0)
which stands for the American Standard Code for Information Interchange. ASCII is a set
of 128 numeric codes that represent the English letters, various punctuation marks, and 2.44 To fill a shape with a color, you use the turtle.begin_fill() command
other characters. For example, the ASCII code for the uppercase letter A is 65. When you before drawing the shape, then you use the turtle.end_fill() command
type an uppercase A on your computer keyboard, the number 65 is stored in memory (as after the shape is drawn. When the turtle.end_fill() command executes,
a binary number, of course). This is shown in Figure 1-13. the shape will be filled with the current fill color.
2.45 With the turtle.write()command
Figure 1-13 The letter A is stored in memory as the number 65
Chapter 3
1 1
A
3.1 A logical design that controls the order in which a set of statements execute
65 3.2 It is a program structure that can execute a set of statements only under
0 0 0 0 0 0
certain circumstances.
3.3 A decision structure that provides a single alternative path of execution.
If the condition that is being tested is true, the program takes the alternative
TIP : The acronym ASCII is pronounced “askee.” path.
3.4 An expression that can be evaluated as either true or false
In case you are curious, the ASCII code for uppercase B is 66, for uppercase C is 67, and so 3.5 You can determine whether one value is greater than, less than, greater than
forth. Appendix C shows all of the ASCII codes and the characters they represent. or equal to, less than or equal to, equal to, or not equal to another value.
The ASCII character set was developed in the early 1960s and was eventually adopted by 3.6 if y == 20:
almost all computer manufacturers. ASCII is limited, however, because it defines codes for x = 0
only 128 characters. To remedy this, the Unicode character set was developed in the early 3.7 if sales >= 10000:
1990s. Unicode is an extensive encoding scheme that is compatible with ASCII, but can commissionRate = 0.2
also represent characters for many of the languages in the world. Today, Unicode is quickly
becoming the standard character set used in the computer industry. 3.8 A dual alternative decision structure has two possible paths of execution;
one path is taken if a condition is true, and the other path is taken if the
condition is false.
Advanced Number Storage 3.9 if-else
Earlier, you read about numbers and how they are stored in memory. While reading that 3.10 When the condition is false
section, perhaps it occurred to you that the binary numbering system can be used to repre-
sent only integer numbers, beginning with 0. Negative numbers and real numbers (such as 3.11 z is not less than a.
3.14159) cannot be represented using the simple binary numbering technique we discussed. 3.12 Boston
Computers are able to store negative numbers and real numbers in memory, but to do so New York
they use encoding schemes along with the binary numbering system. Negative numbers are
encoded using a technique known as two’s complement, and real numbers are encoded in
floating-point notation. You don’t need to know how these encoding schemes work, only
that they are used to convert negative numbers and real numbers to binary format.
Appendix G Answers to Checkpoints 709 34 Chapter 1 Introduction to Computers and Programming
01
0
2.20 4
00
10
101
101
2.21 1
2.22 If you do not want the print function to start a new line of output when it
finishes displaying its output, you can pass the special argument end = ' '
to the function.
The music that you play on your CD player, iPod, or MP3 player is also digital. A digital
2.23 You can pass the argument sep= to the print function, specifying the song is broken into small pieces known as samples. Each sample is converted to a binary
desired character. number, which can be stored in memory. The more samples that a song is divided into, the
2.24 It is the newline escape character. more it sounds like the original music when it is played back. A CD quality song is divided
into more than 44,000 samples per second!
2.25 It is the string concatenation operator, which joins two strings together.
2.26 65.43 Checkpoint
2.27 987,654.13 1.12 What amount of memory is enough to store a letter of the alphabet or a small
number?
2.28 (1) Named constants make programs more self-explanatory, (2) widespread
changes can easily be made to the program, and (3) they help to prevent the 1.13 What do you call a tiny “switch” that can be set to either on or off?
typographical errors that are common when using magic numbers. 1.14 In what numbering system are all numeric values written as sequences of 0s and 1s?
2.35 turtle.circle(100) CONCEPT : A computer’s CPU can only understand instructions that are written in
machine language. Because people find it very difficult to write entire
2.36 turtle.pensize(8)
programs in machine language, other programming languages have been
2.37 turtle.pencolor('blue') invented.
1.4 How a Program Works 35 708 Appendix G Answers to Checkpoints
Earlier, we stated that the CPU is the most important component in a computer because it is 1.18 Machine language
the part of the computer that runs programs. Sometimes the CPU is called the “computer’s
1.19 Main memory, or RAM
brain” and is described as being “smart.” Although these are common metaphors, you
should understand that the CPU is not a brain, and it is not smart. The CPU is an electronic 1.20 The fetch-decode-execute cycle
device that is designed to do specific things. In particular, the CPU is designed to perform
1.21 It is an alternative to machine language. Instead of using binary numbers
operations such as the following:
for instructions, assembly language uses short words that are known as
Reading a piece of data from main memory mnemonics.
Adding two numbers
1.22 A high-level language
Subtracting one number from another number
Multiplying two numbers 1.23 Syntax
Dividing one number by another number
1.24 A compiler
Moving a piece of data from one memory location to another
Determining whether one value is equal to another value 1.25 An interpreter
As you can see from this list, the CPU performs simple operations on pieces of data. The 1.26 A syntax error
CPU does nothing on its own, however. It has to be told what to do, and that’s the purpose
of a program. A program is nothing more than a list of instructions that cause the CPU to
perform operations. Chapter 2
Each instruction in a program is a command that tells the CPU to perform a specific opera- 2.1 Any person, group, or organization that is asking you to write a program
tion. Here’s an example of an instruction that might appear in a program: 2.2 A single function that the program must perform in order to satisfy the
10110000 customer
To you and me, this is only a series of 0s and 1s. To a CPU, however, this is an instruction 2.3 A set of well-defined logical steps that must be taken to perform a task
to perform an operation.1 It is written in 0s and 1s because CPUs only understand instruc- 2.4 An informal language that has no syntax rules and is not meant to be
tions that are written in machine language, and machine language instructions always have compiled or executed. Instead, programmers use pseudocode to create
an underlying binary structure. models, or “mock-ups,” of programs.
A machine language instruction exists for each operation that a CPU is capable of perform- 2.5 A diagram that graphically depicts the steps that take place in a program
ing. For example, there is an instruction for adding numbers, there is an instruction for
subtracting one number from another, and so forth. The entire set of instructions that a 2.6 Ovals are terminal symbols. Parallelograms are either output or input
CPU can execute is known as the CPU’s instruction set. symbols. Rectangles are processing symbols.
2.7 print('Jimmy Smith')
The machine language instruction that was previously shown is an example of only one
instruction. It takes a lot more than one instruction, however, for the computer to do any-
thing meaningful. Because the operations that a CPU knows how to perform are so basic in
nature, a meaningful task can be accomplished only if the CPU performs many operations.
For example, if you want your computer to calculate the amount of interest that you will
APP ENDIX
earn from your savings account this year, the CPU will have to perform a large number of
G
instructions, carried out in the proper sequence. It is not unusual for a program to contain
Answers to Checkpoints thousands or even millions of machine language instructions.
Programs are usually stored on a secondary storage device such as a disk drive. When you
install a program on your computer, the program is typically copied to your computer’s disk
drive from a CD-ROM, or downloaded from a website.
Although a program can be stored on a secondary storage device such as a disk drive,
it has to be copied into main memory, or RAM, each time the CPU executes it. For
example, suppose you have a word processing program on your computer’s disk. To
execute the program, you use the mouse to double-click the program’s icon. This causes
Chapter 1
the program to be copied from the disk into main memory. Then, the computer’s CPU
1.1 A program is a set of instructions that a computer follows to perform a task. executes the copy of the program that is in main memory. This process is illustrated in
1.2 Hardware is all the physical devices, or components, of which a computer is Figure 1-15.
made.
1.3 The central processing unit (CPU), main memory, secondary storage devices, Figure 1-15 A program is copied into main memory and then executed
input devices, and output devices
The program is copied
1.4 The CPU The CPU executes
from secondary storage
the program in
to main memory.
1.5 Main memory main memory.
Main memory
1.6 Secondary storage (RAM)
1.7 Input device
1.8 Output device
1.9 The operating system Disk drive CPU
707
1.4 How a Program Works 37
10100001
Fetch the next instruction
1
in the program.
10100001
10111000 Decode the instruction
10011110 2 to determine which
00011010 operation to perform.
11011100
and so forth... CPU
Execute the instruction
3
(perform the operation).
Main memory
(RAM)
N OTE : There are many different versions of assembly language. It was mentioned
earlier that each brand of CPU has its own machine language instruction set. Each
brand of CPU typically has its own assembly language as well.
Assembly language programs cannot be executed by the CPU, however. The CPU only
understands machine language, so a special program known as an assembler is used to
translate an assembly language program to a machine language program. This process is
shown in Figure 1-17. The machine language program that is created by the assembler can
then be executed by the CPU.
2
The first assembly language was most likely that developed in the 1940s at Cambridge University
for use with a historic computer known as the EDSAC.
38 Chapter 1 Introduction to Computers and Programming
F
mov eax, Z 10100001
add eax, 2
mov Y, eax 10111000
High-Level Languages
Although assembly language makes it unnecessary to write binary machine language instruc-
The Python standard library provides classes and functions that your programs can use to tions, it is not without difficulties. Assembly language is primarily a direct substitute for
perform basic operations, as well as many advanced tasks. There are operations, however, machine language, and like machine language, it requires that you know a lot about the
that the standard library cannot perform. When you need to do something that is beyond CPU. Assembly language also requires that you write a large number of instructions for even
the scope of the standard library, you have two choices: write the code yourself, or use code the simplest program. Because assembly language is so close in nature to machine language,
that someone else has already written. it is referred to as a low-level language.
Fortunately, there are thousands of Python modules, written by independent programmers, In the 1950s, a new generation of programming languages known as high-level languages
that provide capabilities that the standard Python library does not offer. These are known began to appear. A high-level language allows you to create powerful and complex pro-
as third-party modules. A large collection of third-party modules exists at the website pypi. grams without knowing how the CPU works and without writing large numbers of low-level
python.org, which is known as the Python Package Index, or PyPI. instructions. In addition, most high-level languages use words that are easy to understand.
For example, if a programmer were using COBOL (which was one of the early high-level
The modules that are available at PyPI are organized as packages. A package is simply a coll- languages created in the 1950s), he or she would write the following instruction to display
ection of one or more related modules. The easiest way to download and install a package the message Hello world on the computer screen:
is with the pip utility. The pip utility is a program that is part of the standard Python
installation, beginning with Python 3.4. To install a package on a Windows system with DISPLAY "Hello world"
the pip utility, you must open a command prompt window, and type a command following Python is a modern, high-level programming language that we will use in this book. In
this format: Python you would display the message Hello world with the following instruction:
pip install package_name print('Hello world')
package_name is the name of a package that you want to download and install. If you are
Doing the same thing in assembly language would require several instructions and an inti-
running a Mac or a Linux system, you must use the pip3 command instead of the pip com-
mate knowledge of how the CPU interacts with the computer’s output device. As you can see
mand. In addition, you will need superuser privileges to execute the pip3 command on a
from this example, high-level languages allow programmers to concentrate on the tasks they
Mac or Linux system, so you will have to prefix the command with sudo, as shown here: want to perform with their programs, rather than the details of how the CPU will execute
sudo pip3 install package_name those programs.
Once you enter the command, the pip utility will start downloading and installing the Since the 1950s, thousands of high-level languages have been created. Table 1-1 lists several
package. Depending on the size of the package, it may take a few minutes to complete the of the more well-known languages.
installation process. Once the process is finished, you can typically verify that the package
was correctly installed by starting IDLE and entering the command
Key Words, Operators, and Syntax: An Overview
>>> import package_name
Each high-level language has its own set of predefined words that the programmer must
where package_name is the name of the package that you installed. If you do not see an use to write a program. The words that make up a high-level programming language are
error message, you can assume the package was successfully installed. known as key words or reserved words. Each key word has a specific meaning, and cannot
In Chapter 7, you will explore a popular third-party package named matplotlib. You can be used for any other purpose. Table 1-2 shows all of the Python key words.
use the matplotlib package to create charts and graphs.
705
1.4 How a Program Works 39
Using an Alias In addition to key words, programming languages have operators that perform various
operations on data. For example, all programming languages have math operators that
You can use the as keyword to assign an alias to a module when you import it. The follow- perform arithmetic. In Python, as well as most other languages, the + sign is an operator
ing statement shows an example: that adds two numbers. The following adds 12 and 75:
import math as mt 12 + 75
This statement loads the math module into memory, assigning the module the alias mt. There are numerous other operators in the Python language, many of which you will learn
To use any of the items that are in the module, you prefix the item’s name with the alias, about as you progress through this text.
followed by a dot. For example, to call the sqrt function, you would use the name
mt.sqrt. The following interactive session shows an example: In addition to key words and operators, each language also has its own syntax, which is a
set of rules that must be strictly followed when writing a program. The syntax rules dictate
>>> import math as mt how key words, operators, and various punctuation characters must be used in a program.
>>> x = mt.sqrt(25) When you are learning a programming language, you must learn the syntax rules for that
>>> a = mt.radians(180) particular language.
>>> print(x)
5.0 The individual instructions that you use to write a program in a high-level programming
>>> print(a) language are called statements. A programming statement can consist of key words, oper-
3.141592653589793 ators, punctuation, and other allowable programming elements, arranged in the proper
>>> sequence to perform an operation.
You can also assign an alias to a specific function or class when you import it. The follow-
ing statement imports the sqrt function from the math module, and assigns the function Compilers and Interpreters
the alias square_root:
Because the CPU understands only machine language instructions, programs that are writ-
from math import sqrt as square_root ten in a high-level language must be translated into machine language. Depending on the
language in which a program has been written, the programmer will use either a compiler
After using this import statement, you would use the name square_root to call the sqrt
or an interpreter to make the translation.
function. The following interactive session shows an example:
A compiler is a program that translates a high-level language program into a separate
>>> from math import sqrt as square_root
machine language program. The machine language program can then be executed any time
>>> x = square_root(25)
it is needed. This is shown in Figure 1-18. As shown in the figure, compiling and executing
>>> print(x)
are two different processes.
5.0
>>> Figure 1-18 Compiling a high-level program and executing it
In the following interactive session, we import two functions from the math module, giving
High-level language Machine language
each of them an alias. The sqrt function is imported as square_root, and the tan func- program
program
tion is imported as tangent:
The compiler is used 10100001
print ("Hello
>>> from math import sqrt as square_root, tan as tangent 1 to translate the high-level Earthling") 10111000
language program to a Compiler
>>> x = square_root(25) 10011110
machine language program. and so forth... and so forth...
>>> y = tangent(45)
>>> print(x)
5.0
>>> print(y)
1.6197751905438615
Machine language
CPU
program
The machine language 10100001
2 program can be executed 10111000
at any time, without using 10011110
the compiler. and so forth...
1.4 How a Program Works 41 702 Appendix E More About the import Statement
The Python language uses an interpreter, which is a program that both translates and This statement causes only the sqrt function to be imported from the math module. It also
executes the instructions in a high-level language program. As the interpreter reads allows you to call the sqrt function without prefixing the function’s name with the name
each individual instruction in the program, it converts it to machine language instruc- of the module. The following interactive session shows an example:
tions then immediately executes them. This process repeats for every instruction in
>>> from math import sqrt
the program. This process is illustrated in Figure 1-19. Because interpreters combine
>>> x = sqrt(25)
translation and execution, they typically do not create separate machine language
>>> print(x)
programs.
5.0
>>>
Figure 1-19 Executing a high-level program with an interpreter You can specify the names of multiple items, separated with commas, when you use this
form of the import statement. For example, the import statement in the following interac-
High-level language tive session imports only the sqrt function and the radians function from the math
program CPU module:
Machine language
print ("Hello instruction
>>> from math import sqrt, radians
Earthling") Interpreter 10100001
>>> x = sqrt(25)
and so forth... >>> a = radians(180)
>>> print(x)
5.0
The interpreter translates each high-level instruction to
>>> print(a)
its equivalent machine language instructions then 3.141592653589793
immediately executes them. >>>
This process is repeated for each high-level instruction.
Wildcard Imports
The statements that a programmer writes in a high-level language are called source A wildcard import statement loads the entire contents of a module. Here is an example:
code, or simply code. Typically, the programmer types a program’s code into a text
editor then saves the code in a file on the computer’s disk. Next, the programmer uses from math import *
a compiler to translate the code into a machine language program, or an interpreter to The difference between this statement and the import math statement is that the wildcard
translate and execute the code. If the code contains a syntax error, however, it cannot import statement does not require you to use the qualified names of the items in the mod-
be translated. A syntax error is a mistake such as a misspelled key word, a missing ule. For example, here is an interactive session that uses a wildcard import statement:
punctuation character, or the incorrect use of an operator. When this happens, the
compiler or interpreter displays an error message indicating that the program contains >>> from math import*
a syntax error. The programmer corrects the error then attempts once again to translate >>> x = sqrt(25)
the program. >>> a = radians(180)
>>>
And, here is an interactive session that uses the regular import statement:
N OTE : Human languages also have syntax rules. Do you remember when you took >>> import math
your first English class, and you learned all those rules about commas, apostrophes, >>> x = math.sqrt(25)
capitalization, and so forth? You were learning the syntax of the English language. >>> a = math.radians(180)
>>>
Although people commonly violate the syntax rules of their native language when
speaking and writing, other people usually understand what they mean. Unfortunately, Typically, you should avoid using the wildcard import statement because it can lead to
compilers and interpreters do not have this ability. If even a single syntax error appears name clashes when you are importing several modules. A name clash occurs when a
in a program, the program cannot be compiled or executed. When an interpreter program imports two modules that have functions or classes with the same name. Name
encounters a syntax error, it stops executing the program. clashes do not occur when you are using the qualified names of a module’s functions
and/or classes.
42 Chapter 1 Introduction to Computers and Programming
Checkpoint
1.18 A CPU understands instructions that are written only in what language?
1.19 A program has to be copied into what type of memory each time the CPU
executes it?
1.20 When a CPU executes the instructions in a program, it is engaged in what process?
More About the import
APP ENDIX
E
1.21 What is assembly language?
1.22 What type of programming language allows you to create powerful and complex
Statement 1.23
programs without knowing how the CPU works?
Each language has a set of rules that must be strictly followed when writing a
program. What is this set of rules called?
1.24 What do you call a program that translates a high-level language program into a
separate machine language program?
1.25 What do you call a program that both translates and executes the instructions in
A module is a Python source code file that contains functions and/or classes. Many of the a high-level language program?
functions in the Python standard library are stored in modules. For example, the math mod- 1.26 What type of mistake is usually caused by a misspelled key word, a missing
ule contains various mathematical functions, and the random module contains functions for punctuation character, or the incorrect use of an operator?
working with random numbers.
In order to use the functions and/or classes that are stored in a module, you must import the
module. To import a module, you write an import statement at the top of your program.
1.5 Using Python
Here is an import statement that imports the math module:
CONCEPT : The Python interpreter can run Python programs that are saved in files
import math
or interactively execute Python statements that are typed at the keyboard.
This statement causes the Python interpreter to load the contents of the math module into Python comes with a program named IDLE that simplifies the process of
memory, making the functions and/or classes that are stored in the math module available writing, executing, and testing programs.
to the program. To use any item that is in the module, you must use the item’s qualified
name. This means that you must prefix the item’s name with the name of the module, fol-
lowed by a dot. For example, the math module has a function named sqrt that returns the Installing Python
square root of a number. To call the sqrt function, you would use the name math.sqrt. Before you can try any of the programs shown in this book, or write any programs of your
The following interactive session shows an example: own, you need to make sure that Python is installed on your computer and properly con-
>>> import math
figured. If you are working in a computer lab, this has probably been done already. If you
>>> x = math.sqrt(25)
are using your own computer, you can follow the instructions in Appendix A to download
>>> print(x)
and install Python.
5.0
>>> The Python Interpreter
You learned earlier that Python is an interpreted language. When you install the Python
language on your computer, one of the items that is installed is the Python interpreter. The
Importing a Specific Function or Class Python interpreter is a program that can read Python programming statements and execute
The previously shown form of the import statement loads the entire contents of a module them. (Sometimes, we will refer to the Python interpreter simply as the interpreter.)
into memory. Sometimes you want to import only a specific function or class from a mod-
You can use the interpreter in two modes: interactive mode and script mode. In interac-
ule. When this is the case, you can use the from keyword with the import statement, as
tive mode, the interpreter waits for you to type Python statements on the keyboard. Once
shown here:
you type a statement, the interpreter executes it and then waits for you to type another
from math import sqrt statement. In script mode, the interpreter reads the contents of a file that contains Python
statements. Such a file is known as a Python program or a Python script. The interpreter
executes each statement in the Python program as it reads it.
701
1.5 Using Python 43
Interactive Mode
Once Python has been installed and set up on your system, you start the interpreter in
interactive mode by going to the operating system’s command line and typing the follow-
ing command:
python
If you are using Windows, you can alternatively type python in the Windows search box.
In the search results, you will see a program named something like Python 3.5. (The “3.5”
is the version of Python that is installed. At the time this is being written, Python 3.5 is
the latest version.) Clicking this item will start the Python interpreter in interactive mode.
When the Python interpreter starts in interactive mode, you will see something like the fol-
lowing displayed in a console window:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48)
[MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license"
for more information. This page intentionally left blank
>>>
The >>> that you see is a prompt that indicates the interpreter is waiting for you to type
a Python statement. Let’s try it out. One of the simplest things that you can do in Python
is print a message on the screen. For example, the following statement prints the message
Python programming is fun! on the screen:
print('Python programming is fun!')
You can think of this as a command that you are sending to the Python interpreter. If
you type the statement exactly as it is shown, the message Python programming is fun! is
printed on the screen. Here is an example of how you type this statement at the interpreter’s
prompt:
>>> print('Python programming is fun!') Enter
After typing the statement, you press the Enter key, and the Python interpreter executes the
statement, as shown here:
>>> print('Python programming is fun!') Enter
Python programming is fun!
>>>
Appendix D Predefined Named Colors 699 44 Chapter 1 Introduction to Computers and Programming
'gray3' 'gray4' 'gray5' After the message is displayed, the >>> prompt appears again, indicating the interpreter is
'gray6' 'gray7' 'gray8' waiting for you to enter another statement. Let’s look at another example. In the following
sample session, we have entered two statements:
'gray9' 'gray10' 'gray11'
>>> print('To be or not to be') Enter
'gray12' 'gray13' 'gray14'
To be or not to be
'gray15' 'gray16' 'gray17' >>> print('That is the question.') Enter
'gray18' 'gray19' 'gray20' That is the question.
>>>
'gray21' 'gray22' 'gray23'
'gray24' 'gray25' 'gray26' If you incorrectly type a statement in interactive mode, the interpreter will display an error
message. This will make interactive mode useful to you while you learn Python. As you
'gray27' 'gray28' 'gray29'
learn new parts of the Python language, you can try them out in interactive mode and get
'gray30' 'gray31' 'gray32' immediate feedback from the interpreter.
'gray33' 'gray34' 'gray35' To quit the Python interpreter in interactive mode on a Windows computer, press Ctrl-Z
'gray36' 'gray37' 'gray38' (pressing both keys together) followed by Enter. On a Mac, Linux, or UNIX computer,
press Ctrl-D.
'gray39' 'gray40' 'gray42'
'gray43' 'gray44' 'gray45'
'gray46' 'gray47' 'gray48' N O TE : In Chapter 2, we will discuss the details of statements like the ones previously
shown. If you want to try them now in interactive mode, make sure you type them exactly
'gray49' 'gray50' 'gray51'
as shown.
'gray52' 'gray53' 'gray54'
'gray55' 'gray56' 'gray57'
'gray58' 'gray59' 'gray60' Writing Python Programs and Running
'gray61' 'gray62' 'gray63' Them in Script Mode
'gray64' 'gray65' 'gray66' Although interactive mode is useful for testing code, the statements that you enter in interac-
tive mode are not saved as a program. They are simply executed and their results displayed on
'gray67' 'gray68' 'gray69'
the screen. If you want to save a set of Python statements as a program, you save those state-
'gray70' 'gray71' 'gray72' ments in a file. Then, to execute the program, you use the Python interpreter in script mode.
'gray73' 'gray74' 'gray75' For example, suppose you want to write a Python program that displays the following three
'gray76' 'gray77' 'gray78' lines of text:
'gray79' 'gray80' 'gray81' Nudge nudge
'gray82' 'gray83' 'gray84' Wink wink
Know what I mean?
'gray85' 'gray86' 'gray87'
'gray88' 'gray89' 'gray90'
To write the program you would use a simple text editor like Notepad (which is installed
on all Windows computers) to create a file containing the following statements:
'gray91' 'gray92' 'gray93'
print('Nudge nudge')
'gray94' 'gray95' 'gray97'
print('Wink wink')
'gray98' 'gray99' print('Know what I mean?')
N O TE : It is possible to use a word processor to create a Python program, but you must
be sure to save the program as a plain text file. Otherwise, the Python interpreter will
not be able to read its contents.
GLOBAL GLOBAL
EDITION EDITION
RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO
THIS INFORMATION, INCLUDING ALL WARRANTIES AND CONDITIONS OF MERCHANTABILITY,
Digital Resources for Students WHETHER EXPRESS, IMPLIED OR STATUTORY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
Your new textbook provides 12-month access to digital resources that may include WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
VideoNotes (step-by-step video tutorials on programming concepts), source code, web
WITH THE USE OR PERFORMANCE OF INFORMATION AVAILABLE FROM THE SERVICES. THE
chapters, quizzes, and more. Refer to the preface in the textbook for a detailed list of DOCUMENTS AND RELATED GRAPHICS CONTAINED HEREIN COULD INCLUDE TECHNICAL
resources. INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO
THE INFORMATION HEREIN. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS MAY MAKE
Follow the instructions below to register for the Companion Website for Tony Gaddis’ IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED
Starting Out with Python, Fourth Edition, Global Edition. HEREIN AT ANY TIME. PARTIAL SCREEN SHOTS MAY BE VIEWED IN FULL WITHIN THE SOFTWARE
VERSION SPECIFIED.
1. Go to www.pearsonglobaleditions.com/gaddis
2. Enter the title of your textbook or browse by author name.
3. Click Companion Website.
4. Click Register and follow the on-screen instructions to create a login name
and password.
ISSGPY-PRANK-CURRY-PIQUE-METIS-ROUSE
Use the login name and password you created during registration to start using the
online resources that accompany your textbook.
IMPORTANT:
This prepaid subscription does not include access to MyProgrammingLab, which is
available at www.myprogramminglab.com for purchase.
This subscription is valid for 12 months upon activation and is not transferable.
743
742 Index
P
defined, 261 Widgets
general format, 272 arrangement of, 630
how to use, 274–276 Button, 622, 630–633
®
and IPO charts, 276–277 Canvas, 622
randint and, 263–266 Checkbutton, 622, 648–650
random number generation, 262–271 defined, 622
randrange and, 269–270 Entry, 622, 633–636
returning multiple values, 282–283 Frame, 622, 629
return statement, 272–274 with frames, organizing, 627–630
for simplifying mathematical expressions, 274–276 Label, 622, 625–626, 629, 636–640
values, 261, 274 Listbox, 622
void functions and, 233 list of, 641
F OUR TH ED ITION writing, 272–283
Values
Menu, 622
Menubutton, 622
P
str data type, 69–70 as base classes, 574
str function defined, 574
defined, 326 in UML diagrams, 582–583
®
example use, 323 writing, 575
String comparisons, 144–147, 444–445, 463, 464 Supersets, 492
String concatenation SUV class, 580–581
defined, 90, 434 Symbols, flowchart, 56
example, 90 symmetric_difference method, 491
interactive sessions, 434 Symmetric difference of sets, 491
newline to, 319–320 Syntax
with + operator, 90 defined, 40
with += operator, 435 human language, 41
F OUR TH ED ITION String literals
defined, 59
Syntax errors
correcting, 54
GLOBA L EDITION enclosing in triple quotes, 60
Strings
defined, 41
reporting, 691
characters, accessing, 430–434 running programs and, 691
comparing, 144–148 System software, 28–29
defined, 59
extracting characters from, 438–440 T
as immutable, 435–436 tan() function, 285
Tony Gaddis
indexes, 432–433 Target variables
iterating with for loop, 430–432 defined, 192
list of, 366 inside for loops, 194–196
Haywood Community College method call format, 442 use example, 195
modification methods, 444–445 Terminal symbols, 56
operations, 429–436 Testing
raw, 314 dictionary values, 463–464
reading as input, 429 programs, 54–55
repetition operator (*) with, 450–451 set values, 488–489
returning, 280 string methods, 442–443
search and replace methods, 445–446 strings, 441
slicing, 437–438 Text
space character at end, 73 drawing with Canvas widget, 667–672
splitting, 451–452 displaying with Label widget, 624–627
storing with str data type, 69–70 editing, 687–688
stripping newline from, 320–322 font setting, 670–672
testing, 441 Text files
testing methods, 442–443 defined, 311
writing as output, 429 reading numbers from, 324
written to files, 316 Text widget, 622
StringVar object, 636–637 third-party modules, 705
strip() method, 444 Tkinter module
Stripping newline from string, 320–322 defined, 621
Structure charts. See Hierarchy charts programs using, 622
Subclasses widgets, 622
defined, 574 Top-down design
as derived classes, 574 defined, 240
method override, 588 process, 240–241
�)è“ÜÊÃ�ZãØ——ã �B—ô�xÊع �Bx�
Index 739
Running programs, 690–691 set method, 640, 647 Senior Vice President Courseware Portfolio Management: Marcia J. Horton
Running totals Sets Director, Portfolio Management: Engineering,
calculating, 201–204 adding elements, 486–487 Computer Science & Global Editions: Julian Partridge
defined, 201 creating, 485
Portfolio Manager: Matt Goldstein
elements for calculating, 201 defined, 484
example, 202 difference of, 490–491
Acquisitions Editor, Global Edition: Sourabh Maheshwari
logic for calculating, 201 duplicate elements, 485 Portfolio Management Assistant: Kristy Alaura
elements, as unique, 484 Field Marketing Manager: Demetrius Hall
S elements, number of, 486 Product Marketing Manager: Yvonne Vannatta
Samples, 34 elements, removing, 487–488 Managing Producer, ECS and Math: Scott Disanno
Saving programs, 690 intersection of, 490 Content Producer: Sandra L. Rodriguez
SavingsAccount class, 584, 585 for loop iteration over, 488
Project Editors, Global Edition: Tanima Ghosh and Neelakantan K.K.
Scale widget, 622 operations, 493–495
Scientific notation, 92 subsets, 492
Senior Manufacturing Controller, Global Edition: Jerry Kataria
Scope supersets, 492 Manager, Media Production, Global Edition: Vikram Kumar
defined, 245 symmetric difference of, 491 Cover Designer: Lumina Datamatics
local variables and, 245–247 union of, 489 Cover Photo: Africa Studio/Shutterstock
parameter variable, 249 unordered, 484
Credits and acknowledgments borrowed from other sources and reproduced, with permission, appear
Script mode, running programs in, 45 values, testing, 488–489
Scrollbar widget, 622 Settings. See Mutator methods
on the Credits page in the endmatter of this textbook.
Searching Showinfo function, 630 Pearson Education Limited
lists, 376–377 sin() function, 285
KAO Two
records, 339–341 Single alternative decision structures, 132
strings, 445–446 Slices KAO Park
Secondary storage defined, 373 Harlow
defined, 27 example use, 373–375 CM17 9NA
devices, 27–28 general format, 373 United Kingdom
Seeds, random number, 270–271 invalid indexes and, 375
Seed value, 270 list, 373–376 and Associated Companies throughout the world
Selection structures. See Decision structures start and end index, 374
Visit us on the World Wide Web at: www.pearsonglobaleditions.com
Sentinels string, 437–438
defined, 204, 205 Software © Pearson Education Limited 2019
using, 205–206 application, 29
values, 204–205 defined, 23 The rights of Tony Gaddis to be identified as the author of this work has been asserted by him in accor-
Separators developers. See Programmers dance with the Copyright, Designs and Patents Act 1988.
comma, 92–93 development tools, 29
item, 88–89 operating system, 28 Authorized adaptation from the United States edition, entitled Starting Out with Python, 4th Edition,
split method, 451–452 requirements, 55 ISBN 978-0-13-444432-1 by Tony Gaddis, published by Pearson Education © 2018.
Sequences. See also Lists system, 28–29
accepting as argument, 383–384 types of, 28 All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted
defined, 365 utility programs, 28 in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without either
length, returning, 369 Sorting, item list, 381–382 the prior written permission of the publisher or a license permitting restricted copying in the United Kingdom
tuples, 402–404 sort method, 378, 381–382
issued by the Copyright Licensing Agency Ltd, Sa ron House, 6–10 Kirby Street, London EC1N 8TS.
Sequence structures Source code. See Code
with decision structure, 147 Specialization, 573–574 All trademarks used herein are the property of their respective owners. The use of any trademark in this
defined, 131 split method, 451 text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor
example, 131 Splitting strings, 451–452
does the use of such trademarks imply any a liation with or endorsement of this book by such owners.
nested inside decision structure, 148 sqrt() function, 285
structure, 147, 148 startswith method, 445, 446
British Library Cataloguing-in-Publication Data
use in programming, 131–132 Statements
Serializing objects for, 190, 194, 196 A catalogue record for this book is available from the British Library
defined, 496 assignment, 62–65
10 9 8 7 6 5 4 3 2 1
example, 498–500, 542–544 in blocks, 133, 235
pickle module, 496–497 breaking into multiple lines, 86–87 ISBN 10: 1-292-22575-0
unserializing, 500–502, 543–544 converting math formulas to, 83–85 ISBN 13: 978-1-292-22575-3
ServiceQuote class, 563–565 defined, 40
set function, 485 del, 383 Typeset by iEnergizer Aptara®, Ltd.
Printed and bound in Malaysia
738 Index
7
Index 735 8 Contents
Chapter 8 More About Strings 429 not operator, 155, 157 multiplication (*), 76, 79, 367
8.1 Basic String Operations 429 Nouns, list refining, 557–560 not in. See Not in operator
8.2 String Slicing 437 Numbers or, 155–157, 159, 160
advanced storage, 34 precedence, 79
8.3 Testing, Searching, and Manipulating Strings 441
binary, 31–32 relational, 133–134, 145–146
Review Questions 453 factorial of, 603–605 remainder (%), 76, 79, 82–83
Programming Exercises 456 Fibonacci, 607–609 repetition (*), 367, 450–451
floating-point, 33, 94 subtraction (−), 76, 79
Chapter 9 Dictionaries and Sets 461 formatting, 90–91 Optical devices, 28
9.1 Dictionaries 461 pseudorandom, 270–271 or operator, 155–157, 159, 160
9.2 Sets 484 random, 262–271 Output
9.3 Serializing Objects 496 running totals, 201–204 in computer program process, 57–58
storage, 31–33 data, 87–95
Review Questions 502
Numeric literals, 69 defined, 28
Programming Exercises 507 Numeric ranges, with logical operators, 160 displaying, 58–61
Output devices, 28
Chapter 10 Classes and Object-Oriented Programming 511 Output files, 310, 311, 315, 322, 326
10.1 Procedural and Object-Oriented Programming 511 O
Overhead, 602
Object-oriented programming (OOP)
10.2 Classes 515 class design, 554–565
Overriding, method, 588
10.3 Working with Instances 532 classes, 515–532
10.4 Techniques for Designing Classes 554 data hiding, 512
P
pack method, 625–627, 629, 634
Review Questions 565 defined, 512
Parameter lists, 252
Programming Exercises 568 encapsulation, 512
Parentheses, grouping with, 80
instances, 515, 532–554
Pascal, 39
Chapter 11 Inheritance 573 Objects, 629. See also Classes
Passing arguments. See also Arguments
11.1 Introduction to Inheritance 573 characteristics description, 515
to function, 248–251
11.2 Polymorphism 588 defined, 512
function parameter variable, 253–255
dictionary, 461–484
Review Questions 594 to index method, 379–381
everyday example of, 513–514
Programming Exercises 596 list as function, 389–390
exception, 359 multiple, 251–253
file, 316–317 and objects, 540–541
Chapter 12 Recursion 599 list, 365, 366 by position, 252
12.1 Introduction to Recursion 599 “is a” relationship, 574 by value, 255
12.2 Problem Solving with Recursion 602 passing as arguments, 540–541 Passwords, validating characters in, 446–449
12.3 Examples of Recursive Algorithms 606 pickling, 542–544 Pattern printing using nested loops, 215–218
Review Questions 614 reusability, 513 Percentages, calculations, 77–78
Programming Exercises 616 sequence, 365 Pickle module, 497–498, 542, 547
serializing, 496–502 Pickling, 496–498, 500, 542–544
Chapter 13 GUI Programming 619 set, 484–496 pi variable, 285
storing in dictionaries, 544–554 pie chart, plotting, 418–420
13.1 Graphical User Interfaces 619
storing in lists, 538–540 pip utility, 705
13.2 Using the tkinter Module 621 StringVar, 636–637 Pixels, 34
13.3 Display Text with Label Widgets 624 unpickling, 543–544 plot() function, 406–407
13.4 Organizing Widgets with Frames 627 open function, 313, 314, 318 Polymorphism
13.5 Button Widgets and Info Dialog Boxes 630 Operands, 76 behavior, ingredients of, 588
13.6 Getting Input with the Entry Widget 633 Operating systems, 28 defined, 588
Operators isinstance function, 591–594
13.7 Using Labels as Output Fields 636
and, 156–158 popitem method, 473, 477
13.8 Radio Buttons and Check Buttons 644 in. See In operator pop method, 472, 720
13.9 Drawing Shapes with the Canvas Widget 651 addition (+), 76, 79, 90 Positional arguments, 257
Review Questions 673 assignment, 135, 203–204 Precedence, operator, 79
Programming Exercises 676 augmented assignment, 203–204 Predefined names colors, 695–699
exponent (**), 76, 80–82 Pretest loops
logical. See Logical operators defined, 186
math, 75–76 while loops as, 186–187
Index 733 10 Contents
Error handlers, 209 defined, 607–608 The new Turtle Graphics sections are designed with flexibility in mind. They can be
Error messages, 41, 44 recursive function calculation, 608–609 assigned as optional material, incorporated into your existing syllabus, or skipped
default, displaying, 355–356 Field widths
altogether.
loop displaying, 208–209 columns, 93
traceback, 349, 351 minimum, specifying, 93–94 ● Chapter 2 has a new section on named constants. Although Python does not support
Errors. See Exceptions File modes, 317 true constants, you can create variable names that symbolize values that should not
Error traps, 209 Filename extensions, 312
change as the program executes. This section teaches the student to avoid the use
Escape characters, 89–90 File objects
Event handlers, callback functions as, 630 close method, 315, 497 of “magic numbers,” and to create symbolic names that make his or her code more
Exception handling defined, 312 self-documenting and easier to maintain.
defined, 352 read method, 316–319 ● Chapter 7 has a new section on using the matplotlib package to plot charts and graphs
multiple exceptions, 352–355 variable name referencing, 312–314 from lists. The new section describes how to install the matplotlib package, and use it to
with try/except statement, 357–358 writelines method, 395–398
plot line graphs, bar charts, and pie charts.
Exception objects, 359 write method, 314
Exceptions finally clause, with try/except statement, 358
● Chapter 13 has a new section on creating graphics in a GUI application with the
catching all, with one except clause, 354–355 Finally suite, 358 Canvas widget. The new section describes how to use the Canvas widget to draw lines,
code response to, 348 find method, 446 rectangles, ovals, arcs, polygons, and text.
default error message display, 355–356 Flags, 162 ● Several new, more challenging, programming problems have been added throughout
defined, 75, 346 Flash drives, 28 the book.
IndexError, 368–369, 433 Flash memory, 28
IOError, 351–352, 354, 358 float data type, 69, 85–86
● Appendix E is a new appendix that discusses the various forms of the import statement.
KeyError, 463, 465, 487 float() function, 73, 74, 75, 86
● Appendix F is a new appendix that discusses installing third-party modules with the
multiple, 352–354 Floating-point division, 78, 79 pip utility.
unhandled, 358–359 Floating-point notation, 33
ValueError, 349–350, 354, 355, Floating-point numbers, 94
356, 358, 382 floor() function, 285 Brief Overview of Each Chapter
ZeroDivisionError, 358 Floppy disk drives, 27
Execution, 223 Flowchart, 56
in fetch-decode-execute cycle, 36 clock simulator, 213
Chapter 1: Introduction to Computers and Programming
pausing, 244 decision structure, 132, 133, 137 This chapter begins by giving a very concrete and easy-to-understand explanation of how
Python interpreter, 686–687 dual alternative decision structure, 130
computers work, how data is stored and manipulated, and why we write programs in high-
try/except statement, 349 input validation loop, 208
while loop, 209 logic for file end detection, 328 level languages. An introduction to Python, interactive mode, script mode, and the IDLE
Exercises nested decision structure, 149, 152 environment are also given.
decision structures, 173–179 pay calculating program, 57
dictionaries and sets, 507–510 program development cycle, 53
files and exceptions, 366–368 running total calculation, 201 Chapter 2: Input, Processing, and Output
functions, 302–308 sequence structure nested inside decision
This chapter introduces the program development cycle, variables, data types, and simple
GUI programming, 676–679 structure, 148
inheritance, 596–597 sequence structures with decision structure, 147–148 programs that are written as sequence structures. The student learns to write simple pro-
input, processing, and output, 126–130 while loop, 183 grams that read input from the keyboard, perform mathematical operations, and produce
introduction, 50–51 Font class, 670–672 screen output. Pseudocode and flowcharts are also introduced as tools for designing pro-
lists and tuples, 424–428 keyword arguments for, 671 grams. The chapter also includes an optional introduction to the turtle graphics library.
programming, 568–572 for loops. See also Loops
recursion, 616–617 as count-controlled loops, 190–200
repetition structures, 265–267 defined, 190–191 Chapter 3: Decision Structures and Boolean Logic
strings, 456–460 in turtle graphics, 219
exp() function, 285 iterating lists with, 368 In this chapter, the student learns about relational operators and Boolean expressions and is
Exponent (**) operator, 76, 80–82 iterating over dictionaries with, 468–469 shown how to control the flow of a program with decision structures. The if, if-else, and
iterating over list of strings with, 192 if-elif-else statements are covered. Nested decision structures and logical operators are
F iterating over sets, 488
discussed as well. The chapter also includes an optional turtle graphics section, with a discus-
Factorial function, 604–605 iterations, 198–200
Factorials iterations, user control, 198–200 sion of how to use decision structures to test the state of the turtle.
calculation with recursion, 602–606 range function with, 190–194
definition rules, 606, 609 target variables, 194–198
Fetch-decode-execute cycle, 36–37 format function, 91, 94
Chapter 4: Repetition Structures
Fibonacci series Format specifiers, 91–94 This chapter shows the student how to create repetition structures using the while loop and
for loop. Counters, accumulators, running totals, and sentinels are discussed, as well as
Preface 15 728 Index
techniques for writing input validation loops. The chapter also includes an optional section create_polygon method, 665–667 defined, 461
on using loops to draw designs with the turtle graphics library. optional arguments to, 667 elements, adding, 464
create_rectangle method, 655–657 elements, deleting, 465, 469
optional arguments to, 657 elements, display order, 462
Chapter 5: Functions create_text method, 667–672 elements, number of, 465–466
optional arguments to, 669 empty, creating, 467–468
In this chapter, the student first learns how to write and call void functions. The chapter C# programming language, 39 example, 474–477, 477–483
shows the benefits of using functions to modularize programs and discusses the top-down Customer class, 561–562 iteration, 468–469
design approach. Then, the student learns to pass arguments to functions. Common library keys, 461, 462
functions, such as those for generating random numbers, are discussed. After learning how D key-value pairs, 461, 464
Data methods, 469–474
to call library functions and use their return value, the student learns to define and call his mixing data types in, 466–467
appending to files, 322
or her own functions. Then the student learns how to use modules to organize functions. An binary file, 311 parts of, 461
optional section includes a discussion of modularizing turtle graphics code with functions. digital, 34 retrieving value from, 462–463
hiding, 512 storing objects in, 544–554
output, 87–95 values, 463–464
Chapter 6: Files and Exceptions processing, 333–346 Dictionary views
reading from files, 310–311, 316–319 defined, 470
This chapter introduces sequential file input and output. The student learns to read and write
text file, 311 elements, 470
large sets of data and store data as fields and records. The chapter concludes by discussing keys returned as, 471
writing to files, 310, 314–316
exceptions and shows the student how to write exception-handling code. Data attributes, 512 values returned as, 473–474
hidden, 513 dict() method, 468
hiding, 522–525 difference method, 490–491
Chapter 7: Lists and Tuples Digital data, 34
initializing, 518
This chapter introduces the student to the concept of a sequence in Python and explores the instance, 532–554 Digital devices, 34
Data storage, 29–33 Direct access files, 312, 343, 346
use of two common Python sequences: lists and tuples. The student learns to use lists for
characters, 33 Direct recursion, 606
arraylike operations, such as storing objects in a list, iterating over a list, searching for items music, 34 discard method, 487
in a list, and calculating the sum and average of items in a list. The chapter discusses slic- Data types Disk drives
ing and many of the list methods. One- and two-dimensional lists are covered. The chapter bool, 161 defined, 27
also includes a discussion of the matplotlib package, and how to use it to plot charts and conversion and mixed-type expressions, 85–86 program storage on, 36
graphs from lists. and literals, 68–69 Divide and conquer approach, 232
mixing, 466–467 Division
str, 69–70 floating-point, 78
Chapter 8: More About Strings Debugging, 54, 154 integer, 76, 78
global variables and, 258–259 / operator, 76, 78, 79
In this chapter, the student learns to process strings at a detailed level. String slicing and Decision structures, 132 Dog class, 589–590
algorithms that step through the individual characters in a string are discussed, and several actions performed in, 132–133 Dot notation, 263, 285
built-in functions and string methods for character and text processing are introduced. combining sequence structures with, 147–148 Dual alternative decision structure,
dual alternative, 140 139–140
in flowcharts, 132 dump method, 497
Chapter 9: Dictionaries and Sets if-elif-else statement, 153–154 DVD drives, 28
if-else statement, 140–143 DVDs (digital versatile discs), 28
This chapter introduces the dictionary and set data structures. The student learns to store data if statement, 131–139
as key-value pairs in dictionaries, search for values, change existing values, add new key-value inside, 148 E
pairs, and delete key-value pairs. The student learns to store values as unique elements in sets nested, 147–155 else clause, 143, 150
and perform common set operations such as union, intersection, di erence, and symmetric single alternative, 132 execution, 140
degrees() function, 285 with try/except statement, 357–358
di erence. The chapter concludes with a discussion of object serialization and introduces the
del statement, 383 else suite, 357
student to the Python pickle module. Depth of recursion, 602 Encapsulation, 512
Derived classes, 574 end–of–file, 500–501, 543
Chapter 10: Classes and Object-Oriented Programming Dialog boxes endswith method, 445, 446
defined, 619 ENIAC computer, 25, 26
This chapter compares procedural and object-oriented programming practices. It covers the illustrated, 620–621 Entry widget
fundamental concepts of classes and objects. Attributes, methods, encapsulation and data info, 630–633 defined, 622, 633
Dictionaries getting input with, 633–636
hiding, _ _init_ _ functions (which are similar to constructors), accessors, and mutators are
creating, 462 use example, 634–636
discussed. The student learns how to model classes with UML and how to find the classes
in a particular problem.
Index 727 16 Preface
VideoNotes Online videos developed specifically for this book are available
for viewing at www.pearsonglobaleditions.com/gaddis. Icons appear
throughout the text alerting the student to videos about specific
topics.
Notes Notes appear at several places throughout the text. They are
short explanations of interesting or often misunderstood points
relevant to the topic at hand.
Index Tips Tips advise the student on the best techniques for approaching
di erent programming problems.
Warnings Warnings caution students about programming techniques or
practices that can lead to malfunctioning programs or lost data.
Checkpoints Checkpoints are questions placed at intervals throughout each
chapter. They are designed to query the student’s knowledge
Symbols defined, 134 quickly after learning a new topic.
!= operator in string comparisons, 144
defined, 136 use example, 138 Review Questions Each chapter presents a thorough and diverse set of review
example use, 136, 138 > operator questions and exercises. They include Multiple Choice, True/
" (double-quote marks), 60 defined, 134 False, Algorithm Workbench, and Short Answer.
""" or "' (triple quotes), 60 in string comparisons, 146
# character, 61 use example, 134, 135–136 Programming Each chapter o ers a pool of programming exercises designed
% (remainder) operator >= operator Exercises to solidify the student’s knowledge of the topics currently being
defined, 76, 82 defined, 134 studied.
function of, 281 in superset determination, 492
%= operator, 203 relationship testing, 135
& operator, for intersection of sets, 490 >>> prompt, 43, 44
Supplements
' (single-quote marks), 59–60 ^ operator, 491
* operator _ _init_ _ method, 521, 555, 561, 563, 583 Student Online Resources
multiplication, 76 {}(curly braces), 462
Many student resources are available for this book from the publisher. The following items
repetition, 367
are available at www.pearsonglobaleditions.com/gaddis
** (exponent) operator, 76, 80–82 A
*= operator, 203 Accessor methods, 537 ● The source code for each example program in the book
+ operator acos(x) function, 285 ● Access to the book’s companion VideoNotes
defined, 76 Actions
displaying multiple items with, 90 conditionally executed, 132
in list concatenation, 371 in decision structures, 133 Instructor Resources
+= operator Ada programming language, 39
defined, 203
The following supplements are available to qualified instructors only:
Addition (+) operator
in list concatenation, 372 defined, 76 ● Answers to all of the Review Questions
in string concatenation, 435 displaying multiple items with, 90 ● Solutions for the exercises
− (subtraction) operator, 76 precedence, 79
_ _str_ _ method, 529–532 add method, 486
● PowerPoint presentation slides for each chapter
−= operator, 203 Algebraic expressions, 83–84 ● Test bank
/ (division) operator, 76, 78 Algorithms
// (integer division) operator, 76, 78 defined, 55 Visit the Pearson Instructor Resource Center (www.pearsonglobaleditions.com/gaddis) or
/= operator, 203 example, 55 contact your local Pearson campus representative for information on how to access them.
= operator recursive, 602, 603, 606–613
defined, 134 and operator
in subset determination, 492 defined, 156
relationship testing, 135 false, 158
= (assignment) operator, 135 short-circuit evaluation, 157
== operator truth table, 156
assignment operator versus, 136 Appending data, 322
725
Preface 19 724 Appendix G Answers to Checkpoints
I would like to thank the following faculty reviewers for their insight, expertise, and thought- 13.16 You would use check buttons.
ful recommendations: 13.17 When you create a group of Radiobuttons, you associate them all with
Sonya Dennis Anita Sutton the same IntVar object. You also assign a unique integer value to each
Morehouse College Germanna Community College Radiobutton widget. When one of the Radiobutton widgets is selected,
it stores its unique integer value in the IntVar object.
Diane Innes Christopher Urban
Sandhills Community College SUNY Institute of Technology 13.18 You associate a different IntVar object with each Checkbutton. When a
Checkbutton is selected, its associated IntVar object will hold the value 1.
John Kinuthia Nanette Veilleux When a Checkbutton is deselected, its associated IntVar object will hold the
Nazareth College of Rochester Simmons College value 0.
Frank Liu Brent Wilson 13.19 (0, 0)
Sam Houston State University George Fox University
13.20 (139, 479)
Haris Ribic
SUNY at Binghamton 13.21 With the Canvas widget, the point (0, 0) is in the upper-left corner of the
window. In turtle graphics, the point (0, 0) is in the center of the window.
Reviewers of Previous Editions Also, with the Canvas widget, the Y coordinates increase as you move down
Paul Amer Shyamal Mitra the screen. In turtle graphics, the Y coordinates decrease as you move down
University of Delaware University of Texas at Austin the screen.
Chapter 12 I would also like to thank my family and friends for their support in all of my projects.
I am extremely fortunate to have Matt Goldstein as my editor, and Kristy Alaura as edito-
12.1 A recursive algorithm requires multiple method calls. Each method call rial assistant. Their guidance and encouragement make it a pleasure to write chapters and
requires several actions to be performed by the JVM. These actions include meet deadlines. I am also fortunate to have Demetrius Hall as my marketing manager. His
allocating memory for parameters and local variables and storing the address hard work is truly inspiring, and he does a great job of getting this book out to the academic
of the program location where control returns after the method terminates. community. The production team, led by Sandra Rodriguez, worked tirelessly to make this
All these actions are known as overhead. In an iterative algorithm, which book a reality. Thanks to you all!
uses a loop, such overhead is unnecessary.
12.2 A case in which the problem can be solved without recursion Acknowledgments for the Global Edition
12.3 Cases in which the problem is solved using recursion Pearson would like to thank and acknowledge the following for their contributions to the
12.4 When it reaches the base case Global Edition.
12.5 In direct recursion, a recursive method calls itself. In indirect recursion, Contributor
method A calls method B, which in turn calls method A. Gregory Baatard, Edith Cowan University
Kenneth Eustace, Charles Sturt University
Chapter 13 Reviewers
Lindsay Ward, James Cook University
13.1 The part of a computer and its operating system with which the user
Ajay Mittal, University Institute of Engineering and Technology
interacts
Khyat Sharma
13.2 A command line interface typically displays a prompt, and the user types a
command, which is then executed. About the Author
13.3 The program Tony Gaddis is the principal author of the Starting Out with series of textbooks. Tony has
13.4 A program that responds to events that take place, such as the user clicking a nearly two decades of experience teaching computer science courses at Haywood Com-
button munity College. He is a highly acclaimed instructor who was previously selected as the
North Carolina Community College “Teacher of the Year” and has received the Teaching
13.5 a) Label—An area that displays one line of text or an image Excellence award from the National Institute for Sta and Organizational Development.
b) Entry—An area in which the user may type a single line of input from the The Starting Out with series includes introductory books covering C++, Java™, Microsoft®
keyboard Visual Basic®, Microsoft® C#®, Python®, Programming Logic and Design, Alice, and App
c) Button—A button that can cause an action to occur when it is clicked Inventor, all published by Pearson.
d) Frame—A container that can hold other widgets
13.6 You create an instance of the tkinter module’s Tk class.
13.7 This function runs like an infinite loop until you close the main window.
13.8 The pack method arranges a widget in its proper position, and it makes the
widget visible when the main window is displayed.
13.9 One will be stacked on top of the other.
13.10 side=–left—
13.11 You use an Entry widget’s get method to retrieve the data that the user has
typed into the widget.
13.12 It is a string.
13.13 tkinter
13.14 Any value that is stored in the StringVar object will automatically be
displayed in the Label widget.
722 Appendix G Answers to Checkpoints
Chapter 11
11.1 A superclass is a general class, and a subclass is a specialized class.
11.2 When one object is a specialized version of another object, there is an “is a”
relationship between them. The specialized object “is a” version of the
general object.
11.3 It inherits all the superclass’s attributes.
11.4 Bird is the superclass, and Canary is the subclass.
9.25 If the specified element to delete is not in the set, the remove method raises a
KeyError exception, but the discard method does not raise an exception.
9.26 You can use the in operator to test for the element.
9.27 {10, 20, 30, 100, 200, 300}
9.28 {3, 4}
9.29 {1, 2}
9.30 {5, 6}
9.33 The process of converting the object to a stream of bytes that can be saved to
a file for later retrieval.
9.34 'wb'
9.35 'rb'
9.38 pickle.load
Chapter 9
9.1 Key and value
9.2 The key
9.3 The string 'start' is the key, and the integer 1472 is the value.
Introduction to Computers
CHAPTE R
1
9.4 It stores the key-value pair 'id' : 54321 in the employee dictionary.
Computers can perform such a wide variety of tasks because they can be programmed. This 9.18 The set will contain one element: 25.
means that computers are not designed to do just one job, but to do any job that their pro-
9.19 The set will contain these elements (in no particular order): 'w', ' ', 'x',
grams tell them to do. A program is a set of instructions that a computer follows to perform
'y', and 'z'.
a task. For example, Figure 1-1 shows screens using Microsoft Word and PowerPoint, two
commonly used programs. 9.20 The set will contain these elements (in no particular order): 1, 2, 3, and 4.
Programs are commonly referred to as software. Software is essential to a computer because 9.21 The set will contain these elements (in no particular order): 'www', 'xxx',
it controls everything the computer does. All of the software that we use to make our com- 'yyy', and 'zzz'.
puters useful is created by individuals working as programmers or software developers. A
9.22 You pass the set as an argument to the len function.
programmer, or software developer, is a person with the training and skills necessary to
design, create, and test computer programs. Computer programming is an exciting and 9.23 The set will contain these elements (in no particular order): 10, 9, 8, 1, 2,
rewarding career. Today, you will find programmers’ work used in business, medicine, gov- and 3.
ernment, law enforcement, agriculture, academics, entertainment, and many other fields. 9.24 The set will contain these elements (in no particular order): 10, 9, 8, 'a',
This book introduces you to the fundamental concepts of computer programming using the 'b', and 'c'.
Python language. The Python language is a good choice for beginners because it is easy to learn
23
Appendix G Answers to Checkpoints 719 24 Chapter 1 Introduction to Computers and Programming
Then, each element in the list will become a slice in the pie chart. The size of Figure 1-1 A word processing program and an image editing program
a slice represents that element’s value as a percentage of the whole.
Chapter 8
8.1 for letter in name:
print(letter)
8.2 0
8.3 9
8.4 An IndexError exception will occur if you try to use an index that is out of
range for a particular string.
8.5 Use the built-in len function.
8.6 The second statement attempts to assign a value to an individual character
in the string. Strings are immutable, however, so the expression animal[0]
cannot appear on the left side of an assignment operator.
8.7 cde and programs can be written quickly using it. Python is also a powerful language, popular with
professional software developers. In fact, it has been reported that Python is used by Google,
8.8 defg NASA, YouTube, various game companies, the New York Stock Exchange, and many others.
8.9 abc Before we begin exploring the concepts of programming, you need to understand a few
8.10 abcdefg basic things about computers and how they work. This chapter will build a solid founda-
tion of knowledge that you will continually rely on as you study computer science. First,
8.11 if 'd' in mystring: we will discuss the physical components of which computers are commonly made. Next, we
print('Yes, it is there.')
will look at how computers store data and execute programs. Finally, you will get a quick
8.12 little = big.upper() introduction to the software that you will use to write Python programs.
8.13 if ch.isdigit():
print('Digit')
else: 1.2 Hardware and Software
print('No digit')
8.14 a A CONCEPT : The physical devices of which a computer is made are referred to as the
computer’s hardware. The programs that run on a computer are referred
8.15 again = input('Do you want to repeat ' + to as software.
'the program or quit? (R/Q) ')
while again.upper() != 'R' and again.upper() != 'Q': Hardware
again = input('Do you want to repeat the ' +
'program or quit? (R/Q) ') The term hardware refers to all of the physical devices, or components, of which a computer
is made. A computer is not one single device, but a system of devices that all work toge-
8.16 $ ther. Like the different instruments in a symphony orchestra, each device in a computer
8.17 for letter in mystring: plays its own part.
if letter.isupper(): If you have ever shopped for a computer, you’ve probably seen sales literature listing compo-
count += 1
nents such as microprocessors, memory, disk drives, video displays, graphics cards, and so on.
8.18 my_list = days.split() Unless you already know a lot about computers, or at least have a friend that does, under-
standing what these different components do might be challenging. As shown in Figure 1-2, a
8.19 my_list = values.split('$')
typical computer system consists of the following major components:
The central processing unit (CPU)
Main memory
1.2 Hardware and Software 25 718 Appendix G Answers to Checkpoints
Figure 1-2 Typical components of a computer system 7.17 You would use statement b, names.append('Wendy'). This is because
element 0 does not exist. If you try to use statement a, an error will occur.
7.18 a) The index method searches for an item in the list and returns the index of
the first element containing that item.
b) The insert method inserts an item into the list at a specified index.
Shutterstock
Central Processing c) The sort method sorts the items in the list to appear in ascending order.
Shutterstock
Unit
d) The reverse method reverses the order of the items in the list.
iko/Shutterstock
7.19 The list contains 4 rows and 2 columns.
Shutterstock
Feng Yu/Shutterstock
Output
Aquila/ Devices 7.20 mylist = [[0, 0, 0, 0], [0, 0, 0, 0],
[0, 0, 0, 0], [0, 0, 0, 0]]
Chiyacat/
Shutterstock 7.21 for r in range(4):
Peter Guess/
Shutterstock
for c in range(2):
Input
Devices
print(numbers[r][c])
jocic/Shutterstock
7.22 The primary difference between tuples and lists is that tuples are immutable.
Eikostas/Shutterstock
That means that once a tuple is created, it cannot be changed.
Main Memory
(RAM) 7.23 Here are three reasons:
Lusoimages/Shutterstock
Processing a tuple is faster than processing a list, so tuples are good
tkemot/Shutterstock Secondary
Storage Devices choices when you are processing lots of data and that data will not be
modified.
Tuples are safe. Because you are not allowed to change the contents of a
tuple, you can store data in one and rest assured that it will not be modified
(accidentally or otherwise) by any code in your program.
There are certain operations in Python that require the use of a tuple.
Vitaly Korovin/Shutterstock Andre Nitsievsky/Shutterstock.
7.24 my_tuple = tuple(my_list)
Secondary storage devices 7.25 my_list = list(my_tuple)
Input devices
Output devices 7.26 Two lists: one holding the X coordinates of the data points, and the other
holding the Y coordinates.
Let’s take a closer look at each of these components.
7.27 A line graph
The CPU 7.28 Use the xlabel and ylabel functions.
When a computer is performing the tasks that a program tells it to do, we say that the 7.29 Call the xlim and ylim functions, passing values for the xmin, xmax, ymin,
computer is running or executing the program. The central processing unit, or CPU, is the and ymax keyword arguments.
part of a computer that actually runs programs. The CPU is the most important component
7.30 Call the xticks and yticks functions. You pass two arguments to these
in a computer because without it, the computer could not run software.
functions. The first argument is a list of tick-mark locations, and the second
In the earliest computers, CPUs were huge devices made of electrical and mechanical com- argument is a list of labels to display at the specified locations.
ponents such as vacuum tubes and switches. Figure 1-3 shows such a device. The two
7.31 Two lists: one containing the X coordinates of each bar’s left edge, and
women in the photo are working with the historic ENIAC computer. The ENIAC, which
another containing the heights of each bar, along the Y axis.
is considered by many to be the world’s first programmable electronic computer, was built
in 1945 to calculate artillery ballistic tables for the U.S. Army. This machine, which was 7.32 The bars will be red, blue, red, and blue.
primarily one big CPU, was 8 feet tall, 100 feet long, and weighed 30 tons. 7.33 You pass a list of values as an argument. The pie function will calculate
Today, CPUs are small chips known as microprocessors. Figure 1-4 shows a photo of a lab the sum of the values in the list, then use that sum as the value of the whole.
technician holding a modern microprocessor. In addition to being much smaller than the old
electromechanical CPUs in early computers, microprocessors are also much more powerful.
Appendix G Answers to Checkpoints 717 26 Chapter 1 Introduction to Computers and Programming
6.18 You copy all the original file’s records to the temporary file, except for the Figure 1-3 The ENIAC computer
record that is to be deleted. The temporary file then takes the place of the
original file. You delete the original file and rename the temporary file, giving
it the name that the original file had on the computer’s disk.
6.19 An exception is an error that occurs while a program is running. In most
cases, an exception causes a program to abruptly halt.
6.20 The program halts.
6.21 IOError
6.22 ValueError
Chapter 7
7.1 [1, 2, 99, 4, 5]
7.2 [0, 1, 2]
7.4 1
courtesy of U.S. Army Historic Computer Images
3
5
7
9
Figure 1-4 A lab technician holds a modern microprocessor
7.5 4
7.8 [1, 2, 3]
[10, 20, 30, 1, 2, 3]
7.9 [2, 3]
7.10 [2, 3]
7.11 [1]
7.12 [1, 2, 3, 4, 5]
7.13 [3, 4, 5]
7.15 The remove method searches for and removes an element containing a
Creativa/Shutterstock
specific value. The del statement removes an element at a specific index.
7.16 You can use the built-in min and max functions.
1.2 Hardware and Software 27 716 Appendix G Answers to Checkpoints
Main Memory has not been converted to text. As a consequence, you cannot view the con-
tents of a binary file with a text editor.
You can think of main memory as the computer’s work area. This is where the computer
stores a program while the program is running, as well as the data that the program is 6.5 Sequential and direct access. When you work with a sequential access file,
working with. For example, suppose you are using a word processing program to write an you access data from the beginning of the file to the end of the file. When
essay for one of your classes. While you do this, both the word processing program and the you work with a direct access file, you can jump directly to any piece of data
essay are stored in main memory. in the file without reading the data that comes before it.
Main memory is commonly known as random-access memory, or RAM. It is called this 6.6 The file’s name on the disk and the name of a variable that references a file
because the CPU is able to quickly access data stored at any random location in RAM. object.
RAM is usually a volatile type of memory that is used only for temporary storage while
6.7 The file’s contents are erased.
a program is running. When the computer is turned off, the contents of RAM are erased.
Inside your computer, RAM is stored in chips, similar to the ones shown in Figure 1-5. 6.8 Opening a file creates a connection between the file and the program. It also
creates an association between the file and a file object.
6.9 Closing a file disconnects the program from the file.
Figure 1-5 Memory chips
6.10 A file’s read position marks the location of the next item that will be read
from the file. When an input file is opened, its read position is initially set to
the first item in the file.
6.11 You open the file in append mode. When you write data to a file in append
mode, the data is written to the end of the file’s existing contents.
Garsya/Shutterstock 6.12 outfile = open('numbers.txt', 'w')
for num in range(1, 11):
outfile.write(str(num) + '\n')
outfile.close()
Secondary Storage Devices
6.13 The readline method returns an empty string ('') when it has attempted to
Secondary storage is a type of memory that can hold data for long periods of time, even
read beyond the end of a file.
when there is no power to the computer. Programs are normally stored in secondary mem-
ory and loaded into main memory as needed. Important data, such as word processing 6.14 infile = open('numbers.txt', 'r')
documents, payroll data, and inventory records, is saved to secondary storage as well. line = infile.readline()
while line != '':
The most common type of secondary storage device is the disk drive. A traditional disk
print(line)
drive stores data by magnetically encoding it onto a spinning circular disk. Solid-state
line = infile.readline()
drives, which store data in solid-state memory, are increasingly becoming popular. A solid-
state drive has no moving parts and operates faster than a traditional disk drive. Most in le.close()
computers have some sort of secondary storage device, either a traditional disk drive or a 6.15 infile = open('data.txt', 'r')
solid-state drive, mounted inside their case. External storage devices, which connect to one for line in infile:
of the computer’s communication ports, are also available. External storage devices can print(line)
be used to create backup copies of important data or to move data to another computer. infile.close()
In addition to external storage devices, many types of devices have been created for copy- 6.16 A record is a complete set of data that describes one item, and a field is a
ing data and for moving it to other computers. For example, USB drives are small devices single piece of data within a record.
that plug into the computer’s USB (universal serial bus) port and appear to the system as
a disk drive. These drives do not actually contain a disk, however. They store data in a 6.17 You copy all the original file's records to the temporary file, but when you
special type of memory known as flash memory. USB drives, which are also known as get to the record that is to be modified, you do not write its old contents
memory sticks and flash drives, are inexpensive, reliable, and small enough to be carried to the temporary file. Instead, you write its new, modified values to the
in your pocket. temporary file. Then, you finish copying any remaining records from the
original file to the temporary file.
Appendix G Answers to Checkpoints 715 28 Chapter 1 Introduction to Computers and Programming
be changed during the program’s execution, you do not have to worry about Optical devices such as the CD (compact disc) and the DVD (digital versatile disc) are
its value being altered. also popular for data storage. Data is not recorded magnetically on an optical disc, but is
encoded as a series of pits on the disc surface. CD and DVD drives use a laser to detect
5.21 The difference is that a value returning function returns a value back to the
the pits and thus read the encoded data. Optical discs hold large amounts of data, and
statement that called it. A simple function does not return a value.
for that reason, recordable CD and DVD drives are commonly used for creating backup
5.22 A prewritten function that performs some commonly needed task copies of data.
5.23 The term “black box” is used to describe any mechanism that accepts input,
performs some operation (that cannot be seen) using the input, and produces Input Devices
output.
Input is any data the computer collects from people and from other devices. The compo-
5.24 It assigns a random integer in the range of 1 through 100 to the variable x. nent that collects the data and sends it to the computer is called an input device. Common
5.25 It prints a random integer in the range of 1 through 20. input devices are the keyboard, mouse, touchscreen, scanner, microphone, and digital cam-
era. Disk drives and optical drives can also be considered input devices, because programs
5.26 It prints a random integer in the range of 10 through 19. and data are retrieved from them and loaded into the computer’s memory.
5.27 It prints a random floating-point number in the range of 0.0 up to, but not
including, 1.0.
Output Devices
5.28 It prints a random floating-point number in the range of 0.1 through 0.5.
Output is any data the computer produces for people or for other devices. It might be
5.29 It uses the system time, retrieved from the computer’s internal clock. a sales report, a list of names, or a graphic image. The data is sent to an output device,
5.30 If the same seed value were always used, the random number functions which formats and presents it. Common output devices are video displays and printers.
would always generate the same series of pseudorandom numbers. Disk drives can also be considered output devices because the system sends data to them
in order to be saved.
5.31 It returns a value back to the part of the program that called it.
Software Development Tools Software development tools are the programs that pro- 5.5 When a program is developed as a set of functions in which each performs
grammers use to create, modify, and test software. Assemblers, compilers, and interpret- an individual task, then different programmers can be assigned the job of
ers are examples of programs that fall into this category. writing different functions.
5.6 A function definition has two parts: a header and a block. The header
Application Software indicates the starting point of the function, and the block is a list of
statements that belong to the function.
Programs that make a computer useful for everyday tasks are known as application soft-
ware. These are the programs that people normally spend most of their time running on 5.7 To call a function means to execute the function.
their computers. Figure 1-1, at the beginning of this chapter, shows screens from two com- 5.8 When the end of the function is reached, the computer returns back to the
monly used applications: Microsoft Word, a word processing program, and PowerPoint, a part of the program that called the function, and the program resumes
presentation program. Some other examples of application software are spreadsheet pro- execution at that point.
grams, email programs, web browsers, and game programs.
5.9 Because the Python interpreter uses the indentation to determine where a
block begins and ends
Checkpoint
5.10 A local variable is a variable that is declared inside a function. It belongs to
1.1 What is a program?
the function in which it is declared, and only statements in the same function
1.2 What is hardware? can access it.
1.3 List the five major components of a computer system.
5.11 The part of a program in which a variable may be accessed
1.4 What part of the computer actually runs programs?
5.12 Yes, it is permissible.
1.5 What part of the computer serves as a work area to store a program and its data
while the program is running? 5.13 Arguments
1.6 What part of the computer holds data for long periods of time, even when there is 5.14 Parameters
no power to the computer?
5.15 A parameter variable’s scope is the entire function in which the parameter is
1.7 What part of the computer collects data from people and from other devices?
declared.
1.8 What part of the computer formats and presents data for people or other devices?
5.16 No, it does not.
1.9 What fundamental set of programs control the internal operations of the
computer’s hardware? 5.17 a. passes by keyword argument
1.10 What do you call a program that performs a specialized task, such as a virus b. passes by position
scanner, a file compression program, or a data backup program? 5.18 The entire program
1.11 Word processing programs, spreadsheet programs, email programs, web browsers,
5.19 Here are three:
and game programs belong to what category of software?
Global variables make debugging difficult. Any statement in a program can
change the value of a global variable. If you find that the wrong value is being
stored in a global variable, you have to track down every statement that
1.3 How Computers Store Data accesses it to determine where the bad value is coming from. In a program
with thousands of lines of code, this can be difficult.
CONCEPT: All data that is stored in a computer is converted to sequences of 0s Functions that use global variables are usually dependent on those variables.
and 1s. If you want to use such a function in a different program, you will most likely
have to redesign it so it does not rely on the global variable.
A computer’s memory is divided into tiny storage locations known as bytes. One byte is Global variables make a program hard to understand. A global variable
only enough memory to store a letter of the alphabet or a small number. In order to do can be modified by any statement in the program. If you are to understand
anything meaningful, a computer has to have lots of bytes. Most computers today have any part of the program that uses a global variable, you have to be aware
millions, or even billions, of bytes of memory. of all the other parts of the program that access the global variable.
Each byte is divided into eight smaller storage locations known as bits. The term bit stands 5.20 A global constant is a name that is available to every function in the
for binary digit. Computer scientists usually think of bits as tiny switches that can be either program. It is permissible to use global constants. Because their value cannot
Appendix G Answers to Checkpoints 713 30 Chapter 1 Introduction to Computers and Programming
4.13 A variable that is used to accumulate the total of a series of numbers on or off. Bits aren’t actual “switches,” however, at least not in the conventional sense. In
most computer systems, bits are tiny electrical components that can hold either a positive
4.14 Yes, it should be initialized with the value 0. This is because values are added
or a negative charge. Computer scientists think of a positive charge as a switch in the on
to the accumulator by a loop. If the accumulator does not start at the value 0,
position, and a negative charge as a switch in the off position. Figure 1-6 shows the way
it will not contain the correct total of the numbers that were added to it when
that a computer scientist might think of a byte of memory: as a collection of switches that
the loop ends.
are each flipped to either the on or off position.
4.15 15
4.16 15
Figure 1-6 Think of a byte as eight switches
5
4.17 a) quantity += 1 ON ON ON ON
b) days_left −= 5
c) price *= 10
d) price /= 2
4.18 A sentinel is a special value that marks the end of a list of items.
4.19 A sentinel value must be unique enough that it will not be mistaken as a OFF OFF OFF OFF
regular value in the list.
4.20 It means that if bad data (garbage) is provided as input to a program, the
program will produce bad data (garbage) as output. When a piece of data is stored in a byte, the computer sets the eight bits to an on/off
4.21 When input is given to a program, it should be inspected before it is pattern that represents the data. For example, the pattern on the left in Figure 1-7 shows
processed. If the input is invalid, then it should be discarded and the user how the number 77 would be stored in a byte, and the pattern on the right shows how the
should be prompted to enter the correct data. letter A would be stored in a byte. We explain below how these patterns are determined.
4.22 The input is read, then a pretest loop is executed. If the input data is invalid,
the body of the loop executes. In the body of the loop, an error message is Figure 1-7 Bit patterns for the number 77 and the letter A
displayed so the user will know that the input was invalid, and then the
input read again. The loop repeats as long as the input is invalid. ON ON ON ON ON ON
4.23 It is the input operation that takes place just before an input validation loop.
The purpose of the priming read is to get the first input value.
4.24 None OFF
OFF OFF OFF OFF OFF OFF OFF OFF OFF
The position of each digit in a binary number has a value assigned to it. Starting with 3.26 You use the turtle.pencolor() function to determine the pen color.
the rightmost digit and moving left, the position values are 20, 21, 22, 23, and so forth, as You use the turtle.fillcolor() function to determine the current fill
shown in Figure 1-8. Figure 1-9 shows the same diagram with the position values calcu- color. You use the turtle.bgcolor() function to determine the current
lated. Starting with the rightmost digit and moving left, the position values are 1, 2, 4, 8, background color of the turtle’s graphics window.
and so forth.
3.27 You use the turtle.pensize() function.
3.28 You use the turtle.speed() function.
Figure 1-8 The values of binary digits as powers of 2
10011101 Chapter 4
0 4.1 A structure that causes a section of code to repeat
2
21 4.2 A loop that uses a true/false condition to control the number of times that it
22
23 repeats
24
25 4.3 A loop that repeats a specific number of times
26
27 4.4 An execution of the statements in the body of the loop
4.5 Before
Figure 1-9 The values of binary digits 4.6 None. The condition count < 0 will be false to begin with.
4.7 A loop that has no way of stopping and repeats until the program is
10011101 interrupted.
1 4.8 for x in range(6):
2
4 print('I love to program!')
8
16 4.9 0
32 1
64
128
2
3
4
5
To determine the value of a binary number, you simply add up the position values of all the
1s. For example, in the binary number 10011101, the position values of the 1s are 1, 4, 8, 4.10 2
16, and 128. This is shown in Figure 1-10. The sum of all of these position values is 157. 3
So, the value of the binary number 10011101 is 157. 4
5
3.13 if number == 1: Figure 1-11 shows how you can picture the number 157 stored in a byte of memory. Each
print('One') 1 is represented by a bit in the on position, and each 0 is represented by a bit in the off
elif number == 2: position.
print('Two')
elif number == 3:
print('Three') Figure 1-11 The bit pattern for 157
else:
print('Unknown')
Any piece of data that is stored in a computer’s memory must be stored as a binary num- 2.39 turtle.setup(500, 200)
ber. That includes characters, such as letters and punctuation marks. When a character is 2.40 turtle.goto(100, 50)
stored in memory, it is first converted to a numeric code. The numeric code is then stored
in memory as a binary number. 2.41 turtle.pos()
Over the years, different coding schemes have been developed to represent characters in 2.42 turtle.speed(10)
computer memory. Historically, the most important of these coding schemes is ASCII, 2.43 turtle.speed(0)
which stands for the American Standard Code for Information Interchange. ASCII is a set
of 128 numeric codes that represent the English letters, various punctuation marks, and 2.44 To fill a shape with a color, you use the turtle.begin_fill() command
other characters. For example, the ASCII code for the uppercase letter A is 65. When you before drawing the shape, then you use the turtle.end_fill() command
type an uppercase A on your computer keyboard, the number 65 is stored in memory (as after the shape is drawn. When the turtle.end_fill() command executes,
a binary number, of course). This is shown in Figure 1-13. the shape will be filled with the current fill color.
2.45 With the turtle.write()command
Figure 1-13 The letter A is stored in memory as the number 65
Chapter 3
1 1
A
3.1 A logical design that controls the order in which a set of statements execute
65 3.2 It is a program structure that can execute a set of statements only under
0 0 0 0 0 0
certain circumstances.
3.3 A decision structure that provides a single alternative path of execution.
If the condition that is being tested is true, the program takes the alternative
TIP : The acronym ASCII is pronounced “askee.” path.
3.4 An expression that can be evaluated as either true or false
In case you are curious, the ASCII code for uppercase B is 66, for uppercase C is 67, and so 3.5 You can determine whether one value is greater than, less than, greater than
forth. Appendix C shows all of the ASCII codes and the characters they represent. or equal to, less than or equal to, equal to, or not equal to another value.
The ASCII character set was developed in the early 1960s and was eventually adopted by 3.6 if y == 20:
almost all computer manufacturers. ASCII is limited, however, because it defines codes for x = 0
only 128 characters. To remedy this, the Unicode character set was developed in the early 3.7 if sales >= 10000:
1990s. Unicode is an extensive encoding scheme that is compatible with ASCII, but can commissionRate = 0.2
also represent characters for many of the languages in the world. Today, Unicode is quickly
becoming the standard character set used in the computer industry. 3.8 A dual alternative decision structure has two possible paths of execution;
one path is taken if a condition is true, and the other path is taken if the
condition is false.
Advanced Number Storage 3.9 if-else
Earlier, you read about numbers and how they are stored in memory. While reading that 3.10 When the condition is false
section, perhaps it occurred to you that the binary numbering system can be used to repre-
sent only integer numbers, beginning with 0. Negative numbers and real numbers (such as 3.11 z is not less than a.
3.14159) cannot be represented using the simple binary numbering technique we discussed. 3.12 Boston
Computers are able to store negative numbers and real numbers in memory, but to do so New York
they use encoding schemes along with the binary numbering system. Negative numbers are
encoded using a technique known as two’s complement, and real numbers are encoded in
floating-point notation. You don’t need to know how these encoding schemes work, only
that they are used to convert negative numbers and real numbers to binary format.
Appendix G Answers to Checkpoints 709 34 Chapter 1 Introduction to Computers and Programming
01
0
2.20 4
00
10
101
101
2.21 1
2.22 If you do not want the print function to start a new line of output when it
finishes displaying its output, you can pass the special argument end = ' '
to the function.
The music that you play on your CD player, iPod, or MP3 player is also digital. A digital
2.23 You can pass the argument sep= to the print function, specifying the song is broken into small pieces known as samples. Each sample is converted to a binary
desired character. number, which can be stored in memory. The more samples that a song is divided into, the
2.24 It is the newline escape character. more it sounds like the original music when it is played back. A CD quality song is divided
into more than 44,000 samples per second!
2.25 It is the string concatenation operator, which joins two strings together.
2.26 65.43 Checkpoint
2.27 987,654.13 1.12 What amount of memory is enough to store a letter of the alphabet or a small
number?
2.28 (1) Named constants make programs more self-explanatory, (2) widespread
changes can easily be made to the program, and (3) they help to prevent the 1.13 What do you call a tiny “switch” that can be set to either on or off?
typographical errors that are common when using magic numbers. 1.14 In what numbering system are all numeric values written as sequences of 0s and 1s?
2.35 turtle.circle(100) CONCEPT : A computer’s CPU can only understand instructions that are written in
machine language. Because people find it very difficult to write entire
2.36 turtle.pensize(8)
programs in machine language, other programming languages have been
2.37 turtle.pencolor('blue') invented.
1.4 How a Program Works 35 708 Appendix G Answers to Checkpoints
Earlier, we stated that the CPU is the most important component in a computer because it is 1.18 Machine language
the part of the computer that runs programs. Sometimes the CPU is called the “computer’s
1.19 Main memory, or RAM
brain” and is described as being “smart.” Although these are common metaphors, you
should understand that the CPU is not a brain, and it is not smart. The CPU is an electronic 1.20 The fetch-decode-execute cycle
device that is designed to do specific things. In particular, the CPU is designed to perform
1.21 It is an alternative to machine language. Instead of using binary numbers
operations such as the following:
for instructions, assembly language uses short words that are known as
Reading a piece of data from main memory mnemonics.
Adding two numbers
1.22 A high-level language
Subtracting one number from another number
Multiplying two numbers 1.23 Syntax
Dividing one number by another number
1.24 A compiler
Moving a piece of data from one memory location to another
Determining whether one value is equal to another value 1.25 An interpreter
As you can see from this list, the CPU performs simple operations on pieces of data. The 1.26 A syntax error
CPU does nothing on its own, however. It has to be told what to do, and that’s the purpose
of a program. A program is nothing more than a list of instructions that cause the CPU to
perform operations. Chapter 2
Each instruction in a program is a command that tells the CPU to perform a specific opera- 2.1 Any person, group, or organization that is asking you to write a program
tion. Here’s an example of an instruction that might appear in a program: 2.2 A single function that the program must perform in order to satisfy the
10110000 customer
To you and me, this is only a series of 0s and 1s. To a CPU, however, this is an instruction 2.3 A set of well-defined logical steps that must be taken to perform a task
to perform an operation.1 It is written in 0s and 1s because CPUs only understand instruc- 2.4 An informal language that has no syntax rules and is not meant to be
tions that are written in machine language, and machine language instructions always have compiled or executed. Instead, programmers use pseudocode to create
an underlying binary structure. models, or “mock-ups,” of programs.
A machine language instruction exists for each operation that a CPU is capable of perform- 2.5 A diagram that graphically depicts the steps that take place in a program
ing. For example, there is an instruction for adding numbers, there is an instruction for
subtracting one number from another, and so forth. The entire set of instructions that a 2.6 Ovals are terminal symbols. Parallelograms are either output or input
CPU can execute is known as the CPU’s instruction set. symbols. Rectangles are processing symbols.
2.7 print('Jimmy Smith')
The machine language instruction that was previously shown is an example of only one
instruction. It takes a lot more than one instruction, however, for the computer to do any-
thing meaningful. Because the operations that a CPU knows how to perform are so basic in
nature, a meaningful task can be accomplished only if the CPU performs many operations.
For example, if you want your computer to calculate the amount of interest that you will
APP ENDIX
earn from your savings account this year, the CPU will have to perform a large number of
G
instructions, carried out in the proper sequence. It is not unusual for a program to contain
Answers to Checkpoints thousands or even millions of machine language instructions.
Programs are usually stored on a secondary storage device such as a disk drive. When you
install a program on your computer, the program is typically copied to your computer’s disk
drive from a CD-ROM, or downloaded from a website.
Although a program can be stored on a secondary storage device such as a disk drive,
it has to be copied into main memory, or RAM, each time the CPU executes it. For
example, suppose you have a word processing program on your computer’s disk. To
execute the program, you use the mouse to double-click the program’s icon. This causes
Chapter 1
the program to be copied from the disk into main memory. Then, the computer’s CPU
1.1 A program is a set of instructions that a computer follows to perform a task. executes the copy of the program that is in main memory. This process is illustrated in
1.2 Hardware is all the physical devices, or components, of which a computer is Figure 1-15.
made.
1.3 The central processing unit (CPU), main memory, secondary storage devices, Figure 1-15 A program is copied into main memory and then executed
input devices, and output devices
The program is copied
1.4 The CPU The CPU executes
from secondary storage
the program in
to main memory.
1.5 Main memory main memory.
Main memory
1.6 Secondary storage (RAM)
1.7 Input device
1.8 Output device
1.9 The operating system Disk drive CPU
707
1.4 How a Program Works 37
10100001
Fetch the next instruction
1
in the program.
10100001
10111000 Decode the instruction
10011110 2 to determine which
00011010 operation to perform.
11011100
and so forth... CPU
Execute the instruction
3
(perform the operation).
Main memory
(RAM)
N OTE : There are many different versions of assembly language. It was mentioned
earlier that each brand of CPU has its own machine language instruction set. Each
brand of CPU typically has its own assembly language as well.
Assembly language programs cannot be executed by the CPU, however. The CPU only
understands machine language, so a special program known as an assembler is used to
translate an assembly language program to a machine language program. This process is
shown in Figure 1-17. The machine language program that is created by the assembler can
then be executed by the CPU.
2
The first assembly language was most likely that developed in the 1940s at Cambridge University
for use with a historic computer known as the EDSAC.
38 Chapter 1 Introduction to Computers and Programming
F
mov eax, Z 10100001
add eax, 2
mov Y, eax 10111000
High-Level Languages
Although assembly language makes it unnecessary to write binary machine language instruc-
The Python standard library provides classes and functions that your programs can use to tions, it is not without difficulties. Assembly language is primarily a direct substitute for
perform basic operations, as well as many advanced tasks. There are operations, however, machine language, and like machine language, it requires that you know a lot about the
that the standard library cannot perform. When you need to do something that is beyond CPU. Assembly language also requires that you write a large number of instructions for even
the scope of the standard library, you have two choices: write the code yourself, or use code the simplest program. Because assembly language is so close in nature to machine language,
that someone else has already written. it is referred to as a low-level language.
Fortunately, there are thousands of Python modules, written by independent programmers, In the 1950s, a new generation of programming languages known as high-level languages
that provide capabilities that the standard Python library does not offer. These are known began to appear. A high-level language allows you to create powerful and complex pro-
as third-party modules. A large collection of third-party modules exists at the website pypi. grams without knowing how the CPU works and without writing large numbers of low-level
python.org, which is known as the Python Package Index, or PyPI. instructions. In addition, most high-level languages use words that are easy to understand.
For example, if a programmer were using COBOL (which was one of the early high-level
The modules that are available at PyPI are organized as packages. A package is simply a coll- languages created in the 1950s), he or she would write the following instruction to display
ection of one or more related modules. The easiest way to download and install a package the message Hello world on the computer screen:
is with the pip utility. The pip utility is a program that is part of the standard Python
installation, beginning with Python 3.4. To install a package on a Windows system with DISPLAY "Hello world"
the pip utility, you must open a command prompt window, and type a command following Python is a modern, high-level programming language that we will use in this book. In
this format: Python you would display the message Hello world with the following instruction:
pip install package_name print('Hello world')
package_name is the name of a package that you want to download and install. If you are
Doing the same thing in assembly language would require several instructions and an inti-
running a Mac or a Linux system, you must use the pip3 command instead of the pip com-
mate knowledge of how the CPU interacts with the computer’s output device. As you can see
mand. In addition, you will need superuser privileges to execute the pip3 command on a
from this example, high-level languages allow programmers to concentrate on the tasks they
Mac or Linux system, so you will have to prefix the command with sudo, as shown here: want to perform with their programs, rather than the details of how the CPU will execute
sudo pip3 install package_name those programs.
Once you enter the command, the pip utility will start downloading and installing the Since the 1950s, thousands of high-level languages have been created. Table 1-1 lists several
package. Depending on the size of the package, it may take a few minutes to complete the of the more well-known languages.
installation process. Once the process is finished, you can typically verify that the package
was correctly installed by starting IDLE and entering the command
Key Words, Operators, and Syntax: An Overview
>>> import package_name
Each high-level language has its own set of predefined words that the programmer must
where package_name is the name of the package that you installed. If you do not see an use to write a program. The words that make up a high-level programming language are
error message, you can assume the package was successfully installed. known as key words or reserved words. Each key word has a specific meaning, and cannot
In Chapter 7, you will explore a popular third-party package named matplotlib. You can be used for any other purpose. Table 1-2 shows all of the Python key words.
use the matplotlib package to create charts and graphs.
705
1.4 How a Program Works 39
Using an Alias In addition to key words, programming languages have operators that perform various
operations on data. For example, all programming languages have math operators that
You can use the as keyword to assign an alias to a module when you import it. The follow- perform arithmetic. In Python, as well as most other languages, the + sign is an operator
ing statement shows an example: that adds two numbers. The following adds 12 and 75:
import math as mt 12 + 75
This statement loads the math module into memory, assigning the module the alias mt. There are numerous other operators in the Python language, many of which you will learn
To use any of the items that are in the module, you prefix the item’s name with the alias, about as you progress through this text.
followed by a dot. For example, to call the sqrt function, you would use the name
mt.sqrt. The following interactive session shows an example: In addition to key words and operators, each language also has its own syntax, which is a
set of rules that must be strictly followed when writing a program. The syntax rules dictate
>>> import math as mt how key words, operators, and various punctuation characters must be used in a program.
>>> x = mt.sqrt(25) When you are learning a programming language, you must learn the syntax rules for that
>>> a = mt.radians(180) particular language.
>>> print(x)
5.0 The individual instructions that you use to write a program in a high-level programming
>>> print(a) language are called statements. A programming statement can consist of key words, oper-
3.141592653589793 ators, punctuation, and other allowable programming elements, arranged in the proper
>>> sequence to perform an operation.
You can also assign an alias to a specific function or class when you import it. The follow-
ing statement imports the sqrt function from the math module, and assigns the function Compilers and Interpreters
the alias square_root:
Because the CPU understands only machine language instructions, programs that are writ-
from math import sqrt as square_root ten in a high-level language must be translated into machine language. Depending on the
language in which a program has been written, the programmer will use either a compiler
After using this import statement, you would use the name square_root to call the sqrt
or an interpreter to make the translation.
function. The following interactive session shows an example:
A compiler is a program that translates a high-level language program into a separate
>>> from math import sqrt as square_root
machine language program. The machine language program can then be executed any time
>>> x = square_root(25)
it is needed. This is shown in Figure 1-18. As shown in the figure, compiling and executing
>>> print(x)
are two different processes.
5.0
>>> Figure 1-18 Compiling a high-level program and executing it
In the following interactive session, we import two functions from the math module, giving
High-level language Machine language
each of them an alias. The sqrt function is imported as square_root, and the tan func- program
program
tion is imported as tangent:
The compiler is used 10100001
print ("Hello
>>> from math import sqrt as square_root, tan as tangent 1 to translate the high-level Earthling") 10111000
language program to a Compiler
>>> x = square_root(25) 10011110
machine language program. and so forth... and so forth...
>>> y = tangent(45)
>>> print(x)
5.0
>>> print(y)
1.6197751905438615
Machine language
CPU
program
The machine language 10100001
2 program can be executed 10111000
at any time, without using 10011110
the compiler. and so forth...
1.4 How a Program Works 41 702 Appendix E More About the import Statement
The Python language uses an interpreter, which is a program that both translates and This statement causes only the sqrt function to be imported from the math module. It also
executes the instructions in a high-level language program. As the interpreter reads allows you to call the sqrt function without prefixing the function’s name with the name
each individual instruction in the program, it converts it to machine language instruc- of the module. The following interactive session shows an example:
tions then immediately executes them. This process repeats for every instruction in
>>> from math import sqrt
the program. This process is illustrated in Figure 1-19. Because interpreters combine
>>> x = sqrt(25)
translation and execution, they typically do not create separate machine language
>>> print(x)
programs.
5.0
>>>
Figure 1-19 Executing a high-level program with an interpreter You can specify the names of multiple items, separated with commas, when you use this
form of the import statement. For example, the import statement in the following interac-
High-level language tive session imports only the sqrt function and the radians function from the math
program CPU module:
Machine language
print ("Hello instruction
>>> from math import sqrt, radians
Earthling") Interpreter 10100001
>>> x = sqrt(25)
and so forth... >>> a = radians(180)
>>> print(x)
5.0
The interpreter translates each high-level instruction to
>>> print(a)
its equivalent machine language instructions then 3.141592653589793
immediately executes them. >>>
This process is repeated for each high-level instruction.
Wildcard Imports
The statements that a programmer writes in a high-level language are called source A wildcard import statement loads the entire contents of a module. Here is an example:
code, or simply code. Typically, the programmer types a program’s code into a text
editor then saves the code in a file on the computer’s disk. Next, the programmer uses from math import *
a compiler to translate the code into a machine language program, or an interpreter to The difference between this statement and the import math statement is that the wildcard
translate and execute the code. If the code contains a syntax error, however, it cannot import statement does not require you to use the qualified names of the items in the mod-
be translated. A syntax error is a mistake such as a misspelled key word, a missing ule. For example, here is an interactive session that uses a wildcard import statement:
punctuation character, or the incorrect use of an operator. When this happens, the
compiler or interpreter displays an error message indicating that the program contains >>> from math import*
a syntax error. The programmer corrects the error then attempts once again to translate >>> x = sqrt(25)
the program. >>> a = radians(180)
>>>
And, here is an interactive session that uses the regular import statement:
N OTE : Human languages also have syntax rules. Do you remember when you took >>> import math
your first English class, and you learned all those rules about commas, apostrophes, >>> x = math.sqrt(25)
capitalization, and so forth? You were learning the syntax of the English language. >>> a = math.radians(180)
>>>
Although people commonly violate the syntax rules of their native language when
speaking and writing, other people usually understand what they mean. Unfortunately, Typically, you should avoid using the wildcard import statement because it can lead to
compilers and interpreters do not have this ability. If even a single syntax error appears name clashes when you are importing several modules. A name clash occurs when a
in a program, the program cannot be compiled or executed. When an interpreter program imports two modules that have functions or classes with the same name. Name
encounters a syntax error, it stops executing the program. clashes do not occur when you are using the qualified names of a module’s functions
and/or classes.
42 Chapter 1 Introduction to Computers and Programming
Checkpoint
1.18 A CPU understands instructions that are written only in what language?
1.19 A program has to be copied into what type of memory each time the CPU
executes it?
1.20 When a CPU executes the instructions in a program, it is engaged in what process?
More About the import
APP ENDIX
E
1.21 What is assembly language?
1.22 What type of programming language allows you to create powerful and complex
Statement 1.23
programs without knowing how the CPU works?
Each language has a set of rules that must be strictly followed when writing a
program. What is this set of rules called?
1.24 What do you call a program that translates a high-level language program into a
separate machine language program?
1.25 What do you call a program that both translates and executes the instructions in
A module is a Python source code file that contains functions and/or classes. Many of the a high-level language program?
functions in the Python standard library are stored in modules. For example, the math mod- 1.26 What type of mistake is usually caused by a misspelled key word, a missing
ule contains various mathematical functions, and the random module contains functions for punctuation character, or the incorrect use of an operator?
working with random numbers.
In order to use the functions and/or classes that are stored in a module, you must import the
module. To import a module, you write an import statement at the top of your program.
1.5 Using Python
Here is an import statement that imports the math module:
CONCEPT : The Python interpreter can run Python programs that are saved in files
import math
or interactively execute Python statements that are typed at the keyboard.
This statement causes the Python interpreter to load the contents of the math module into Python comes with a program named IDLE that simplifies the process of
memory, making the functions and/or classes that are stored in the math module available writing, executing, and testing programs.
to the program. To use any item that is in the module, you must use the item’s qualified
name. This means that you must prefix the item’s name with the name of the module, fol-
lowed by a dot. For example, the math module has a function named sqrt that returns the Installing Python
square root of a number. To call the sqrt function, you would use the name math.sqrt. Before you can try any of the programs shown in this book, or write any programs of your
The following interactive session shows an example: own, you need to make sure that Python is installed on your computer and properly con-
>>> import math
figured. If you are working in a computer lab, this has probably been done already. If you
>>> x = math.sqrt(25)
are using your own computer, you can follow the instructions in Appendix A to download
>>> print(x)
and install Python.
5.0
>>> The Python Interpreter
You learned earlier that Python is an interpreted language. When you install the Python
language on your computer, one of the items that is installed is the Python interpreter. The
Importing a Specific Function or Class Python interpreter is a program that can read Python programming statements and execute
The previously shown form of the import statement loads the entire contents of a module them. (Sometimes, we will refer to the Python interpreter simply as the interpreter.)
into memory. Sometimes you want to import only a specific function or class from a mod-
You can use the interpreter in two modes: interactive mode and script mode. In interac-
ule. When this is the case, you can use the from keyword with the import statement, as
tive mode, the interpreter waits for you to type Python statements on the keyboard. Once
shown here:
you type a statement, the interpreter executes it and then waits for you to type another
from math import sqrt statement. In script mode, the interpreter reads the contents of a file that contains Python
statements. Such a file is known as a Python program or a Python script. The interpreter
executes each statement in the Python program as it reads it.
701
1.5 Using Python 43
Interactive Mode
Once Python has been installed and set up on your system, you start the interpreter in
interactive mode by going to the operating system’s command line and typing the follow-
ing command:
python
If you are using Windows, you can alternatively type python in the Windows search box.
In the search results, you will see a program named something like Python 3.5. (The “3.5”
is the version of Python that is installed. At the time this is being written, Python 3.5 is
the latest version.) Clicking this item will start the Python interpreter in interactive mode.
When the Python interpreter starts in interactive mode, you will see something like the fol-
lowing displayed in a console window:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48)
[MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license"
for more information. This page intentionally left blank
>>>
The >>> that you see is a prompt that indicates the interpreter is waiting for you to type
a Python statement. Let’s try it out. One of the simplest things that you can do in Python
is print a message on the screen. For example, the following statement prints the message
Python programming is fun! on the screen:
print('Python programming is fun!')
You can think of this as a command that you are sending to the Python interpreter. If
you type the statement exactly as it is shown, the message Python programming is fun! is
printed on the screen. Here is an example of how you type this statement at the interpreter’s
prompt:
>>> print('Python programming is fun!') Enter
After typing the statement, you press the Enter key, and the Python interpreter executes the
statement, as shown here:
>>> print('Python programming is fun!') Enter
Python programming is fun!
>>>
Appendix D Predefined Named Colors 699 44 Chapter 1 Introduction to Computers and Programming
'gray3' 'gray4' 'gray5' After the message is displayed, the >>> prompt appears again, indicating the interpreter is
'gray6' 'gray7' 'gray8' waiting for you to enter another statement. Let’s look at another example. In the following
sample session, we have entered two statements:
'gray9' 'gray10' 'gray11'
>>> print('To be or not to be') Enter
'gray12' 'gray13' 'gray14'
To be or not to be
'gray15' 'gray16' 'gray17' >>> print('That is the question.') Enter
'gray18' 'gray19' 'gray20' That is the question.
>>>
'gray21' 'gray22' 'gray23'
'gray24' 'gray25' 'gray26' If you incorrectly type a statement in interactive mode, the interpreter will display an error
message. This will make interactive mode useful to you while you learn Python. As you
'gray27' 'gray28' 'gray29'
learn new parts of the Python language, you can try them out in interactive mode and get
'gray30' 'gray31' 'gray32' immediate feedback from the interpreter.
'gray33' 'gray34' 'gray35' To quit the Python interpreter in interactive mode on a Windows computer, press Ctrl-Z
'gray36' 'gray37' 'gray38' (pressing both keys together) followed by Enter. On a Mac, Linux, or UNIX computer,
press Ctrl-D.
'gray39' 'gray40' 'gray42'
'gray43' 'gray44' 'gray45'
'gray46' 'gray47' 'gray48' N O TE : In Chapter 2, we will discuss the details of statements like the ones previously
shown. If you want to try them now in interactive mode, make sure you type them exactly
'gray49' 'gray50' 'gray51'
as shown.
'gray52' 'gray53' 'gray54'
'gray55' 'gray56' 'gray57'
'gray58' 'gray59' 'gray60' Writing Python Programs and Running
'gray61' 'gray62' 'gray63' Them in Script Mode
'gray64' 'gray65' 'gray66' Although interactive mode is useful for testing code, the statements that you enter in interac-
tive mode are not saved as a program. They are simply executed and their results displayed on
'gray67' 'gray68' 'gray69'
the screen. If you want to save a set of Python statements as a program, you save those state-
'gray70' 'gray71' 'gray72' ments in a file. Then, to execute the program, you use the Python interpreter in script mode.
'gray73' 'gray74' 'gray75' For example, suppose you want to write a Python program that displays the following three
'gray76' 'gray77' 'gray78' lines of text:
'gray79' 'gray80' 'gray81' Nudge nudge
'gray82' 'gray83' 'gray84' Wink wink
Know what I mean?
'gray85' 'gray86' 'gray87'
'gray88' 'gray89' 'gray90'
To write the program you would use a simple text editor like Notepad (which is installed
on all Windows computers) to create a file containing the following statements:
'gray91' 'gray92' 'gray93'
print('Nudge nudge')
'gray94' 'gray95' 'gray97'
print('Wink wink')
'gray98' 'gray99' print('Know what I mean?')
N O TE : It is possible to use a word processor to create a Python program, but you must
be sure to save the program as a plain text file. Otherwise, the Python interpreter will
not be able to read its contents.
GLOBAL GLOBAL
EDITION EDITION
RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO
THIS INFORMATION, INCLUDING ALL WARRANTIES AND CONDITIONS OF MERCHANTABILITY,
Digital Resources for Students WHETHER EXPRESS, IMPLIED OR STATUTORY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
Your new textbook provides 12-month access to digital resources that may include WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
VideoNotes (step-by-step video tutorials on programming concepts), source code, web
WITH THE USE OR PERFORMANCE OF INFORMATION AVAILABLE FROM THE SERVICES. THE
chapters, quizzes, and more. Refer to the preface in the textbook for a detailed list of DOCUMENTS AND RELATED GRAPHICS CONTAINED HEREIN COULD INCLUDE TECHNICAL
resources. INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO
THE INFORMATION HEREIN. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS MAY MAKE
Follow the instructions below to register for the Companion Website for Tony Gaddis’ IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED
Starting Out with Python, Fourth Edition, Global Edition. HEREIN AT ANY TIME. PARTIAL SCREEN SHOTS MAY BE VIEWED IN FULL WITHIN THE SOFTWARE
VERSION SPECIFIED.
1. Go to www.pearsonglobaleditions.com/gaddis
2. Enter the title of your textbook or browse by author name.
3. Click Companion Website.
4. Click Register and follow the on-screen instructions to create a login name
and password.
ISSGPY-PRANK-CURRY-PIQUE-METIS-ROUSE
Use the login name and password you created during registration to start using the
online resources that accompany your textbook.
IMPORTANT:
This prepaid subscription does not include access to MyProgrammingLab, which is
available at www.myprogramminglab.com for purchase.
This subscription is valid for 12 months upon activation and is not transferable.
743
742 Index
P
defined, 261 Widgets
general format, 272 arrangement of, 630
how to use, 274–276 Button, 622, 630–633
®
and IPO charts, 276–277 Canvas, 622
randint and, 263–266 Checkbutton, 622, 648–650
random number generation, 262–271 defined, 622
randrange and, 269–270 Entry, 622, 633–636
returning multiple values, 282–283 Frame, 622, 629
return statement, 272–274 with frames, organizing, 627–630
for simplifying mathematical expressions, 274–276 Label, 622, 625–626, 629, 636–640
values, 261, 274 Listbox, 622
void functions and, 233 list of, 641
F OUR TH ED ITION writing, 272–283
Values
Menu, 622
Menubutton, 622
P
str data type, 69–70 as base classes, 574
str function defined, 574
defined, 326 in UML diagrams, 582–583
®
example use, 323 writing, 575
String comparisons, 144–147, 444–445, 463, 464 Supersets, 492
String concatenation SUV class, 580–581
defined, 90, 434 Symbols, flowchart, 56
example, 90 symmetric_difference method, 491
interactive sessions, 434 Symmetric difference of sets, 491
newline to, 319–320 Syntax
with + operator, 90 defined, 40
with += operator, 435 human language, 41
F OUR TH ED ITION String literals
defined, 59
Syntax errors
correcting, 54
GLOBA L EDITION enclosing in triple quotes, 60
Strings
defined, 41
reporting, 691
characters, accessing, 430–434 running programs and, 691
comparing, 144–148 System software, 28–29
defined, 59
extracting characters from, 438–440 T
as immutable, 435–436 tan() function, 285
Tony Gaddis
indexes, 432–433 Target variables
iterating with for loop, 430–432 defined, 192
list of, 366 inside for loops, 194–196
Haywood Community College method call format, 442 use example, 195
modification methods, 444–445 Terminal symbols, 56
operations, 429–436 Testing
raw, 314 dictionary values, 463–464
reading as input, 429 programs, 54–55
repetition operator (*) with, 450–451 set values, 488–489
returning, 280 string methods, 442–443
search and replace methods, 445–446 strings, 441
slicing, 437–438 Text
space character at end, 73 drawing with Canvas widget, 667–672
splitting, 451–452 displaying with Label widget, 624–627
storing with str data type, 69–70 editing, 687–688
stripping newline from, 320–322 font setting, 670–672
testing, 441 Text files
testing methods, 442–443 defined, 311
writing as output, 429 reading numbers from, 324
written to files, 316 Text widget, 622
StringVar object, 636–637 third-party modules, 705
strip() method, 444 Tkinter module
Stripping newline from string, 320–322 defined, 621
Structure charts. See Hierarchy charts programs using, 622
Subclasses widgets, 622
defined, 574 Top-down design
as derived classes, 574 defined, 240
method override, 588 process, 240–241
�)è“ÜÊÃ�ZãØ——ã �B—ô�xÊع �Bx�
Index 739
Running programs, 690–691 set method, 640, 647 Senior Vice President Courseware Portfolio Management: Marcia J. Horton
Running totals Sets Director, Portfolio Management: Engineering,
calculating, 201–204 adding elements, 486–487 Computer Science & Global Editions: Julian Partridge
defined, 201 creating, 485
Portfolio Manager: Matt Goldstein
elements for calculating, 201 defined, 484
example, 202 difference of, 490–491
Acquisitions Editor, Global Edition: Sourabh Maheshwari
logic for calculating, 201 duplicate elements, 485 Portfolio Management Assistant: Kristy Alaura
elements, as unique, 484 Field Marketing Manager: Demetrius Hall
S elements, number of, 486 Product Marketing Manager: Yvonne Vannatta
Samples, 34 elements, removing, 487–488 Managing Producer, ECS and Math: Scott Disanno
Saving programs, 690 intersection of, 490 Content Producer: Sandra L. Rodriguez
SavingsAccount class, 584, 585 for loop iteration over, 488
Project Editors, Global Edition: Tanima Ghosh and Neelakantan K.K.
Scale widget, 622 operations, 493–495
Scientific notation, 92 subsets, 492
Senior Manufacturing Controller, Global Edition: Jerry Kataria
Scope supersets, 492 Manager, Media Production, Global Edition: Vikram Kumar
defined, 245 symmetric difference of, 491 Cover Designer: Lumina Datamatics
local variables and, 245–247 union of, 489 Cover Photo: Africa Studio/Shutterstock
parameter variable, 249 unordered, 484
Credits and acknowledgments borrowed from other sources and reproduced, with permission, appear
Script mode, running programs in, 45 values, testing, 488–489
Scrollbar widget, 622 Settings. See Mutator methods
on the Credits page in the endmatter of this textbook.
Searching Showinfo function, 630 Pearson Education Limited
lists, 376–377 sin() function, 285
KAO Two
records, 339–341 Single alternative decision structures, 132
strings, 445–446 Slices KAO Park
Secondary storage defined, 373 Harlow
defined, 27 example use, 373–375 CM17 9NA
devices, 27–28 general format, 373 United Kingdom
Seeds, random number, 270–271 invalid indexes and, 375
Seed value, 270 list, 373–376 and Associated Companies throughout the world
Selection structures. See Decision structures start and end index, 374
Visit us on the World Wide Web at: www.pearsonglobaleditions.com
Sentinels string, 437–438
defined, 204, 205 Software © Pearson Education Limited 2019
using, 205–206 application, 29
values, 204–205 defined, 23 The rights of Tony Gaddis to be identified as the author of this work has been asserted by him in accor-
Separators developers. See Programmers dance with the Copyright, Designs and Patents Act 1988.
comma, 92–93 development tools, 29
item, 88–89 operating system, 28 Authorized adaptation from the United States edition, entitled Starting Out with Python, 4th Edition,
split method, 451–452 requirements, 55 ISBN 978-0-13-444432-1 by Tony Gaddis, published by Pearson Education © 2018.
Sequences. See also Lists system, 28–29
accepting as argument, 383–384 types of, 28 All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted
defined, 365 utility programs, 28 in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without either
length, returning, 369 Sorting, item list, 381–382 the prior written permission of the publisher or a license permitting restricted copying in the United Kingdom
tuples, 402–404 sort method, 378, 381–382
issued by the Copyright Licensing Agency Ltd, Sa ron House, 6–10 Kirby Street, London EC1N 8TS.
Sequence structures Source code. See Code
with decision structure, 147 Specialization, 573–574 All trademarks used herein are the property of their respective owners. The use of any trademark in this
defined, 131 split method, 451 text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor
example, 131 Splitting strings, 451–452
does the use of such trademarks imply any a liation with or endorsement of this book by such owners.
nested inside decision structure, 148 sqrt() function, 285
structure, 147, 148 startswith method, 445, 446
British Library Cataloguing-in-Publication Data
use in programming, 131–132 Statements
Serializing objects for, 190, 194, 196 A catalogue record for this book is available from the British Library
defined, 496 assignment, 62–65
10 9 8 7 6 5 4 3 2 1
example, 498–500, 542–544 in blocks, 133, 235
pickle module, 496–497 breaking into multiple lines, 86–87 ISBN 10: 1-292-22575-0
unserializing, 500–502, 543–544 converting math formulas to, 83–85 ISBN 13: 978-1-292-22575-3
ServiceQuote class, 563–565 defined, 40
set function, 485 del, 383 Typeset by iEnergizer Aptara®, Ltd.
Printed and bound in Malaysia
738 Index
7
Index 735 8 Contents
Chapter 8 More About Strings 429 not operator, 155, 157 multiplication (*), 76, 79, 367
8.1 Basic String Operations 429 Nouns, list refining, 557–560 not in. See Not in operator
8.2 String Slicing 437 Numbers or, 155–157, 159, 160
advanced storage, 34 precedence, 79
8.3 Testing, Searching, and Manipulating Strings 441
binary, 31–32 relational, 133–134, 145–146
Review Questions 453 factorial of, 603–605 remainder (%), 76, 79, 82–83
Programming Exercises 456 Fibonacci, 607–609 repetition (*), 367, 450–451
floating-point, 33, 94 subtraction (−), 76, 79
Chapter 9 Dictionaries and Sets 461 formatting, 90–91 Optical devices, 28
9.1 Dictionaries 461 pseudorandom, 270–271 or operator, 155–157, 159, 160
9.2 Sets 484 random, 262–271 Output
9.3 Serializing Objects 496 running totals, 201–204 in computer program process, 57–58
storage, 31–33 data, 87–95
Review Questions 502
Numeric literals, 69 defined, 28
Programming Exercises 507 Numeric ranges, with logical operators, 160 displaying, 58–61
Output devices, 28
Chapter 10 Classes and Object-Oriented Programming 511 Output files, 310, 311, 315, 322, 326
10.1 Procedural and Object-Oriented Programming 511 O
Overhead, 602
Object-oriented programming (OOP)
10.2 Classes 515 class design, 554–565
Overriding, method, 588
10.3 Working with Instances 532 classes, 515–532
10.4 Techniques for Designing Classes 554 data hiding, 512
P
pack method, 625–627, 629, 634
Review Questions 565 defined, 512
Parameter lists, 252
Programming Exercises 568 encapsulation, 512
Parentheses, grouping with, 80
instances, 515, 532–554
Pascal, 39
Chapter 11 Inheritance 573 Objects, 629. See also Classes
Passing arguments. See also Arguments
11.1 Introduction to Inheritance 573 characteristics description, 515
to function, 248–251
11.2 Polymorphism 588 defined, 512
function parameter variable, 253–255
dictionary, 461–484
Review Questions 594 to index method, 379–381
everyday example of, 513–514
Programming Exercises 596 list as function, 389–390
exception, 359 multiple, 251–253
file, 316–317 and objects, 540–541
Chapter 12 Recursion 599 list, 365, 366 by position, 252
12.1 Introduction to Recursion 599 “is a” relationship, 574 by value, 255
12.2 Problem Solving with Recursion 602 passing as arguments, 540–541 Passwords, validating characters in, 446–449
12.3 Examples of Recursive Algorithms 606 pickling, 542–544 Pattern printing using nested loops, 215–218
Review Questions 614 reusability, 513 Percentages, calculations, 77–78
Programming Exercises 616 sequence, 365 Pickle module, 497–498, 542, 547
serializing, 496–502 Pickling, 496–498, 500, 542–544
Chapter 13 GUI Programming 619 set, 484–496 pi variable, 285
storing in dictionaries, 544–554 pie chart, plotting, 418–420
13.1 Graphical User Interfaces 619
storing in lists, 538–540 pip utility, 705
13.2 Using the tkinter Module 621 StringVar, 636–637 Pixels, 34
13.3 Display Text with Label Widgets 624 unpickling, 543–544 plot() function, 406–407
13.4 Organizing Widgets with Frames 627 open function, 313, 314, 318 Polymorphism
13.5 Button Widgets and Info Dialog Boxes 630 Operands, 76 behavior, ingredients of, 588
13.6 Getting Input with the Entry Widget 633 Operating systems, 28 defined, 588
Operators isinstance function, 591–594
13.7 Using Labels as Output Fields 636
and, 156–158 popitem method, 473, 477
13.8 Radio Buttons and Check Buttons 644 in. See In operator pop method, 472, 720
13.9 Drawing Shapes with the Canvas Widget 651 addition (+), 76, 79, 90 Positional arguments, 257
Review Questions 673 assignment, 135, 203–204 Precedence, operator, 79
Programming Exercises 676 augmented assignment, 203–204 Predefined names colors, 695–699
exponent (**), 76, 80–82 Pretest loops
logical. See Logical operators defined, 186
math, 75–76 while loops as, 186–187
Index 733 10 Contents
Error handlers, 209 defined, 607–608 The new Turtle Graphics sections are designed with flexibility in mind. They can be
Error messages, 41, 44 recursive function calculation, 608–609 assigned as optional material, incorporated into your existing syllabus, or skipped
default, displaying, 355–356 Field widths
altogether.
loop displaying, 208–209 columns, 93
traceback, 349, 351 minimum, specifying, 93–94 ● Chapter 2 has a new section on named constants. Although Python does not support
Errors. See Exceptions File modes, 317 true constants, you can create variable names that symbolize values that should not
Error traps, 209 Filename extensions, 312
change as the program executes. This section teaches the student to avoid the use
Escape characters, 89–90 File objects
Event handlers, callback functions as, 630 close method, 315, 497 of “magic numbers,” and to create symbolic names that make his or her code more
Exception handling defined, 312 self-documenting and easier to maintain.
defined, 352 read method, 316–319 ● Chapter 7 has a new section on using the matplotlib package to plot charts and graphs
multiple exceptions, 352–355 variable name referencing, 312–314 from lists. The new section describes how to install the matplotlib package, and use it to
with try/except statement, 357–358 writelines method, 395–398
plot line graphs, bar charts, and pie charts.
Exception objects, 359 write method, 314
Exceptions finally clause, with try/except statement, 358
● Chapter 13 has a new section on creating graphics in a GUI application with the
catching all, with one except clause, 354–355 Finally suite, 358 Canvas widget. The new section describes how to use the Canvas widget to draw lines,
code response to, 348 find method, 446 rectangles, ovals, arcs, polygons, and text.
default error message display, 355–356 Flags, 162 ● Several new, more challenging, programming problems have been added throughout
defined, 75, 346 Flash drives, 28 the book.
IndexError, 368–369, 433 Flash memory, 28
IOError, 351–352, 354, 358 float data type, 69, 85–86
● Appendix E is a new appendix that discusses the various forms of the import statement.
KeyError, 463, 465, 487 float() function, 73, 74, 75, 86
● Appendix F is a new appendix that discusses installing third-party modules with the
multiple, 352–354 Floating-point division, 78, 79 pip utility.
unhandled, 358–359 Floating-point notation, 33
ValueError, 349–350, 354, 355, Floating-point numbers, 94
356, 358, 382 floor() function, 285 Brief Overview of Each Chapter
ZeroDivisionError, 358 Floppy disk drives, 27
Execution, 223 Flowchart, 56
in fetch-decode-execute cycle, 36 clock simulator, 213
Chapter 1: Introduction to Computers and Programming
pausing, 244 decision structure, 132, 133, 137 This chapter begins by giving a very concrete and easy-to-understand explanation of how
Python interpreter, 686–687 dual alternative decision structure, 130
computers work, how data is stored and manipulated, and why we write programs in high-
try/except statement, 349 input validation loop, 208
while loop, 209 logic for file end detection, 328 level languages. An introduction to Python, interactive mode, script mode, and the IDLE
Exercises nested decision structure, 149, 152 environment are also given.
decision structures, 173–179 pay calculating program, 57
dictionaries and sets, 507–510 program development cycle, 53
files and exceptions, 366–368 running total calculation, 201 Chapter 2: Input, Processing, and Output
functions, 302–308 sequence structure nested inside decision
This chapter introduces the program development cycle, variables, data types, and simple
GUI programming, 676–679 structure, 148
inheritance, 596–597 sequence structures with decision structure, 147–148 programs that are written as sequence structures. The student learns to write simple pro-
input, processing, and output, 126–130 while loop, 183 grams that read input from the keyboard, perform mathematical operations, and produce
introduction, 50–51 Font class, 670–672 screen output. Pseudocode and flowcharts are also introduced as tools for designing pro-
lists and tuples, 424–428 keyword arguments for, 671 grams. The chapter also includes an optional introduction to the turtle graphics library.
programming, 568–572 for loops. See also Loops
recursion, 616–617 as count-controlled loops, 190–200
repetition structures, 265–267 defined, 190–191 Chapter 3: Decision Structures and Boolean Logic
strings, 456–460 in turtle graphics, 219
exp() function, 285 iterating lists with, 368 In this chapter, the student learns about relational operators and Boolean expressions and is
Exponent (**) operator, 76, 80–82 iterating over dictionaries with, 468–469 shown how to control the flow of a program with decision structures. The if, if-else, and
iterating over list of strings with, 192 if-elif-else statements are covered. Nested decision structures and logical operators are
F iterating over sets, 488
discussed as well. The chapter also includes an optional turtle graphics section, with a discus-
Factorial function, 604–605 iterations, 198–200
Factorials iterations, user control, 198–200 sion of how to use decision structures to test the state of the turtle.
calculation with recursion, 602–606 range function with, 190–194
definition rules, 606, 609 target variables, 194–198
Fetch-decode-execute cycle, 36–37 format function, 91, 94
Chapter 4: Repetition Structures
Fibonacci series Format specifiers, 91–94 This chapter shows the student how to create repetition structures using the while loop and
for loop. Counters, accumulators, running totals, and sentinels are discussed, as well as
Preface 15 728 Index
techniques for writing input validation loops. The chapter also includes an optional section create_polygon method, 665–667 defined, 461
on using loops to draw designs with the turtle graphics library. optional arguments to, 667 elements, adding, 464
create_rectangle method, 655–657 elements, deleting, 465, 469
optional arguments to, 657 elements, display order, 462
Chapter 5: Functions create_text method, 667–672 elements, number of, 465–466
optional arguments to, 669 empty, creating, 467–468
In this chapter, the student first learns how to write and call void functions. The chapter C# programming language, 39 example, 474–477, 477–483
shows the benefits of using functions to modularize programs and discusses the top-down Customer class, 561–562 iteration, 468–469
design approach. Then, the student learns to pass arguments to functions. Common library keys, 461, 462
functions, such as those for generating random numbers, are discussed. After learning how D key-value pairs, 461, 464
Data methods, 469–474
to call library functions and use their return value, the student learns to define and call his mixing data types in, 466–467
appending to files, 322
or her own functions. Then the student learns how to use modules to organize functions. An binary file, 311 parts of, 461
optional section includes a discussion of modularizing turtle graphics code with functions. digital, 34 retrieving value from, 462–463
hiding, 512 storing objects in, 544–554
output, 87–95 values, 463–464
Chapter 6: Files and Exceptions processing, 333–346 Dictionary views
reading from files, 310–311, 316–319 defined, 470
This chapter introduces sequential file input and output. The student learns to read and write
text file, 311 elements, 470
large sets of data and store data as fields and records. The chapter concludes by discussing keys returned as, 471
writing to files, 310, 314–316
exceptions and shows the student how to write exception-handling code. Data attributes, 512 values returned as, 473–474
hidden, 513 dict() method, 468
hiding, 522–525 difference method, 490–491
Chapter 7: Lists and Tuples Digital data, 34
initializing, 518
This chapter introduces the student to the concept of a sequence in Python and explores the instance, 532–554 Digital devices, 34
Data storage, 29–33 Direct access files, 312, 343, 346
use of two common Python sequences: lists and tuples. The student learns to use lists for
characters, 33 Direct recursion, 606
arraylike operations, such as storing objects in a list, iterating over a list, searching for items music, 34 discard method, 487
in a list, and calculating the sum and average of items in a list. The chapter discusses slic- Data types Disk drives
ing and many of the list methods. One- and two-dimensional lists are covered. The chapter bool, 161 defined, 27
also includes a discussion of the matplotlib package, and how to use it to plot charts and conversion and mixed-type expressions, 85–86 program storage on, 36
graphs from lists. and literals, 68–69 Divide and conquer approach, 232
mixing, 466–467 Division
str, 69–70 floating-point, 78
Chapter 8: More About Strings Debugging, 54, 154 integer, 76, 78
global variables and, 258–259 / operator, 76, 78, 79
In this chapter, the student learns to process strings at a detailed level. String slicing and Decision structures, 132 Dog class, 589–590
algorithms that step through the individual characters in a string are discussed, and several actions performed in, 132–133 Dot notation, 263, 285
built-in functions and string methods for character and text processing are introduced. combining sequence structures with, 147–148 Dual alternative decision structure,
dual alternative, 140 139–140
in flowcharts, 132 dump method, 497
Chapter 9: Dictionaries and Sets if-elif-else statement, 153–154 DVD drives, 28
if-else statement, 140–143 DVDs (digital versatile discs), 28
This chapter introduces the dictionary and set data structures. The student learns to store data if statement, 131–139
as key-value pairs in dictionaries, search for values, change existing values, add new key-value inside, 148 E
pairs, and delete key-value pairs. The student learns to store values as unique elements in sets nested, 147–155 else clause, 143, 150
and perform common set operations such as union, intersection, di erence, and symmetric single alternative, 132 execution, 140
degrees() function, 285 with try/except statement, 357–358
di erence. The chapter concludes with a discussion of object serialization and introduces the
del statement, 383 else suite, 357
student to the Python pickle module. Depth of recursion, 602 Encapsulation, 512
Derived classes, 574 end–of–file, 500–501, 543
Chapter 10: Classes and Object-Oriented Programming Dialog boxes endswith method, 445, 446
defined, 619 ENIAC computer, 25, 26
This chapter compares procedural and object-oriented programming practices. It covers the illustrated, 620–621 Entry widget
fundamental concepts of classes and objects. Attributes, methods, encapsulation and data info, 630–633 defined, 622, 633
Dictionaries getting input with, 633–636
hiding, _ _init_ _ functions (which are similar to constructors), accessors, and mutators are
creating, 462 use example, 634–636
discussed. The student learns how to model classes with UML and how to find the classes
in a particular problem.
Index 727 16 Preface
VideoNotes Online videos developed specifically for this book are available
for viewing at www.pearsonglobaleditions.com/gaddis. Icons appear
throughout the text alerting the student to videos about specific
topics.
Notes Notes appear at several places throughout the text. They are
short explanations of interesting or often misunderstood points
relevant to the topic at hand.
Index Tips Tips advise the student on the best techniques for approaching
di erent programming problems.
Warnings Warnings caution students about programming techniques or
practices that can lead to malfunctioning programs or lost data.
Checkpoints Checkpoints are questions placed at intervals throughout each
chapter. They are designed to query the student’s knowledge
Symbols defined, 134 quickly after learning a new topic.
!= operator in string comparisons, 144
defined, 136 use example, 138 Review Questions Each chapter presents a thorough and diverse set of review
example use, 136, 138 > operator questions and exercises. They include Multiple Choice, True/
" (double-quote marks), 60 defined, 134 False, Algorithm Workbench, and Short Answer.
""" or "' (triple quotes), 60 in string comparisons, 146
# character, 61 use example, 134, 135–136 Programming Each chapter o ers a pool of programming exercises designed
% (remainder) operator >= operator Exercises to solidify the student’s knowledge of the topics currently being
defined, 76, 82 defined, 134 studied.
function of, 281 in superset determination, 492
%= operator, 203 relationship testing, 135
& operator, for intersection of sets, 490 >>> prompt, 43, 44
Supplements
' (single-quote marks), 59–60 ^ operator, 491
* operator _ _init_ _ method, 521, 555, 561, 563, 583 Student Online Resources
multiplication, 76 {}(curly braces), 462
Many student resources are available for this book from the publisher. The following items
repetition, 367
are available at www.pearsonglobaleditions.com/gaddis
** (exponent) operator, 76, 80–82 A
*= operator, 203 Accessor methods, 537 ● The source code for each example program in the book
+ operator acos(x) function, 285 ● Access to the book’s companion VideoNotes
defined, 76 Actions
displaying multiple items with, 90 conditionally executed, 132
in list concatenation, 371 in decision structures, 133 Instructor Resources
+= operator Ada programming language, 39
defined, 203
The following supplements are available to qualified instructors only:
Addition (+) operator
in list concatenation, 372 defined, 76 ● Answers to all of the Review Questions
in string concatenation, 435 displaying multiple items with, 90 ● Solutions for the exercises
− (subtraction) operator, 76 precedence, 79
_ _str_ _ method, 529–532 add method, 486
● PowerPoint presentation slides for each chapter
−= operator, 203 Algebraic expressions, 83–84 ● Test bank
/ (division) operator, 76, 78 Algorithms
// (integer division) operator, 76, 78 defined, 55 Visit the Pearson Instructor Resource Center (www.pearsonglobaleditions.com/gaddis) or
/= operator, 203 example, 55 contact your local Pearson campus representative for information on how to access them.
= operator recursive, 602, 603, 606–613
defined, 134 and operator
in subset determination, 492 defined, 156
relationship testing, 135 false, 158
= (assignment) operator, 135 short-circuit evaluation, 157
== operator truth table, 156
assignment operator versus, 136 Appending data, 322
725
Preface 19 724 Appendix G Answers to Checkpoints
I would like to thank the following faculty reviewers for their insight, expertise, and thought- 13.16 You would use check buttons.
ful recommendations: 13.17 When you create a group of Radiobuttons, you associate them all with
Sonya Dennis Anita Sutton the same IntVar object. You also assign a unique integer value to each
Morehouse College Germanna Community College Radiobutton widget. When one of the Radiobutton widgets is selected,
it stores its unique integer value in the IntVar object.
Diane Innes Christopher Urban
Sandhills Community College SUNY Institute of Technology 13.18 You associate a different IntVar object with each Checkbutton. When a
Checkbutton is selected, its associated IntVar object will hold the value 1.
John Kinuthia Nanette Veilleux When a Checkbutton is deselected, its associated IntVar object will hold the
Nazareth College of Rochester Simmons College value 0.
Frank Liu Brent Wilson 13.19 (0, 0)
Sam Houston State University George Fox University
13.20 (139, 479)
Haris Ribic
SUNY at Binghamton 13.21 With the Canvas widget, the point (0, 0) is in the upper-left corner of the
window. In turtle graphics, the point (0, 0) is in the center of the window.
Reviewers of Previous Editions Also, with the Canvas widget, the Y coordinates increase as you move down
Paul Amer Shyamal Mitra the screen. In turtle graphics, the Y coordinates decrease as you move down
University of Delaware University of Texas at Austin the screen.
Chapter 12 I would also like to thank my family and friends for their support in all of my projects.
I am extremely fortunate to have Matt Goldstein as my editor, and Kristy Alaura as edito-
12.1 A recursive algorithm requires multiple method calls. Each method call rial assistant. Their guidance and encouragement make it a pleasure to write chapters and
requires several actions to be performed by the JVM. These actions include meet deadlines. I am also fortunate to have Demetrius Hall as my marketing manager. His
allocating memory for parameters and local variables and storing the address hard work is truly inspiring, and he does a great job of getting this book out to the academic
of the program location where control returns after the method terminates. community. The production team, led by Sandra Rodriguez, worked tirelessly to make this
All these actions are known as overhead. In an iterative algorithm, which book a reality. Thanks to you all!
uses a loop, such overhead is unnecessary.
12.2 A case in which the problem can be solved without recursion Acknowledgments for the Global Edition
12.3 Cases in which the problem is solved using recursion Pearson would like to thank and acknowledge the following for their contributions to the
12.4 When it reaches the base case Global Edition.
12.5 In direct recursion, a recursive method calls itself. In indirect recursion, Contributor
method A calls method B, which in turn calls method A. Gregory Baatard, Edith Cowan University
Kenneth Eustace, Charles Sturt University
Chapter 13 Reviewers
Lindsay Ward, James Cook University
13.1 The part of a computer and its operating system with which the user
Ajay Mittal, University Institute of Engineering and Technology
interacts
Khyat Sharma
13.2 A command line interface typically displays a prompt, and the user types a
command, which is then executed. About the Author
13.3 The program Tony Gaddis is the principal author of the Starting Out with series of textbooks. Tony has
13.4 A program that responds to events that take place, such as the user clicking a nearly two decades of experience teaching computer science courses at Haywood Com-
button munity College. He is a highly acclaimed instructor who was previously selected as the
North Carolina Community College “Teacher of the Year” and has received the Teaching
13.5 a) Label—An area that displays one line of text or an image Excellence award from the National Institute for Sta and Organizational Development.
b) Entry—An area in which the user may type a single line of input from the The Starting Out with series includes introductory books covering C++, Java™, Microsoft®
keyboard Visual Basic®, Microsoft® C#®, Python®, Programming Logic and Design, Alice, and App
c) Button—A button that can cause an action to occur when it is clicked Inventor, all published by Pearson.
d) Frame—A container that can hold other widgets
13.6 You create an instance of the tkinter module’s Tk class.
13.7 This function runs like an infinite loop until you close the main window.
13.8 The pack method arranges a widget in its proper position, and it makes the
widget visible when the main window is displayed.
13.9 One will be stacked on top of the other.
13.10 side=–left—
13.11 You use an Entry widget’s get method to retrieve the data that the user has
typed into the widget.
13.12 It is a string.
13.13 tkinter
13.14 Any value that is stored in the StringVar object will automatically be
displayed in the Label widget.
722 Appendix G Answers to Checkpoints
Chapter 11
11.1 A superclass is a general class, and a subclass is a specialized class.
11.2 When one object is a specialized version of another object, there is an “is a”
relationship between them. The specialized object “is a” version of the
general object.
11.3 It inherits all the superclass’s attributes.
11.4 Bird is the superclass, and Canary is the subclass.
9.25 If the specified element to delete is not in the set, the remove method raises a
KeyError exception, but the discard method does not raise an exception.
9.26 You can use the in operator to test for the element.
9.27 {10, 20, 30, 100, 200, 300}
9.28 {3, 4}
9.29 {1, 2}
9.30 {5, 6}
9.33 The process of converting the object to a stream of bytes that can be saved to
a file for later retrieval.
9.34 'wb'
9.35 'rb'
9.38 pickle.load
Chapter 9
9.1 Key and value
9.2 The key
9.3 The string 'start' is the key, and the integer 1472 is the value.
Introduction to Computers
CHAPTE R
1
9.4 It stores the key-value pair 'id' : 54321 in the employee dictionary.
Computers can perform such a wide variety of tasks because they can be programmed. This 9.18 The set will contain one element: 25.
means that computers are not designed to do just one job, but to do any job that their pro-
9.19 The set will contain these elements (in no particular order): 'w', ' ', 'x',
grams tell them to do. A program is a set of instructions that a computer follows to perform
'y', and 'z'.
a task. For example, Figure 1-1 shows screens using Microsoft Word and PowerPoint, two
commonly used programs. 9.20 The set will contain these elements (in no particular order): 1, 2, 3, and 4.
Programs are commonly referred to as software. Software is essential to a computer because 9.21 The set will contain these elements (in no particular order): 'www', 'xxx',
it controls everything the computer does. All of the software that we use to make our com- 'yyy', and 'zzz'.
puters useful is created by individuals working as programmers or software developers. A
9.22 You pass the set as an argument to the len function.
programmer, or software developer, is a person with the training and skills necessary to
design, create, and test computer programs. Computer programming is an exciting and 9.23 The set will contain these elements (in no particular order): 10, 9, 8, 1, 2,
rewarding career. Today, you will find programmers’ work used in business, medicine, gov- and 3.
ernment, law enforcement, agriculture, academics, entertainment, and many other fields. 9.24 The set will contain these elements (in no particular order): 10, 9, 8, 'a',
This book introduces you to the fundamental concepts of computer programming using the 'b', and 'c'.
Python language. The Python language is a good choice for beginners because it is easy to learn
23
Appendix G Answers to Checkpoints 719 24 Chapter 1 Introduction to Computers and Programming
Then, each element in the list will become a slice in the pie chart. The size of Figure 1-1 A word processing program and an image editing program
a slice represents that element’s value as a percentage of the whole.
Chapter 8
8.1 for letter in name:
print(letter)
8.2 0
8.3 9
8.4 An IndexError exception will occur if you try to use an index that is out of
range for a particular string.
8.5 Use the built-in len function.
8.6 The second statement attempts to assign a value to an individual character
in the string. Strings are immutable, however, so the expression animal[0]
cannot appear on the left side of an assignment operator.
8.7 cde and programs can be written quickly using it. Python is also a powerful language, popular with
professional software developers. In fact, it has been reported that Python is used by Google,
8.8 defg NASA, YouTube, various game companies, the New York Stock Exchange, and many others.
8.9 abc Before we begin exploring the concepts of programming, you need to understand a few
8.10 abcdefg basic things about computers and how they work. This chapter will build a solid founda-
tion of knowledge that you will continually rely on as you study computer science. First,
8.11 if 'd' in mystring: we will discuss the physical components of which computers are commonly made. Next, we
print('Yes, it is there.')
will look at how computers store data and execute programs. Finally, you will get a quick
8.12 little = big.upper() introduction to the software that you will use to write Python programs.
8.13 if ch.isdigit():
print('Digit')
else: 1.2 Hardware and Software
print('No digit')
8.14 a A CONCEPT : The physical devices of which a computer is made are referred to as the
computer’s hardware. The programs that run on a computer are referred
8.15 again = input('Do you want to repeat ' + to as software.
'the program or quit? (R/Q) ')
while again.upper() != 'R' and again.upper() != 'Q': Hardware
again = input('Do you want to repeat the ' +
'program or quit? (R/Q) ') The term hardware refers to all of the physical devices, or components, of which a computer
is made. A computer is not one single device, but a system of devices that all work toge-
8.16 $ ther. Like the different instruments in a symphony orchestra, each device in a computer
8.17 for letter in mystring: plays its own part.
if letter.isupper(): If you have ever shopped for a computer, you’ve probably seen sales literature listing compo-
count += 1
nents such as microprocessors, memory, disk drives, video displays, graphics cards, and so on.
8.18 my_list = days.split() Unless you already know a lot about computers, or at least have a friend that does, under-
standing what these different components do might be challenging. As shown in Figure 1-2, a
8.19 my_list = values.split('$')
typical computer system consists of the following major components:
The central processing unit (CPU)
Main memory
1.2 Hardware and Software 25 718 Appendix G Answers to Checkpoints
Figure 1-2 Typical components of a computer system 7.17 You would use statement b, names.append('Wendy'). This is because
element 0 does not exist. If you try to use statement a, an error will occur.
7.18 a) The index method searches for an item in the list and returns the index of
the first element containing that item.
b) The insert method inserts an item into the list at a specified index.
Shutterstock
Central Processing c) The sort method sorts the items in the list to appear in ascending order.
Shutterstock
Unit
d) The reverse method reverses the order of the items in the list.
iko/Shutterstock
7.19 The list contains 4 rows and 2 columns.
Shutterstock
Feng Yu/Shutterstock
Output
Aquila/ Devices 7.20 mylist = [[0, 0, 0, 0], [0, 0, 0, 0],
[0, 0, 0, 0], [0, 0, 0, 0]]
Chiyacat/
Shutterstock 7.21 for r in range(4):
Peter Guess/
Shutterstock
for c in range(2):
Input
Devices
print(numbers[r][c])
jocic/Shutterstock
7.22 The primary difference between tuples and lists is that tuples are immutable.
Eikostas/Shutterstock
That means that once a tuple is created, it cannot be changed.
Main Memory
(RAM) 7.23 Here are three reasons:
Lusoimages/Shutterstock
Processing a tuple is faster than processing a list, so tuples are good
tkemot/Shutterstock Secondary
Storage Devices choices when you are processing lots of data and that data will not be
modified.
Tuples are safe. Because you are not allowed to change the contents of a
tuple, you can store data in one and rest assured that it will not be modified
(accidentally or otherwise) by any code in your program.
There are certain operations in Python that require the use of a tuple.
Vitaly Korovin/Shutterstock Andre Nitsievsky/Shutterstock.
7.24 my_tuple = tuple(my_list)
Secondary storage devices 7.25 my_list = list(my_tuple)
Input devices
Output devices 7.26 Two lists: one holding the X coordinates of the data points, and the other
holding the Y coordinates.
Let’s take a closer look at each of these components.
7.27 A line graph
The CPU 7.28 Use the xlabel and ylabel functions.
When a computer is performing the tasks that a program tells it to do, we say that the 7.29 Call the xlim and ylim functions, passing values for the xmin, xmax, ymin,
computer is running or executing the program. The central processing unit, or CPU, is the and ymax keyword arguments.
part of a computer that actually runs programs. The CPU is the most important component
7.30 Call the xticks and yticks functions. You pass two arguments to these
in a computer because without it, the computer could not run software.
functions. The first argument is a list of tick-mark locations, and the second
In the earliest computers, CPUs were huge devices made of electrical and mechanical com- argument is a list of labels to display at the specified locations.
ponents such as vacuum tubes and switches. Figure 1-3 shows such a device. The two
7.31 Two lists: one containing the X coordinates of each bar’s left edge, and
women in the photo are working with the historic ENIAC computer. The ENIAC, which
another containing the heights of each bar, along the Y axis.
is considered by many to be the world’s first programmable electronic computer, was built
in 1945 to calculate artillery ballistic tables for the U.S. Army. This machine, which was 7.32 The bars will be red, blue, red, and blue.
primarily one big CPU, was 8 feet tall, 100 feet long, and weighed 30 tons. 7.33 You pass a list of values as an argument. The pie function will calculate
Today, CPUs are small chips known as microprocessors. Figure 1-4 shows a photo of a lab the sum of the values in the list, then use that sum as the value of the whole.
technician holding a modern microprocessor. In addition to being much smaller than the old
electromechanical CPUs in early computers, microprocessors are also much more powerful.
Appendix G Answers to Checkpoints 717 26 Chapter 1 Introduction to Computers and Programming
6.18 You copy all the original file’s records to the temporary file, except for the Figure 1-3 The ENIAC computer
record that is to be deleted. The temporary file then takes the place of the
original file. You delete the original file and rename the temporary file, giving
it the name that the original file had on the computer’s disk.
6.19 An exception is an error that occurs while a program is running. In most
cases, an exception causes a program to abruptly halt.
6.20 The program halts.
6.21 IOError
6.22 ValueError
Chapter 7
7.1 [1, 2, 99, 4, 5]
7.2 [0, 1, 2]
7.4 1
courtesy of U.S. Army Historic Computer Images
3
5
7
9
Figure 1-4 A lab technician holds a modern microprocessor
7.5 4
7.8 [1, 2, 3]
[10, 20, 30, 1, 2, 3]
7.9 [2, 3]
7.10 [2, 3]
7.11 [1]
7.12 [1, 2, 3, 4, 5]
7.13 [3, 4, 5]
7.15 The remove method searches for and removes an element containing a
Creativa/Shutterstock
specific value. The del statement removes an element at a specific index.
7.16 You can use the built-in min and max functions.
1.2 Hardware and Software 27 716 Appendix G Answers to Checkpoints
Main Memory has not been converted to text. As a consequence, you cannot view the con-
tents of a binary file with a text editor.
You can think of main memory as the computer’s work area. This is where the computer
stores a program while the program is running, as well as the data that the program is 6.5 Sequential and direct access. When you work with a sequential access file,
working with. For example, suppose you are using a word processing program to write an you access data from the beginning of the file to the end of the file. When
essay for one of your classes. While you do this, both the word processing program and the you work with a direct access file, you can jump directly to any piece of data
essay are stored in main memory. in the file without reading the data that comes before it.
Main memory is commonly known as random-access memory, or RAM. It is called this 6.6 The file’s name on the disk and the name of a variable that references a file
because the CPU is able to quickly access data stored at any random location in RAM. object.
RAM is usually a volatile type of memory that is used only for temporary storage while
6.7 The file’s contents are erased.
a program is running. When the computer is turned off, the contents of RAM are erased.
Inside your computer, RAM is stored in chips, similar to the ones shown in Figure 1-5. 6.8 Opening a file creates a connection between the file and the program. It also
creates an association between the file and a file object.
6.9 Closing a file disconnects the program from the file.
Figure 1-5 Memory chips
6.10 A file’s read position marks the location of the next item that will be read
from the file. When an input file is opened, its read position is initially set to
the first item in the file.
6.11 You open the file in append mode. When you write data to a file in append
mode, the data is written to the end of the file’s existing contents.
Garsya/Shutterstock 6.12 outfile = open('numbers.txt', 'w')
for num in range(1, 11):
outfile.write(str(num) + '\n')
outfile.close()
Secondary Storage Devices
6.13 The readline method returns an empty string ('') when it has attempted to
Secondary storage is a type of memory that can hold data for long periods of time, even
read beyond the end of a file.
when there is no power to the computer. Programs are normally stored in secondary mem-
ory and loaded into main memory as needed. Important data, such as word processing 6.14 infile = open('numbers.txt', 'r')
documents, payroll data, and inventory records, is saved to secondary storage as well. line = infile.readline()
while line != '':
The most common type of secondary storage device is the disk drive. A traditional disk
print(line)
drive stores data by magnetically encoding it onto a spinning circular disk. Solid-state
line = infile.readline()
drives, which store data in solid-state memory, are increasingly becoming popular. A solid-
state drive has no moving parts and operates faster than a traditional disk drive. Most in le.close()
computers have some sort of secondary storage device, either a traditional disk drive or a 6.15 infile = open('data.txt', 'r')
solid-state drive, mounted inside their case. External storage devices, which connect to one for line in infile:
of the computer’s communication ports, are also available. External storage devices can print(line)
be used to create backup copies of important data or to move data to another computer. infile.close()
In addition to external storage devices, many types of devices have been created for copy- 6.16 A record is a complete set of data that describes one item, and a field is a
ing data and for moving it to other computers. For example, USB drives are small devices single piece of data within a record.
that plug into the computer’s USB (universal serial bus) port and appear to the system as
a disk drive. These drives do not actually contain a disk, however. They store data in a 6.17 You copy all the original file's records to the temporary file, but when you
special type of memory known as flash memory. USB drives, which are also known as get to the record that is to be modified, you do not write its old contents
memory sticks and flash drives, are inexpensive, reliable, and small enough to be carried to the temporary file. Instead, you write its new, modified values to the
in your pocket. temporary file. Then, you finish copying any remaining records from the
original file to the temporary file.
Appendix G Answers to Checkpoints 715 28 Chapter 1 Introduction to Computers and Programming
be changed during the program’s execution, you do not have to worry about Optical devices such as the CD (compact disc) and the DVD (digital versatile disc) are
its value being altered. also popular for data storage. Data is not recorded magnetically on an optical disc, but is
encoded as a series of pits on the disc surface. CD and DVD drives use a laser to detect
5.21 The difference is that a value returning function returns a value back to the
the pits and thus read the encoded data. Optical discs hold large amounts of data, and
statement that called it. A simple function does not return a value.
for that reason, recordable CD and DVD drives are commonly used for creating backup
5.22 A prewritten function that performs some commonly needed task copies of data.
5.23 The term “black box” is used to describe any mechanism that accepts input,
performs some operation (that cannot be seen) using the input, and produces Input Devices
output.
Input is any data the computer collects from people and from other devices. The compo-
5.24 It assigns a random integer in the range of 1 through 100 to the variable x. nent that collects the data and sends it to the computer is called an input device. Common
5.25 It prints a random integer in the range of 1 through 20. input devices are the keyboard, mouse, touchscreen, scanner, microphone, and digital cam-
era. Disk drives and optical drives can also be considered input devices, because programs
5.26 It prints a random integer in the range of 10 through 19. and data are retrieved from them and loaded into the computer’s memory.
5.27 It prints a random floating-point number in the range of 0.0 up to, but not
including, 1.0.
Output Devices
5.28 It prints a random floating-point number in the range of 0.1 through 0.5.
Output is any data the computer produces for people or for other devices. It might be
5.29 It uses the system time, retrieved from the computer’s internal clock. a sales report, a list of names, or a graphic image. The data is sent to an output device,
5.30 If the same seed value were always used, the random number functions which formats and presents it. Common output devices are video displays and printers.
would always generate the same series of pseudorandom numbers. Disk drives can also be considered output devices because the system sends data to them
in order to be saved.
5.31 It returns a value back to the part of the program that called it.
Software Development Tools Software development tools are the programs that pro- 5.5 When a program is developed as a set of functions in which each performs
grammers use to create, modify, and test software. Assemblers, compilers, and interpret- an individual task, then different programmers can be assigned the job of
ers are examples of programs that fall into this category. writing different functions.
5.6 A function definition has two parts: a header and a block. The header
Application Software indicates the starting point of the function, and the block is a list of
statements that belong to the function.
Programs that make a computer useful for everyday tasks are known as application soft-
ware. These are the programs that people normally spend most of their time running on 5.7 To call a function means to execute the function.
their computers. Figure 1-1, at the beginning of this chapter, shows screens from two com- 5.8 When the end of the function is reached, the computer returns back to the
monly used applications: Microsoft Word, a word processing program, and PowerPoint, a part of the program that called the function, and the program resumes
presentation program. Some other examples of application software are spreadsheet pro- execution at that point.
grams, email programs, web browsers, and game programs.
5.9 Because the Python interpreter uses the indentation to determine where a
block begins and ends
Checkpoint
5.10 A local variable is a variable that is declared inside a function. It belongs to
1.1 What is a program?
the function in which it is declared, and only statements in the same function
1.2 What is hardware? can access it.
1.3 List the five major components of a computer system.
5.11 The part of a program in which a variable may be accessed
1.4 What part of the computer actually runs programs?
5.12 Yes, it is permissible.
1.5 What part of the computer serves as a work area to store a program and its data
while the program is running? 5.13 Arguments
1.6 What part of the computer holds data for long periods of time, even when there is 5.14 Parameters
no power to the computer?
5.15 A parameter variable’s scope is the entire function in which the parameter is
1.7 What part of the computer collects data from people and from other devices?
declared.
1.8 What part of the computer formats and presents data for people or other devices?
5.16 No, it does not.
1.9 What fundamental set of programs control the internal operations of the
computer’s hardware? 5.17 a. passes by keyword argument
1.10 What do you call a program that performs a specialized task, such as a virus b. passes by position
scanner, a file compression program, or a data backup program? 5.18 The entire program
1.11 Word processing programs, spreadsheet programs, email programs, web browsers,
5.19 Here are three:
and game programs belong to what category of software?
Global variables make debugging difficult. Any statement in a program can
change the value of a global variable. If you find that the wrong value is being
stored in a global variable, you have to track down every statement that
1.3 How Computers Store Data accesses it to determine where the bad value is coming from. In a program
with thousands of lines of code, this can be difficult.
CONCEPT: All data that is stored in a computer is converted to sequences of 0s Functions that use global variables are usually dependent on those variables.
and 1s. If you want to use such a function in a different program, you will most likely
have to redesign it so it does not rely on the global variable.
A computer’s memory is divided into tiny storage locations known as bytes. One byte is Global variables make a program hard to understand. A global variable
only enough memory to store a letter of the alphabet or a small number. In order to do can be modified by any statement in the program. If you are to understand
anything meaningful, a computer has to have lots of bytes. Most computers today have any part of the program that uses a global variable, you have to be aware
millions, or even billions, of bytes of memory. of all the other parts of the program that access the global variable.
Each byte is divided into eight smaller storage locations known as bits. The term bit stands 5.20 A global constant is a name that is available to every function in the
for binary digit. Computer scientists usually think of bits as tiny switches that can be either program. It is permissible to use global constants. Because their value cannot
Appendix G Answers to Checkpoints 713 30 Chapter 1 Introduction to Computers and Programming
4.13 A variable that is used to accumulate the total of a series of numbers on or off. Bits aren’t actual “switches,” however, at least not in the conventional sense. In
most computer systems, bits are tiny electrical components that can hold either a positive
4.14 Yes, it should be initialized with the value 0. This is because values are added
or a negative charge. Computer scientists think of a positive charge as a switch in the on
to the accumulator by a loop. If the accumulator does not start at the value 0,
position, and a negative charge as a switch in the off position. Figure 1-6 shows the way
it will not contain the correct total of the numbers that were added to it when
that a computer scientist might think of a byte of memory: as a collection of switches that
the loop ends.
are each flipped to either the on or off position.
4.15 15
4.16 15
Figure 1-6 Think of a byte as eight switches
5
4.17 a) quantity += 1 ON ON ON ON
b) days_left −= 5
c) price *= 10
d) price /= 2
4.18 A sentinel is a special value that marks the end of a list of items.
4.19 A sentinel value must be unique enough that it will not be mistaken as a OFF OFF OFF OFF
regular value in the list.
4.20 It means that if bad data (garbage) is provided as input to a program, the
program will produce bad data (garbage) as output. When a piece of data is stored in a byte, the computer sets the eight bits to an on/off
4.21 When input is given to a program, it should be inspected before it is pattern that represents the data. For example, the pattern on the left in Figure 1-7 shows
processed. If the input is invalid, then it should be discarded and the user how the number 77 would be stored in a byte, and the pattern on the right shows how the
should be prompted to enter the correct data. letter A would be stored in a byte. We explain below how these patterns are determined.
4.22 The input is read, then a pretest loop is executed. If the input data is invalid,
the body of the loop executes. In the body of the loop, an error message is Figure 1-7 Bit patterns for the number 77 and the letter A
displayed so the user will know that the input was invalid, and then the
input read again. The loop repeats as long as the input is invalid. ON ON ON ON ON ON
4.23 It is the input operation that takes place just before an input validation loop.
The purpose of the priming read is to get the first input value.
4.24 None OFF
OFF OFF OFF OFF OFF OFF OFF OFF OFF
The position of each digit in a binary number has a value assigned to it. Starting with 3.26 You use the turtle.pencolor() function to determine the pen color.
the rightmost digit and moving left, the position values are 20, 21, 22, 23, and so forth, as You use the turtle.fillcolor() function to determine the current fill
shown in Figure 1-8. Figure 1-9 shows the same diagram with the position values calcu- color. You use the turtle.bgcolor() function to determine the current
lated. Starting with the rightmost digit and moving left, the position values are 1, 2, 4, 8, background color of the turtle’s graphics window.
and so forth.
3.27 You use the turtle.pensize() function.
3.28 You use the turtle.speed() function.
Figure 1-8 The values of binary digits as powers of 2
10011101 Chapter 4
0 4.1 A structure that causes a section of code to repeat
2
21 4.2 A loop that uses a true/false condition to control the number of times that it
22
23 repeats
24
25 4.3 A loop that repeats a specific number of times
26
27 4.4 An execution of the statements in the body of the loop
4.5 Before
Figure 1-9 The values of binary digits 4.6 None. The condition count < 0 will be false to begin with.
4.7 A loop that has no way of stopping and repeats until the program is
10011101 interrupted.
1 4.8 for x in range(6):
2
4 print('I love to program!')
8
16 4.9 0
32 1
64
128
2
3
4
5
To determine the value of a binary number, you simply add up the position values of all the
1s. For example, in the binary number 10011101, the position values of the 1s are 1, 4, 8, 4.10 2
16, and 128. This is shown in Figure 1-10. The sum of all of these position values is 157. 3
So, the value of the binary number 10011101 is 157. 4
5
3.13 if number == 1: Figure 1-11 shows how you can picture the number 157 stored in a byte of memory. Each
print('One') 1 is represented by a bit in the on position, and each 0 is represented by a bit in the off
elif number == 2: position.
print('Two')
elif number == 3:
print('Three') Figure 1-11 The bit pattern for 157
else:
print('Unknown')
Any piece of data that is stored in a computer’s memory must be stored as a binary num- 2.39 turtle.setup(500, 200)
ber. That includes characters, such as letters and punctuation marks. When a character is 2.40 turtle.goto(100, 50)
stored in memory, it is first converted to a numeric code. The numeric code is then stored
in memory as a binary number. 2.41 turtle.pos()
Over the years, different coding schemes have been developed to represent characters in 2.42 turtle.speed(10)
computer memory. Historically, the most important of these coding schemes is ASCII, 2.43 turtle.speed(0)
which stands for the American Standard Code for Information Interchange. ASCII is a set
of 128 numeric codes that represent the English letters, various punctuation marks, and 2.44 To fill a shape with a color, you use the turtle.begin_fill() command
other characters. For example, the ASCII code for the uppercase letter A is 65. When you before drawing the shape, then you use the turtle.end_fill() command
type an uppercase A on your computer keyboard, the number 65 is stored in memory (as after the shape is drawn. When the turtle.end_fill() command executes,
a binary number, of course). This is shown in Figure 1-13. the shape will be filled with the current fill color.
2.45 With the turtle.write()command
Figure 1-13 The letter A is stored in memory as the number 65
Chapter 3
1 1
A
3.1 A logical design that controls the order in which a set of statements execute
65 3.2 It is a program structure that can execute a set of statements only under
0 0 0 0 0 0
certain circumstances.
3.3 A decision structure that provides a single alternative path of execution.
If the condition that is being tested is true, the program takes the alternative
TIP : The acronym ASCII is pronounced “askee.” path.
3.4 An expression that can be evaluated as either true or false
In case you are curious, the ASCII code for uppercase B is 66, for uppercase C is 67, and so 3.5 You can determine whether one value is greater than, less than, greater than
forth. Appendix C shows all of the ASCII codes and the characters they represent. or equal to, less than or equal to, equal to, or not equal to another value.
The ASCII character set was developed in the early 1960s and was eventually adopted by 3.6 if y == 20:
almost all computer manufacturers. ASCII is limited, however, because it defines codes for x = 0
only 128 characters. To remedy this, the Unicode character set was developed in the early 3.7 if sales >= 10000:
1990s. Unicode is an extensive encoding scheme that is compatible with ASCII, but can commissionRate = 0.2
also represent characters for many of the languages in the world. Today, Unicode is quickly
becoming the standard character set used in the computer industry. 3.8 A dual alternative decision structure has two possible paths of execution;
one path is taken if a condition is true, and the other path is taken if the
condition is false.
Advanced Number Storage 3.9 if-else
Earlier, you read about numbers and how they are stored in memory. While reading that 3.10 When the condition is false
section, perhaps it occurred to you that the binary numbering system can be used to repre-
sent only integer numbers, beginning with 0. Negative numbers and real numbers (such as 3.11 z is not less than a.
3.14159) cannot be represented using the simple binary numbering technique we discussed. 3.12 Boston
Computers are able to store negative numbers and real numbers in memory, but to do so New York
they use encoding schemes along with the binary numbering system. Negative numbers are
encoded using a technique known as two’s complement, and real numbers are encoded in
floating-point notation. You don’t need to know how these encoding schemes work, only
that they are used to convert negative numbers and real numbers to binary format.
Appendix G Answers to Checkpoints 709 34 Chapter 1 Introduction to Computers and Programming
01
0
2.20 4
00
10
101
101
2.21 1
2.22 If you do not want the print function to start a new line of output when it
finishes displaying its output, you can pass the special argument end = ' '
to the function.
The music that you play on your CD player, iPod, or MP3 player is also digital. A digital
2.23 You can pass the argument sep= to the print function, specifying the song is broken into small pieces known as samples. Each sample is converted to a binary
desired character. number, which can be stored in memory. The more samples that a song is divided into, the
2.24 It is the newline escape character. more it sounds like the original music when it is played back. A CD quality song is divided
into more than 44,000 samples per second!
2.25 It is the string concatenation operator, which joins two strings together.
2.26 65.43 Checkpoint
2.27 987,654.13 1.12 What amount of memory is enough to store a letter of the alphabet or a small
number?
2.28 (1) Named constants make programs more self-explanatory, (2) widespread
changes can easily be made to the program, and (3) they help to prevent the 1.13 What do you call a tiny “switch” that can be set to either on or off?
typographical errors that are common when using magic numbers. 1.14 In what numbering system are all numeric values written as sequences of 0s and 1s?
2.35 turtle.circle(100) CONCEPT : A computer’s CPU can only understand instructions that are written in
machine language. Because people find it very difficult to write entire
2.36 turtle.pensize(8)
programs in machine language, other programming languages have been
2.37 turtle.pencolor('blue') invented.
1.4 How a Program Works 35 708 Appendix G Answers to Checkpoints
Earlier, we stated that the CPU is the most important component in a computer because it is 1.18 Machine language
the part of the computer that runs programs. Sometimes the CPU is called the “computer’s
1.19 Main memory, or RAM
brain” and is described as being “smart.” Although these are common metaphors, you
should understand that the CPU is not a brain, and it is not smart. The CPU is an electronic 1.20 The fetch-decode-execute cycle
device that is designed to do specific things. In particular, the CPU is designed to perform
1.21 It is an alternative to machine language. Instead of using binary numbers
operations such as the following:
for instructions, assembly language uses short words that are known as
Reading a piece of data from main memory mnemonics.
Adding two numbers
1.22 A high-level language
Subtracting one number from another number
Multiplying two numbers 1.23 Syntax
Dividing one number by another number
1.24 A compiler
Moving a piece of data from one memory location to another
Determining whether one value is equal to another value 1.25 An interpreter
As you can see from this list, the CPU performs simple operations on pieces of data. The 1.26 A syntax error
CPU does nothing on its own, however. It has to be told what to do, and that’s the purpose
of a program. A program is nothing more than a list of instructions that cause the CPU to
perform operations. Chapter 2
Each instruction in a program is a command that tells the CPU to perform a specific opera- 2.1 Any person, group, or organization that is asking you to write a program
tion. Here’s an example of an instruction that might appear in a program: 2.2 A single function that the program must perform in order to satisfy the
10110000 customer
To you and me, this is only a series of 0s and 1s. To a CPU, however, this is an instruction 2.3 A set of well-defined logical steps that must be taken to perform a task
to perform an operation.1 It is written in 0s and 1s because CPUs only understand instruc- 2.4 An informal language that has no syntax rules and is not meant to be
tions that are written in machine language, and machine language instructions always have compiled or executed. Instead, programmers use pseudocode to create
an underlying binary structure. models, or “mock-ups,” of programs.
A machine language instruction exists for each operation that a CPU is capable of perform- 2.5 A diagram that graphically depicts the steps that take place in a program
ing. For example, there is an instruction for adding numbers, there is an instruction for
subtracting one number from another, and so forth. The entire set of instructions that a 2.6 Ovals are terminal symbols. Parallelograms are either output or input
CPU can execute is known as the CPU’s instruction set. symbols. Rectangles are processing symbols.
2.7 print('Jimmy Smith')
The machine language instruction that was previously shown is an example of only one
instruction. It takes a lot more than one instruction, however, for the computer to do any-
thing meaningful. Because the operations that a CPU knows how to perform are so basic in
nature, a meaningful task can be accomplished only if the CPU performs many operations.
For example, if you want your computer to calculate the amount of interest that you will
APP ENDIX
earn from your savings account this year, the CPU will have to perform a large number of
G
instructions, carried out in the proper sequence. It is not unusual for a program to contain
Answers to Checkpoints thousands or even millions of machine language instructions.
Programs are usually stored on a secondary storage device such as a disk drive. When you
install a program on your computer, the program is typically copied to your computer’s disk
drive from a CD-ROM, or downloaded from a website.
Although a program can be stored on a secondary storage device such as a disk drive,
it has to be copied into main memory, or RAM, each time the CPU executes it. For
example, suppose you have a word processing program on your computer’s disk. To
execute the program, you use the mouse to double-click the program’s icon. This causes
Chapter 1
the program to be copied from the disk into main memory. Then, the computer’s CPU
1.1 A program is a set of instructions that a computer follows to perform a task. executes the copy of the program that is in main memory. This process is illustrated in
1.2 Hardware is all the physical devices, or components, of which a computer is Figure 1-15.
made.
1.3 The central processing unit (CPU), main memory, secondary storage devices, Figure 1-15 A program is copied into main memory and then executed
input devices, and output devices
The program is copied
1.4 The CPU The CPU executes
from secondary storage
the program in
to main memory.
1.5 Main memory main memory.
Main memory
1.6 Secondary storage (RAM)
1.7 Input device
1.8 Output device
1.9 The operating system Disk drive CPU
707
1.4 How a Program Works 37
10100001
Fetch the next instruction
1
in the program.
10100001
10111000 Decode the instruction
10011110 2 to determine which
00011010 operation to perform.
11011100
and so forth... CPU
Execute the instruction
3
(perform the operation).
Main memory
(RAM)
N OTE : There are many different versions of assembly language. It was mentioned
earlier that each brand of CPU has its own machine language instruction set. Each
brand of CPU typically has its own assembly language as well.
Assembly language programs cannot be executed by the CPU, however. The CPU only
understands machine language, so a special program known as an assembler is used to
translate an assembly language program to a machine language program. This process is
shown in Figure 1-17. The machine language program that is created by the assembler can
then be executed by the CPU.
2
The first assembly language was most likely that developed in the 1940s at Cambridge University
for use with a historic computer known as the EDSAC.
38 Chapter 1 Introduction to Computers and Programming
F
mov eax, Z 10100001
add eax, 2
mov Y, eax 10111000
High-Level Languages
Although assembly language makes it unnecessary to write binary machine language instruc-
The Python standard library provides classes and functions that your programs can use to tions, it is not without difficulties. Assembly language is primarily a direct substitute for
perform basic operations, as well as many advanced tasks. There are operations, however, machine language, and like machine language, it requires that you know a lot about the
that the standard library cannot perform. When you need to do something that is beyond CPU. Assembly language also requires that you write a large number of instructions for even
the scope of the standard library, you have two choices: write the code yourself, or use code the simplest program. Because assembly language is so close in nature to machine language,
that someone else has already written. it is referred to as a low-level language.
Fortunately, there are thousands of Python modules, written by independent programmers, In the 1950s, a new generation of programming languages known as high-level languages
that provide capabilities that the standard Python library does not offer. These are known began to appear. A high-level language allows you to create powerful and complex pro-
as third-party modules. A large collection of third-party modules exists at the website pypi. grams without knowing how the CPU works and without writing large numbers of low-level
python.org, which is known as the Python Package Index, or PyPI. instructions. In addition, most high-level languages use words that are easy to understand.
For example, if a programmer were using COBOL (which was one of the early high-level
The modules that are available at PyPI are organized as packages. A package is simply a coll- languages created in the 1950s), he or she would write the following instruction to display
ection of one or more related modules. The easiest way to download and install a package the message Hello world on the computer screen:
is with the pip utility. The pip utility is a program that is part of the standard Python
installation, beginning with Python 3.4. To install a package on a Windows system with DISPLAY "Hello world"
the pip utility, you must open a command prompt window, and type a command following Python is a modern, high-level programming language that we will use in this book. In
this format: Python you would display the message Hello world with the following instruction:
pip install package_name print('Hello world')
package_name is the name of a package that you want to download and install. If you are
Doing the same thing in assembly language would require several instructions and an inti-
running a Mac or a Linux system, you must use the pip3 command instead of the pip com-
mate knowledge of how the CPU interacts with the computer’s output device. As you can see
mand. In addition, you will need superuser privileges to execute the pip3 command on a
from this example, high-level languages allow programmers to concentrate on the tasks they
Mac or Linux system, so you will have to prefix the command with sudo, as shown here: want to perform with their programs, rather than the details of how the CPU will execute
sudo pip3 install package_name those programs.
Once you enter the command, the pip utility will start downloading and installing the Since the 1950s, thousands of high-level languages have been created. Table 1-1 lists several
package. Depending on the size of the package, it may take a few minutes to complete the of the more well-known languages.
installation process. Once the process is finished, you can typically verify that the package
was correctly installed by starting IDLE and entering the command
Key Words, Operators, and Syntax: An Overview
>>> import package_name
Each high-level language has its own set of predefined words that the programmer must
where package_name is the name of the package that you installed. If you do not see an use to write a program. The words that make up a high-level programming language are
error message, you can assume the package was successfully installed. known as key words or reserved words. Each key word has a specific meaning, and cannot
In Chapter 7, you will explore a popular third-party package named matplotlib. You can be used for any other purpose. Table 1-2 shows all of the Python key words.
use the matplotlib package to create charts and graphs.
705
1.4 How a Program Works 39
Using an Alias In addition to key words, programming languages have operators that perform various
operations on data. For example, all programming languages have math operators that
You can use the as keyword to assign an alias to a module when you import it. The follow- perform arithmetic. In Python, as well as most other languages, the + sign is an operator
ing statement shows an example: that adds two numbers. The following adds 12 and 75:
import math as mt 12 + 75
This statement loads the math module into memory, assigning the module the alias mt. There are numerous other operators in the Python language, many of which you will learn
To use any of the items that are in the module, you prefix the item’s name with the alias, about as you progress through this text.
followed by a dot. For example, to call the sqrt function, you would use the name
mt.sqrt. The following interactive session shows an example: In addition to key words and operators, each language also has its own syntax, which is a
set of rules that must be strictly followed when writing a program. The syntax rules dictate
>>> import math as mt how key words, operators, and various punctuation characters must be used in a program.
>>> x = mt.sqrt(25) When you are learning a programming language, you must learn the syntax rules for that
>>> a = mt.radians(180) particular language.
>>> print(x)
5.0 The individual instructions that you use to write a program in a high-level programming
>>> print(a) language are called statements. A programming statement can consist of key words, oper-
3.141592653589793 ators, punctuation, and other allowable programming elements, arranged in the proper
>>> sequence to perform an operation.
You can also assign an alias to a specific function or class when you import it. The follow-
ing statement imports the sqrt function from the math module, and assigns the function Compilers and Interpreters
the alias square_root:
Because the CPU understands only machine language instructions, programs that are writ-
from math import sqrt as square_root ten in a high-level language must be translated into machine language. Depending on the
language in which a program has been written, the programmer will use either a compiler
After using this import statement, you would use the name square_root to call the sqrt
or an interpreter to make the translation.
function. The following interactive session shows an example:
A compiler is a program that translates a high-level language program into a separate
>>> from math import sqrt as square_root
machine language program. The machine language program can then be executed any time
>>> x = square_root(25)
it is needed. This is shown in Figure 1-18. As shown in the figure, compiling and executing
>>> print(x)
are two different processes.
5.0
>>> Figure 1-18 Compiling a high-level program and executing it
In the following interactive session, we import two functions from the math module, giving
High-level language Machine language
each of them an alias. The sqrt function is imported as square_root, and the tan func- program
program
tion is imported as tangent:
The compiler is used 10100001
print ("Hello
>>> from math import sqrt as square_root, tan as tangent 1 to translate the high-level Earthling") 10111000
language program to a Compiler
>>> x = square_root(25) 10011110
machine language program. and so forth... and so forth...
>>> y = tangent(45)
>>> print(x)
5.0
>>> print(y)
1.6197751905438615
Machine language
CPU
program
The machine language 10100001
2 program can be executed 10111000
at any time, without using 10011110
the compiler. and so forth...
1.4 How a Program Works 41 702 Appendix E More About the import Statement
The Python language uses an interpreter, which is a program that both translates and This statement causes only the sqrt function to be imported from the math module. It also
executes the instructions in a high-level language program. As the interpreter reads allows you to call the sqrt function without prefixing the function’s name with the name
each individual instruction in the program, it converts it to machine language instruc- of the module. The following interactive session shows an example:
tions then immediately executes them. This process repeats for every instruction in
>>> from math import sqrt
the program. This process is illustrated in Figure 1-19. Because interpreters combine
>>> x = sqrt(25)
translation and execution, they typically do not create separate machine language
>>> print(x)
programs.
5.0
>>>
Figure 1-19 Executing a high-level program with an interpreter You can specify the names of multiple items, separated with commas, when you use this
form of the import statement. For example, the import statement in the following interac-
High-level language tive session imports only the sqrt function and the radians function from the math
program CPU module:
Machine language
print ("Hello instruction
>>> from math import sqrt, radians
Earthling") Interpreter 10100001
>>> x = sqrt(25)
and so forth... >>> a = radians(180)
>>> print(x)
5.0
The interpreter translates each high-level instruction to
>>> print(a)
its equivalent machine language instructions then 3.141592653589793
immediately executes them. >>>
This process is repeated for each high-level instruction.
Wildcard Imports
The statements that a programmer writes in a high-level language are called source A wildcard import statement loads the entire contents of a module. Here is an example:
code, or simply code. Typically, the programmer types a program’s code into a text
editor then saves the code in a file on the computer’s disk. Next, the programmer uses from math import *
a compiler to translate the code into a machine language program, or an interpreter to The difference between this statement and the import math statement is that the wildcard
translate and execute the code. If the code contains a syntax error, however, it cannot import statement does not require you to use the qualified names of the items in the mod-
be translated. A syntax error is a mistake such as a misspelled key word, a missing ule. For example, here is an interactive session that uses a wildcard import statement:
punctuation character, or the incorrect use of an operator. When this happens, the
compiler or interpreter displays an error message indicating that the program contains >>> from math import*
a syntax error. The programmer corrects the error then attempts once again to translate >>> x = sqrt(25)
the program. >>> a = radians(180)
>>>
And, here is an interactive session that uses the regular import statement:
N OTE : Human languages also have syntax rules. Do you remember when you took >>> import math
your first English class, and you learned all those rules about commas, apostrophes, >>> x = math.sqrt(25)
capitalization, and so forth? You were learning the syntax of the English language. >>> a = math.radians(180)
>>>
Although people commonly violate the syntax rules of their native language when
speaking and writing, other people usually understand what they mean. Unfortunately, Typically, you should avoid using the wildcard import statement because it can lead to
compilers and interpreters do not have this ability. If even a single syntax error appears name clashes when you are importing several modules. A name clash occurs when a
in a program, the program cannot be compiled or executed. When an interpreter program imports two modules that have functions or classes with the same name. Name
encounters a syntax error, it stops executing the program. clashes do not occur when you are using the qualified names of a module’s functions
and/or classes.
42 Chapter 1 Introduction to Computers and Programming
Checkpoint
1.18 A CPU understands instructions that are written only in what language?
1.19 A program has to be copied into what type of memory each time the CPU
executes it?
1.20 When a CPU executes the instructions in a program, it is engaged in what process?
More About the import
APP ENDIX
E
1.21 What is assembly language?
1.22 What type of programming language allows you to create powerful and complex
Statement 1.23
programs without knowing how the CPU works?
Each language has a set of rules that must be strictly followed when writing a
program. What is this set of rules called?
1.24 What do you call a program that translates a high-level language program into a
separate machine language program?
1.25 What do you call a program that both translates and executes the instructions in
A module is a Python source code file that contains functions and/or classes. Many of the a high-level language program?
functions in the Python standard library are stored in modules. For example, the math mod- 1.26 What type of mistake is usually caused by a misspelled key word, a missing
ule contains various mathematical functions, and the random module contains functions for punctuation character, or the incorrect use of an operator?
working with random numbers.
In order to use the functions and/or classes that are stored in a module, you must import the
module. To import a module, you write an import statement at the top of your program.
1.5 Using Python
Here is an import statement that imports the math module:
CONCEPT : The Python interpreter can run Python programs that are saved in files
import math
or interactively execute Python statements that are typed at the keyboard.
This statement causes the Python interpreter to load the contents of the math module into Python comes with a program named IDLE that simplifies the process of
memory, making the functions and/or classes that are stored in the math module available writing, executing, and testing programs.
to the program. To use any item that is in the module, you must use the item’s qualified
name. This means that you must prefix the item’s name with the name of the module, fol-
lowed by a dot. For example, the math module has a function named sqrt that returns the Installing Python
square root of a number. To call the sqrt function, you would use the name math.sqrt. Before you can try any of the programs shown in this book, or write any programs of your
The following interactive session shows an example: own, you need to make sure that Python is installed on your computer and properly con-
>>> import math
figured. If you are working in a computer lab, this has probably been done already. If you
>>> x = math.sqrt(25)
are using your own computer, you can follow the instructions in Appendix A to download
>>> print(x)
and install Python.
5.0
>>> The Python Interpreter
You learned earlier that Python is an interpreted language. When you install the Python
language on your computer, one of the items that is installed is the Python interpreter. The
Importing a Specific Function or Class Python interpreter is a program that can read Python programming statements and execute
The previously shown form of the import statement loads the entire contents of a module them. (Sometimes, we will refer to the Python interpreter simply as the interpreter.)
into memory. Sometimes you want to import only a specific function or class from a mod-
You can use the interpreter in two modes: interactive mode and script mode. In interac-
ule. When this is the case, you can use the from keyword with the import statement, as
tive mode, the interpreter waits for you to type Python statements on the keyboard. Once
shown here:
you type a statement, the interpreter executes it and then waits for you to type another
from math import sqrt statement. In script mode, the interpreter reads the contents of a file that contains Python
statements. Such a file is known as a Python program or a Python script. The interpreter
executes each statement in the Python program as it reads it.
701
1.5 Using Python 43
Interactive Mode
Once Python has been installed and set up on your system, you start the interpreter in
interactive mode by going to the operating system’s command line and typing the follow-
ing command:
python
If you are using Windows, you can alternatively type python in the Windows search box.
In the search results, you will see a program named something like Python 3.5. (The “3.5”
is the version of Python that is installed. At the time this is being written, Python 3.5 is
the latest version.) Clicking this item will start the Python interpreter in interactive mode.
When the Python interpreter starts in interactive mode, you will see something like the fol-
lowing displayed in a console window:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48)
[MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license"
for more information. This page intentionally left blank
>>>
The >>> that you see is a prompt that indicates the interpreter is waiting for you to type
a Python statement. Let’s try it out. One of the simplest things that you can do in Python
is print a message on the screen. For example, the following statement prints the message
Python programming is fun! on the screen:
print('Python programming is fun!')
You can think of this as a command that you are sending to the Python interpreter. If
you type the statement exactly as it is shown, the message Python programming is fun! is
printed on the screen. Here is an example of how you type this statement at the interpreter’s
prompt:
>>> print('Python programming is fun!') Enter
After typing the statement, you press the Enter key, and the Python interpreter executes the
statement, as shown here:
>>> print('Python programming is fun!') Enter
Python programming is fun!
>>>
Appendix D Predefined Named Colors 699 44 Chapter 1 Introduction to Computers and Programming
'gray3' 'gray4' 'gray5' After the message is displayed, the >>> prompt appears again, indicating the interpreter is
'gray6' 'gray7' 'gray8' waiting for you to enter another statement. Let’s look at another example. In the following
sample session, we have entered two statements:
'gray9' 'gray10' 'gray11'
>>> print('To be or not to be') Enter
'gray12' 'gray13' 'gray14'
To be or not to be
'gray15' 'gray16' 'gray17' >>> print('That is the question.') Enter
'gray18' 'gray19' 'gray20' That is the question.
>>>
'gray21' 'gray22' 'gray23'
'gray24' 'gray25' 'gray26' If you incorrectly type a statement in interactive mode, the interpreter will display an error
message. This will make interactive mode useful to you while you learn Python. As you
'gray27' 'gray28' 'gray29'
learn new parts of the Python language, you can try them out in interactive mode and get
'gray30' 'gray31' 'gray32' immediate feedback from the interpreter.
'gray33' 'gray34' 'gray35' To quit the Python interpreter in interactive mode on a Windows computer, press Ctrl-Z
'gray36' 'gray37' 'gray38' (pressing both keys together) followed by Enter. On a Mac, Linux, or UNIX computer,
press Ctrl-D.
'gray39' 'gray40' 'gray42'
'gray43' 'gray44' 'gray45'
'gray46' 'gray47' 'gray48' N O TE : In Chapter 2, we will discuss the details of statements like the ones previously
shown. If you want to try them now in interactive mode, make sure you type them exactly
'gray49' 'gray50' 'gray51'
as shown.
'gray52' 'gray53' 'gray54'
'gray55' 'gray56' 'gray57'
'gray58' 'gray59' 'gray60' Writing Python Programs and Running
'gray61' 'gray62' 'gray63' Them in Script Mode
'gray64' 'gray65' 'gray66' Although interactive mode is useful for testing code, the statements that you enter in interac-
tive mode are not saved as a program. They are simply executed and their results displayed on
'gray67' 'gray68' 'gray69'
the screen. If you want to save a set of Python statements as a program, you save those state-
'gray70' 'gray71' 'gray72' ments in a file. Then, to execute the program, you use the Python interpreter in script mode.
'gray73' 'gray74' 'gray75' For example, suppose you want to write a Python program that displays the following three
'gray76' 'gray77' 'gray78' lines of text:
'gray79' 'gray80' 'gray81' Nudge nudge
'gray82' 'gray83' 'gray84' Wink wink
Know what I mean?
'gray85' 'gray86' 'gray87'
'gray88' 'gray89' 'gray90'
To write the program you would use a simple text editor like Notepad (which is installed
on all Windows computers) to create a file containing the following statements:
'gray91' 'gray92' 'gray93'
print('Nudge nudge')
'gray94' 'gray95' 'gray97'
print('Wink wink')
'gray98' 'gray99' print('Know what I mean?')
N O TE : It is possible to use a word processor to create a Python program, but you must
be sure to save the program as a plain text file. Otherwise, the Python interpreter will
not be able to read its contents.
GLOBAL GLOBAL
EDITION EDITION
RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO
THIS INFORMATION, INCLUDING ALL WARRANTIES AND CONDITIONS OF MERCHANTABILITY,
Digital Resources for Students WHETHER EXPRESS, IMPLIED OR STATUTORY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
Your new textbook provides 12-month access to digital resources that may include WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
VideoNotes (step-by-step video tutorials on programming concepts), source code, web
WITH THE USE OR PERFORMANCE OF INFORMATION AVAILABLE FROM THE SERVICES. THE
chapters, quizzes, and more. Refer to the preface in the textbook for a detailed list of DOCUMENTS AND RELATED GRAPHICS CONTAINED HEREIN COULD INCLUDE TECHNICAL
resources. INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO
THE INFORMATION HEREIN. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS MAY MAKE
Follow the instructions below to register for the Companion Website for Tony Gaddis’ IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED
Starting Out with Python, Fourth Edition, Global Edition. HEREIN AT ANY TIME. PARTIAL SCREEN SHOTS MAY BE VIEWED IN FULL WITHIN THE SOFTWARE
VERSION SPECIFIED.
1. Go to www.pearsonglobaleditions.com/gaddis
2. Enter the title of your textbook or browse by author name.
3. Click Companion Website.
4. Click Register and follow the on-screen instructions to create a login name
and password.
ISSGPY-PRANK-CURRY-PIQUE-METIS-ROUSE
Use the login name and password you created during registration to start using the
online resources that accompany your textbook.
IMPORTANT:
This prepaid subscription does not include access to MyProgrammingLab, which is
available at www.myprogramminglab.com for purchase.
This subscription is valid for 12 months upon activation and is not transferable.
743
742 Index
P
defined, 261 Widgets
general format, 272 arrangement of, 630
how to use, 274–276 Button, 622, 630–633
®
and IPO charts, 276–277 Canvas, 622
randint and, 263–266 Checkbutton, 622, 648–650
random number generation, 262–271 defined, 622
randrange and, 269–270 Entry, 622, 633–636
returning multiple values, 282–283 Frame, 622, 629
return statement, 272–274 with frames, organizing, 627–630
for simplifying mathematical expressions, 274–276 Label, 622, 625–626, 629, 636–640
values, 261, 274 Listbox, 622
void functions and, 233 list of, 641
F OUR TH ED ITION writing, 272–283
Values
Menu, 622
Menubutton, 622
P
str data type, 69–70 as base classes, 574
str function defined, 574
defined, 326 in UML diagrams, 582–583
®
example use, 323 writing, 575
String comparisons, 144–147, 444–445, 463, 464 Supersets, 492
String concatenation SUV class, 580–581
defined, 90, 434 Symbols, flowchart, 56
example, 90 symmetric_difference method, 491
interactive sessions, 434 Symmetric difference of sets, 491
newline to, 319–320 Syntax
with + operator, 90 defined, 40
with += operator, 435 human language, 41
F OUR TH ED ITION String literals
defined, 59
Syntax errors
correcting, 54
GLOBA L EDITION enclosing in triple quotes, 60
Strings
defined, 41
reporting, 691
characters, accessing, 430–434 running programs and, 691
comparing, 144–148 System software, 28–29
defined, 59
extracting characters from, 438–440 T
as immutable, 435–436 tan() function, 285
Tony Gaddis
indexes, 432–433 Target variables
iterating with for loop, 430–432 defined, 192
list of, 366 inside for loops, 194–196
Haywood Community College method call format, 442 use example, 195
modification methods, 444–445 Terminal symbols, 56
operations, 429–436 Testing
raw, 314 dictionary values, 463–464
reading as input, 429 programs, 54–55
repetition operator (*) with, 450–451 set values, 488–489
returning, 280 string methods, 442–443
search and replace methods, 445–446 strings, 441
slicing, 437–438 Text
space character at end, 73 drawing with Canvas widget, 667–672
splitting, 451–452 displaying with Label widget, 624–627
storing with str data type, 69–70 editing, 687–688
stripping newline from, 320–322 font setting, 670–672
testing, 441 Text files
testing methods, 442–443 defined, 311
writing as output, 429 reading numbers from, 324
written to files, 316 Text widget, 622
StringVar object, 636–637 third-party modules, 705
strip() method, 444 Tkinter module
Stripping newline from string, 320–322 defined, 621
Structure charts. See Hierarchy charts programs using, 622
Subclasses widgets, 622
defined, 574 Top-down design
as derived classes, 574 defined, 240
method override, 588 process, 240–241
�)è“ÜÊÃ�ZãØ——ã �B—ô�xÊع �Bx�
Index 739
Running programs, 690–691 set method, 640, 647 Senior Vice President Courseware Portfolio Management: Marcia J. Horton
Running totals Sets Director, Portfolio Management: Engineering,
calculating, 201–204 adding elements, 486–487 Computer Science & Global Editions: Julian Partridge
defined, 201 creating, 485
Portfolio Manager: Matt Goldstein
elements for calculating, 201 defined, 484
example, 202 difference of, 490–491
Acquisitions Editor, Global Edition: Sourabh Maheshwari
logic for calculating, 201 duplicate elements, 485 Portfolio Management Assistant: Kristy Alaura
elements, as unique, 484 Field Marketing Manager: Demetrius Hall
S elements, number of, 486 Product Marketing Manager: Yvonne Vannatta
Samples, 34 elements, removing, 487–488 Managing Producer, ECS and Math: Scott Disanno
Saving programs, 690 intersection of, 490 Content Producer: Sandra L. Rodriguez
SavingsAccount class, 584, 585 for loop iteration over, 488
Project Editors, Global Edition: Tanima Ghosh and Neelakantan K.K.
Scale widget, 622 operations, 493–495
Scientific notation, 92 subsets, 492
Senior Manufacturing Controller, Global Edition: Jerry Kataria
Scope supersets, 492 Manager, Media Production, Global Edition: Vikram Kumar
defined, 245 symmetric difference of, 491 Cover Designer: Lumina Datamatics
local variables and, 245–247 union of, 489 Cover Photo: Africa Studio/Shutterstock
parameter variable, 249 unordered, 484
Credits and acknowledgments borrowed from other sources and reproduced, with permission, appear
Script mode, running programs in, 45 values, testing, 488–489
Scrollbar widget, 622 Settings. See Mutator methods
on the Credits page in the endmatter of this textbook.
Searching Showinfo function, 630 Pearson Education Limited
lists, 376–377 sin() function, 285
KAO Two
records, 339–341 Single alternative decision structures, 132
strings, 445–446 Slices KAO Park
Secondary storage defined, 373 Harlow
defined, 27 example use, 373–375 CM17 9NA
devices, 27–28 general format, 373 United Kingdom
Seeds, random number, 270–271 invalid indexes and, 375
Seed value, 270 list, 373–376 and Associated Companies throughout the world
Selection structures. See Decision structures start and end index, 374
Visit us on the World Wide Web at: www.pearsonglobaleditions.com
Sentinels string, 437–438
defined, 204, 205 Software © Pearson Education Limited 2019
using, 205–206 application, 29
values, 204–205 defined, 23 The rights of Tony Gaddis to be identified as the author of this work has been asserted by him in accor-
Separators developers. See Programmers dance with the Copyright, Designs and Patents Act 1988.
comma, 92–93 development tools, 29
item, 88–89 operating system, 28 Authorized adaptation from the United States edition, entitled Starting Out with Python, 4th Edition,
split method, 451–452 requirements, 55 ISBN 978-0-13-444432-1 by Tony Gaddis, published by Pearson Education © 2018.
Sequences. See also Lists system, 28–29
accepting as argument, 383–384 types of, 28 All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted
defined, 365 utility programs, 28 in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without either
length, returning, 369 Sorting, item list, 381–382 the prior written permission of the publisher or a license permitting restricted copying in the United Kingdom
tuples, 402–404 sort method, 378, 381–382
issued by the Copyright Licensing Agency Ltd, Sa ron House, 6–10 Kirby Street, London EC1N 8TS.
Sequence structures Source code. See Code
with decision structure, 147 Specialization, 573–574 All trademarks used herein are the property of their respective owners. The use of any trademark in this
defined, 131 split method, 451 text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor
example, 131 Splitting strings, 451–452
does the use of such trademarks imply any a liation with or endorsement of this book by such owners.
nested inside decision structure, 148 sqrt() function, 285
structure, 147, 148 startswith method, 445, 446
British Library Cataloguing-in-Publication Data
use in programming, 131–132 Statements
Serializing objects for, 190, 194, 196 A catalogue record for this book is available from the British Library
defined, 496 assignment, 62–65
10 9 8 7 6 5 4 3 2 1
example, 498–500, 542–544 in blocks, 133, 235
pickle module, 496–497 breaking into multiple lines, 86–87 ISBN 10: 1-292-22575-0
unserializing, 500–502, 543–544 converting math formulas to, 83–85 ISBN 13: 978-1-292-22575-3
ServiceQuote class, 563–565 defined, 40
set function, 485 del, 383 Typeset by iEnergizer Aptara®, Ltd.
Printed and bound in Malaysia
738 Index
7
Index 735 8 Contents
Chapter 8 More About Strings 429 not operator, 155, 157 multiplication (*), 76, 79, 367
8.1 Basic String Operations 429 Nouns, list refining, 557–560 not in. See Not in operator
8.2 String Slicing 437 Numbers or, 155–157, 159, 160
advanced storage, 34 precedence, 79
8.3 Testing, Searching, and Manipulating Strings 441
binary, 31–32 relational, 133–134, 145–146
Review Questions 453 factorial of, 603–605 remainder (%), 76, 79, 82–83
Programming Exercises 456 Fibonacci, 607–609 repetition (*), 367, 450–451
floating-point, 33, 94 subtraction (−), 76, 79
Chapter 9 Dictionaries and Sets 461 formatting, 90–91 Optical devices, 28
9.1 Dictionaries 461 pseudorandom, 270–271 or operator, 155–157, 159, 160
9.2 Sets 484 random, 262–271 Output
9.3 Serializing Objects 496 running totals, 201–204 in computer program process, 57–58
storage, 31–33 data, 87–95
Review Questions 502
Numeric literals, 69 defined, 28
Programming Exercises 507 Numeric ranges, with logical operators, 160 displaying, 58–61
Output devices, 28
Chapter 10 Classes and Object-Oriented Programming 511 Output files, 310, 311, 315, 322, 326
10.1 Procedural and Object-Oriented Programming 511 O
Overhead, 602
Object-oriented programming (OOP)
10.2 Classes 515 class design, 554–565
Overriding, method, 588
10.3 Working with Instances 532 classes, 515–532
10.4 Techniques for Designing Classes 554 data hiding, 512
P
pack method, 625–627, 629, 634
Review Questions 565 defined, 512
Parameter lists, 252
Programming Exercises 568 encapsulation, 512
Parentheses, grouping with, 80
instances, 515, 532–554
Pascal, 39
Chapter 11 Inheritance 573 Objects, 629. See also Classes
Passing arguments. See also Arguments
11.1 Introduction to Inheritance 573 characteristics description, 515
to function, 248–251
11.2 Polymorphism 588 defined, 512
function parameter variable, 253–255
dictionary, 461–484
Review Questions 594 to index method, 379–381
everyday example of, 513–514
Programming Exercises 596 list as function, 389–390
exception, 359 multiple, 251–253
file, 316–317 and objects, 540–541
Chapter 12 Recursion 599 list, 365, 366 by position, 252
12.1 Introduction to Recursion 599 “is a” relationship, 574 by value, 255
12.2 Problem Solving with Recursion 602 passing as arguments, 540–541 Passwords, validating characters in, 446–449
12.3 Examples of Recursive Algorithms 606 pickling, 542–544 Pattern printing using nested loops, 215–218
Review Questions 614 reusability, 513 Percentages, calculations, 77–78
Programming Exercises 616 sequence, 365 Pickle module, 497–498, 542, 547
serializing, 496–502 Pickling, 496–498, 500, 542–544
Chapter 13 GUI Programming 619 set, 484–496 pi variable, 285
storing in dictionaries, 544–554 pie chart, plotting, 418–420
13.1 Graphical User Interfaces 619
storing in lists, 538–540 pip utility, 705
13.2 Using the tkinter Module 621 StringVar, 636–637 Pixels, 34
13.3 Display Text with Label Widgets 624 unpickling, 543–544 plot() function, 406–407
13.4 Organizing Widgets with Frames 627 open function, 313, 314, 318 Polymorphism
13.5 Button Widgets and Info Dialog Boxes 630 Operands, 76 behavior, ingredients of, 588
13.6 Getting Input with the Entry Widget 633 Operating systems, 28 defined, 588
Operators isinstance function, 591–594
13.7 Using Labels as Output Fields 636
and, 156–158 popitem method, 473, 477
13.8 Radio Buttons and Check Buttons 644 in. See In operator pop method, 472, 720
13.9 Drawing Shapes with the Canvas Widget 651 addition (+), 76, 79, 90 Positional arguments, 257
Review Questions 673 assignment, 135, 203–204 Precedence, operator, 79
Programming Exercises 676 augmented assignment, 203–204 Predefined names colors, 695–699
exponent (**), 76, 80–82 Pretest loops
logical. See Logical operators defined, 186
math, 75–76 while loops as, 186–187
Index 733 10 Contents
Error handlers, 209 defined, 607–608 The new Turtle Graphics sections are designed with flexibility in mind. They can be
Error messages, 41, 44 recursive function calculation, 608–609 assigned as optional material, incorporated into your existing syllabus, or skipped
default, displaying, 355–356 Field widths
altogether.
loop displaying, 208–209 columns, 93
traceback, 349, 351 minimum, specifying, 93–94 ● Chapter 2 has a new section on named constants. Although Python does not support
Errors. See Exceptions File modes, 317 true constants, you can create variable names that symbolize values that should not
Error traps, 209 Filename extensions, 312
change as the program executes. This section teaches the student to avoid the use
Escape characters, 89–90 File objects
Event handlers, callback functions as, 630 close method, 315, 497 of “magic numbers,” and to create symbolic names that make his or her code more
Exception handling defined, 312 self-documenting and easier to maintain.
defined, 352 read method, 316–319 ● Chapter 7 has a new section on using the matplotlib package to plot charts and graphs
multiple exceptions, 352–355 variable name referencing, 312–314 from lists. The new section describes how to install the matplotlib package, and use it to
with try/except statement, 357–358 writelines method, 395–398
plot line graphs, bar charts, and pie charts.
Exception objects, 359 write method, 314
Exceptions finally clause, with try/except statement, 358
● Chapter 13 has a new section on creating graphics in a GUI application with the
catching all, with one except clause, 354–355 Finally suite, 358 Canvas widget. The new section describes how to use the Canvas widget to draw lines,
code response to, 348 find method, 446 rectangles, ovals, arcs, polygons, and text.
default error message display, 355–356 Flags, 162 ● Several new, more challenging, programming problems have been added throughout
defined, 75, 346 Flash drives, 28 the book.
IndexError, 368–369, 433 Flash memory, 28
IOError, 351–352, 354, 358 float data type, 69, 85–86
● Appendix E is a new appendix that discusses the various forms of the import statement.
KeyError, 463, 465, 487 float() function, 73, 74, 75, 86
● Appendix F is a new appendix that discusses installing third-party modules with the
multiple, 352–354 Floating-point division, 78, 79 pip utility.
unhandled, 358–359 Floating-point notation, 33
ValueError, 349–350, 354, 355, Floating-point numbers, 94
356, 358, 382 floor() function, 285 Brief Overview of Each Chapter
ZeroDivisionError, 358 Floppy disk drives, 27
Execution, 223 Flowchart, 56
in fetch-decode-execute cycle, 36 clock simulator, 213
Chapter 1: Introduction to Computers and Programming
pausing, 244 decision structure, 132, 133, 137 This chapter begins by giving a very concrete and easy-to-understand explanation of how
Python interpreter, 686–687 dual alternative decision structure, 130
computers work, how data is stored and manipulated, and why we write programs in high-
try/except statement, 349 input validation loop, 208
while loop, 209 logic for file end detection, 328 level languages. An introduction to Python, interactive mode, script mode, and the IDLE
Exercises nested decision structure, 149, 152 environment are also given.
decision structures, 173–179 pay calculating program, 57
dictionaries and sets, 507–510 program development cycle, 53
files and exceptions, 366–368 running total calculation, 201 Chapter 2: Input, Processing, and Output
functions, 302–308 sequence structure nested inside decision
This chapter introduces the program development cycle, variables, data types, and simple
GUI programming, 676–679 structure, 148
inheritance, 596–597 sequence structures with decision structure, 147–148 programs that are written as sequence structures. The student learns to write simple pro-
input, processing, and output, 126–130 while loop, 183 grams that read input from the keyboard, perform mathematical operations, and produce
introduction, 50–51 Font class, 670–672 screen output. Pseudocode and flowcharts are also introduced as tools for designing pro-
lists and tuples, 424–428 keyword arguments for, 671 grams. The chapter also includes an optional introduction to the turtle graphics library.
programming, 568–572 for loops. See also Loops
recursion, 616–617 as count-controlled loops, 190–200
repetition structures, 265–267 defined, 190–191 Chapter 3: Decision Structures and Boolean Logic
strings, 456–460 in turtle graphics, 219
exp() function, 285 iterating lists with, 368 In this chapter, the student learns about relational operators and Boolean expressions and is
Exponent (**) operator, 76, 80–82 iterating over dictionaries with, 468–469 shown how to control the flow of a program with decision structures. The if, if-else, and
iterating over list of strings with, 192 if-elif-else statements are covered. Nested decision structures and logical operators are
F iterating over sets, 488
discussed as well. The chapter also includes an optional turtle graphics section, with a discus-
Factorial function, 604–605 iterations, 198–200
Factorials iterations, user control, 198–200 sion of how to use decision structures to test the state of the turtle.
calculation with recursion, 602–606 range function with, 190–194
definition rules, 606, 609 target variables, 194–198
Fetch-decode-execute cycle, 36–37 format function, 91, 94
Chapter 4: Repetition Structures
Fibonacci series Format specifiers, 91–94 This chapter shows the student how to create repetition structures using the while loop and
for loop. Counters, accumulators, running totals, and sentinels are discussed, as well as
Preface 15 728 Index
techniques for writing input validation loops. The chapter also includes an optional section create_polygon method, 665–667 defined, 461
on using loops to draw designs with the turtle graphics library. optional arguments to, 667 elements, adding, 464
create_rectangle method, 655–657 elements, deleting, 465, 469
optional arguments to, 657 elements, display order, 462
Chapter 5: Functions create_text method, 667–672 elements, number of, 465–466
optional arguments to, 669 empty, creating, 467–468
In this chapter, the student first learns how to write and call void functions. The chapter C# programming language, 39 example, 474–477, 477–483
shows the benefits of using functions to modularize programs and discusses the top-down Customer class, 561–562 iteration, 468–469
design approach. Then, the student learns to pass arguments to functions. Common library keys, 461, 462
functions, such as those for generating random numbers, are discussed. After learning how D key-value pairs, 461, 464
Data methods, 469–474
to call library functions and use their return value, the student learns to define and call his mixing data types in, 466–467
appending to files, 322
or her own functions. Then the student learns how to use modules to organize functions. An binary file, 311 parts of, 461
optional section includes a discussion of modularizing turtle graphics code with functions. digital, 34 retrieving value from, 462–463
hiding, 512 storing objects in, 544–554
output, 87–95 values, 463–464
Chapter 6: Files and Exceptions processing, 333–346 Dictionary views
reading from files, 310–311, 316–319 defined, 470
This chapter introduces sequential file input and output. The student learns to read and write
text file, 311 elements, 470
large sets of data and store data as fields and records. The chapter concludes by discussing keys returned as, 471
writing to files, 310, 314–316
exceptions and shows the student how to write exception-handling code. Data attributes, 512 values returned as, 473–474
hidden, 513 dict() method, 468
hiding, 522–525 difference method, 490–491
Chapter 7: Lists and Tuples Digital data, 34
initializing, 518
This chapter introduces the student to the concept of a sequence in Python and explores the instance, 532–554 Digital devices, 34
Data storage, 29–33 Direct access files, 312, 343, 346
use of two common Python sequences: lists and tuples. The student learns to use lists for
characters, 33 Direct recursion, 606
arraylike operations, such as storing objects in a list, iterating over a list, searching for items music, 34 discard method, 487
in a list, and calculating the sum and average of items in a list. The chapter discusses slic- Data types Disk drives
ing and many of the list methods. One- and two-dimensional lists are covered. The chapter bool, 161 defined, 27
also includes a discussion of the matplotlib package, and how to use it to plot charts and conversion and mixed-type expressions, 85–86 program storage on, 36
graphs from lists. and literals, 68–69 Divide and conquer approach, 232
mixing, 466–467 Division
str, 69–70 floating-point, 78
Chapter 8: More About Strings Debugging, 54, 154 integer, 76, 78
global variables and, 258–259 / operator, 76, 78, 79
In this chapter, the student learns to process strings at a detailed level. String slicing and Decision structures, 132 Dog class, 589–590
algorithms that step through the individual characters in a string are discussed, and several actions performed in, 132–133 Dot notation, 263, 285
built-in functions and string methods for character and text processing are introduced. combining sequence structures with, 147–148 Dual alternative decision structure,
dual alternative, 140 139–140
in flowcharts, 132 dump method, 497
Chapter 9: Dictionaries and Sets if-elif-else statement, 153–154 DVD drives, 28
if-else statement, 140–143 DVDs (digital versatile discs), 28
This chapter introduces the dictionary and set data structures. The student learns to store data if statement, 131–139
as key-value pairs in dictionaries, search for values, change existing values, add new key-value inside, 148 E
pairs, and delete key-value pairs. The student learns to store values as unique elements in sets nested, 147–155 else clause, 143, 150
and perform common set operations such as union, intersection, di erence, and symmetric single alternative, 132 execution, 140
degrees() function, 285 with try/except statement, 357–358
di erence. The chapter concludes with a discussion of object serialization and introduces the
del statement, 383 else suite, 357
student to the Python pickle module. Depth of recursion, 602 Encapsulation, 512
Derived classes, 574 end–of–file, 500–501, 543
Chapter 10: Classes and Object-Oriented Programming Dialog boxes endswith method, 445, 446
defined, 619 ENIAC computer, 25, 26
This chapter compares procedural and object-oriented programming practices. It covers the illustrated, 620–621 Entry widget
fundamental concepts of classes and objects. Attributes, methods, encapsulation and data info, 630–633 defined, 622, 633
Dictionaries getting input with, 633–636
hiding, _ _init_ _ functions (which are similar to constructors), accessors, and mutators are
creating, 462 use example, 634–636
discussed. The student learns how to model classes with UML and how to find the classes
in a particular problem.
Index 727 16 Preface
VideoNotes Online videos developed specifically for this book are available
for viewing at www.pearsonglobaleditions.com/gaddis. Icons appear
throughout the text alerting the student to videos about specific
topics.
Notes Notes appear at several places throughout the text. They are
short explanations of interesting or often misunderstood points
relevant to the topic at hand.
Index Tips Tips advise the student on the best techniques for approaching
di erent programming problems.
Warnings Warnings caution students about programming techniques or
practices that can lead to malfunctioning programs or lost data.
Checkpoints Checkpoints are questions placed at intervals throughout each
chapter. They are designed to query the student’s knowledge
Symbols defined, 134 quickly after learning a new topic.
!= operator in string comparisons, 144
defined, 136 use example, 138 Review Questions Each chapter presents a thorough and diverse set of review
example use, 136, 138 > operator questions and exercises. They include Multiple Choice, True/
" (double-quote marks), 60 defined, 134 False, Algorithm Workbench, and Short Answer.
""" or "' (triple quotes), 60 in string comparisons, 146
# character, 61 use example, 134, 135–136 Programming Each chapter o ers a pool of programming exercises designed
% (remainder) operator >= operator Exercises to solidify the student’s knowledge of the topics currently being
defined, 76, 82 defined, 134 studied.
function of, 281 in superset determination, 492
%= operator, 203 relationship testing, 135
& operator, for intersection of sets, 490 >>> prompt, 43, 44
Supplements
' (single-quote marks), 59–60 ^ operator, 491
* operator _ _init_ _ method, 521, 555, 561, 563, 583 Student Online Resources
multiplication, 76 {}(curly braces), 462
Many student resources are available for this book from the publisher. The following items
repetition, 367
are available at www.pearsonglobaleditions.com/gaddis
** (exponent) operator, 76, 80–82 A
*= operator, 203 Accessor methods, 537 ● The source code for each example program in the book
+ operator acos(x) function, 285 ● Access to the book’s companion VideoNotes
defined, 76 Actions
displaying multiple items with, 90 conditionally executed, 132
in list concatenation, 371 in decision structures, 133 Instructor Resources
+= operator Ada programming language, 39
defined, 203
The following supplements are available to qualified instructors only:
Addition (+) operator
in list concatenation, 372 defined, 76 ● Answers to all of the Review Questions
in string concatenation, 435 displaying multiple items with, 90 ● Solutions for the exercises
− (subtraction) operator, 76 precedence, 79
_ _str_ _ method, 529–532 add method, 486
● PowerPoint presentation slides for each chapter
−= operator, 203 Algebraic expressions, 83–84 ● Test bank
/ (division) operator, 76, 78 Algorithms
// (integer division) operator, 76, 78 defined, 55 Visit the Pearson Instructor Resource Center (www.pearsonglobaleditions.com/gaddis) or
/= operator, 203 example, 55 contact your local Pearson campus representative for information on how to access them.
= operator recursive, 602, 603, 606–613
defined, 134 and operator
in subset determination, 492 defined, 156
relationship testing, 135 false, 158
= (assignment) operator, 135 short-circuit evaluation, 157
== operator truth table, 156
assignment operator versus, 136 Appending data, 322
725
Preface 19 724 Appendix G Answers to Checkpoints
I would like to thank the following faculty reviewers for their insight, expertise, and thought- 13.16 You would use check buttons.
ful recommendations: 13.17 When you create a group of Radiobuttons, you associate them all with
Sonya Dennis Anita Sutton the same IntVar object. You also assign a unique integer value to each
Morehouse College Germanna Community College Radiobutton widget. When one of the Radiobutton widgets is selected,
it stores its unique integer value in the IntVar object.
Diane Innes Christopher Urban
Sandhills Community College SUNY Institute of Technology 13.18 You associate a different IntVar object with each Checkbutton. When a
Checkbutton is selected, its associated IntVar object will hold the value 1.
John Kinuthia Nanette Veilleux When a Checkbutton is deselected, its associated IntVar object will hold the
Nazareth College of Rochester Simmons College value 0.
Frank Liu Brent Wilson 13.19 (0, 0)
Sam Houston State University George Fox University
13.20 (139, 479)
Haris Ribic
SUNY at Binghamton 13.21 With the Canvas widget, the point (0, 0) is in the upper-left corner of the
window. In turtle graphics, the point (0, 0) is in the center of the window.
Reviewers of Previous Editions Also, with the Canvas widget, the Y coordinates increase as you move down
Paul Amer Shyamal Mitra the screen. In turtle graphics, the Y coordinates decrease as you move down
University of Delaware University of Texas at Austin the screen.
Chapter 12 I would also like to thank my family and friends for their support in all of my projects.
I am extremely fortunate to have Matt Goldstein as my editor, and Kristy Alaura as edito-
12.1 A recursive algorithm requires multiple method calls. Each method call rial assistant. Their guidance and encouragement make it a pleasure to write chapters and
requires several actions to be performed by the JVM. These actions include meet deadlines. I am also fortunate to have Demetrius Hall as my marketing manager. His
allocating memory for parameters and local variables and storing the address hard work is truly inspiring, and he does a great job of getting this book out to the academic
of the program location where control returns after the method terminates. community. The production team, led by Sandra Rodriguez, worked tirelessly to make this
All these actions are known as overhead. In an iterative algorithm, which book a reality. Thanks to you all!
uses a loop, such overhead is unnecessary.
12.2 A case in which the problem can be solved without recursion Acknowledgments for the Global Edition
12.3 Cases in which the problem is solved using recursion Pearson would like to thank and acknowledge the following for their contributions to the
12.4 When it reaches the base case Global Edition.
12.5 In direct recursion, a recursive method calls itself. In indirect recursion, Contributor
method A calls method B, which in turn calls method A. Gregory Baatard, Edith Cowan University
Kenneth Eustace, Charles Sturt University
Chapter 13 Reviewers
Lindsay Ward, James Cook University
13.1 The part of a computer and its operating system with which the user
Ajay Mittal, University Institute of Engineering and Technology
interacts
Khyat Sharma
13.2 A command line interface typically displays a prompt, and the user types a
command, which is then executed. About the Author
13.3 The program Tony Gaddis is the principal author of the Starting Out with series of textbooks. Tony has
13.4 A program that responds to events that take place, such as the user clicking a nearly two decades of experience teaching computer science courses at Haywood Com-
button munity College. He is a highly acclaimed instructor who was previously selected as the
North Carolina Community College “Teacher of the Year” and has received the Teaching
13.5 a) Label—An area that displays one line of text or an image Excellence award from the National Institute for Sta and Organizational Development.
b) Entry—An area in which the user may type a single line of input from the The Starting Out with series includes introductory books covering C++, Java™, Microsoft®
keyboard Visual Basic®, Microsoft® C#®, Python®, Programming Logic and Design, Alice, and App
c) Button—A button that can cause an action to occur when it is clicked Inventor, all published by Pearson.
d) Frame—A container that can hold other widgets
13.6 You create an instance of the tkinter module’s Tk class.
13.7 This function runs like an infinite loop until you close the main window.
13.8 The pack method arranges a widget in its proper position, and it makes the
widget visible when the main window is displayed.
13.9 One will be stacked on top of the other.
13.10 side=–left—
13.11 You use an Entry widget’s get method to retrieve the data that the user has
typed into the widget.
13.12 It is a string.
13.13 tkinter
13.14 Any value that is stored in the StringVar object will automatically be
displayed in the Label widget.
722 Appendix G Answers to Checkpoints
Chapter 11
11.1 A superclass is a general class, and a subclass is a specialized class.
11.2 When one object is a specialized version of another object, there is an “is a”
relationship between them. The specialized object “is a” version of the
general object.
11.3 It inherits all the superclass’s attributes.
11.4 Bird is the superclass, and Canary is the subclass.
9.25 If the specified element to delete is not in the set, the remove method raises a
KeyError exception, but the discard method does not raise an exception.
9.26 You can use the in operator to test for the element.
9.27 {10, 20, 30, 100, 200, 300}
9.28 {3, 4}
9.29 {1, 2}
9.30 {5, 6}
9.33 The process of converting the object to a stream of bytes that can be saved to
a file for later retrieval.
9.34 'wb'
9.35 'rb'
9.38 pickle.load
Chapter 9
9.1 Key and value
9.2 The key
9.3 The string 'start' is the key, and the integer 1472 is the value.
Introduction to Computers
CHAPTE R
1
9.4 It stores the key-value pair 'id' : 54321 in the employee dictionary.
Computers can perform such a wide variety of tasks because they can be programmed. This 9.18 The set will contain one element: 25.
means that computers are not designed to do just one job, but to do any job that their pro-
9.19 The set will contain these elements (in no particular order): 'w', ' ', 'x',
grams tell them to do. A program is a set of instructions that a computer follows to perform
'y', and 'z'.
a task. For example, Figure 1-1 shows screens using Microsoft Word and PowerPoint, two
commonly used programs. 9.20 The set will contain these elements (in no particular order): 1, 2, 3, and 4.
Programs are commonly referred to as software. Software is essential to a computer because 9.21 The set will contain these elements (in no particular order): 'www', 'xxx',
it controls everything the computer does. All of the software that we use to make our com- 'yyy', and 'zzz'.
puters useful is created by individuals working as programmers or software developers. A
9.22 You pass the set as an argument to the len function.
programmer, or software developer, is a person with the training and skills necessary to
design, create, and test computer programs. Computer programming is an exciting and 9.23 The set will contain these elements (in no particular order): 10, 9, 8, 1, 2,
rewarding career. Today, you will find programmers’ work used in business, medicine, gov- and 3.
ernment, law enforcement, agriculture, academics, entertainment, and many other fields. 9.24 The set will contain these elements (in no particular order): 10, 9, 8, 'a',
This book introduces you to the fundamental concepts of computer programming using the 'b', and 'c'.
Python language. The Python language is a good choice for beginners because it is easy to learn
23
Appendix G Answers to Checkpoints 719 24 Chapter 1 Introduction to Computers and Programming
Then, each element in the list will become a slice in the pie chart. The size of Figure 1-1 A word processing program and an image editing program
a slice represents that element’s value as a percentage of the whole.
Chapter 8
8.1 for letter in name:
print(letter)
8.2 0
8.3 9
8.4 An IndexError exception will occur if you try to use an index that is out of
range for a particular string.
8.5 Use the built-in len function.
8.6 The second statement attempts to assign a value to an individual character
in the string. Strings are immutable, however, so the expression animal[0]
cannot appear on the left side of an assignment operator.
8.7 cde and programs can be written quickly using it. Python is also a powerful language, popular with
professional software developers. In fact, it has been reported that Python is used by Google,
8.8 defg NASA, YouTube, various game companies, the New York Stock Exchange, and many others.
8.9 abc Before we begin exploring the concepts of programming, you need to understand a few
8.10 abcdefg basic things about computers and how they work. This chapter will build a solid founda-
tion of knowledge that you will continually rely on as you study computer science. First,
8.11 if 'd' in mystring: we will discuss the physical components of which computers are commonly made. Next, we
print('Yes, it is there.')
will look at how computers store data and execute programs. Finally, you will get a quick
8.12 little = big.upper() introduction to the software that you will use to write Python programs.
8.13 if ch.isdigit():
print('Digit')
else: 1.2 Hardware and Software
print('No digit')
8.14 a A CONCEPT : The physical devices of which a computer is made are referred to as the
computer’s hardware. The programs that run on a computer are referred
8.15 again = input('Do you want to repeat ' + to as software.
'the program or quit? (R/Q) ')
while again.upper() != 'R' and again.upper() != 'Q': Hardware
again = input('Do you want to repeat the ' +
'program or quit? (R/Q) ') The term hardware refers to all of the physical devices, or components, of which a computer
is made. A computer is not one single device, but a system of devices that all work toge-
8.16 $ ther. Like the different instruments in a symphony orchestra, each device in a computer
8.17 for letter in mystring: plays its own part.
if letter.isupper(): If you have ever shopped for a computer, you’ve probably seen sales literature listing compo-
count += 1
nents such as microprocessors, memory, disk drives, video displays, graphics cards, and so on.
8.18 my_list = days.split() Unless you already know a lot about computers, or at least have a friend that does, under-
standing what these different components do might be challenging. As shown in Figure 1-2, a
8.19 my_list = values.split('$')
typical computer system consists of the following major components:
The central processing unit (CPU)
Main memory
1.2 Hardware and Software 25 718 Appendix G Answers to Checkpoints
Figure 1-2 Typical components of a computer system 7.17 You would use statement b, names.append('Wendy'). This is because
element 0 does not exist. If you try to use statement a, an error will occur.
7.18 a) The index method searches for an item in the list and returns the index of
the first element containing that item.
b) The insert method inserts an item into the list at a specified index.
Shutterstock
Central Processing c) The sort method sorts the items in the list to appear in ascending order.
Shutterstock
Unit
d) The reverse method reverses the order of the items in the list.
iko/Shutterstock
7.19 The list contains 4 rows and 2 columns.
Shutterstock
Feng Yu/Shutterstock
Output
Aquila/ Devices 7.20 mylist = [[0, 0, 0, 0], [0, 0, 0, 0],
[0, 0, 0, 0], [0, 0, 0, 0]]
Chiyacat/
Shutterstock 7.21 for r in range(4):
Peter Guess/
Shutterstock
for c in range(2):
Input
Devices
print(numbers[r][c])
jocic/Shutterstock
7.22 The primary difference between tuples and lists is that tuples are immutable.
Eikostas/Shutterstock
That means that once a tuple is created, it cannot be changed.
Main Memory
(RAM) 7.23 Here are three reasons:
Lusoimages/Shutterstock
Processing a tuple is faster than processing a list, so tuples are good
tkemot/Shutterstock Secondary
Storage Devices choices when you are processing lots of data and that data will not be
modified.
Tuples are safe. Because you are not allowed to change the contents of a
tuple, you can store data in one and rest assured that it will not be modified
(accidentally or otherwise) by any code in your program.
There are certain operations in Python that require the use of a tuple.
Vitaly Korovin/Shutterstock Andre Nitsievsky/Shutterstock.
7.24 my_tuple = tuple(my_list)
Secondary storage devices 7.25 my_list = list(my_tuple)
Input devices
Output devices 7.26 Two lists: one holding the X coordinates of the data points, and the other
holding the Y coordinates.
Let’s take a closer look at each of these components.
7.27 A line graph
The CPU 7.28 Use the xlabel and ylabel functions.
When a computer is performing the tasks that a program tells it to do, we say that the 7.29 Call the xlim and ylim functions, passing values for the xmin, xmax, ymin,
computer is running or executing the program. The central processing unit, or CPU, is the and ymax keyword arguments.
part of a computer that actually runs programs. The CPU is the most important component
7.30 Call the xticks and yticks functions. You pass two arguments to these
in a computer because without it, the computer could not run software.
functions. The first argument is a list of tick-mark locations, and the second
In the earliest computers, CPUs were huge devices made of electrical and mechanical com- argument is a list of labels to display at the specified locations.
ponents such as vacuum tubes and switches. Figure 1-3 shows such a device. The two
7.31 Two lists: one containing the X coordinates of each bar’s left edge, and
women in the photo are working with the historic ENIAC computer. The ENIAC, which
another containing the heights of each bar, along the Y axis.
is considered by many to be the world’s first programmable electronic computer, was built
in 1945 to calculate artillery ballistic tables for the U.S. Army. This machine, which was 7.32 The bars will be red, blue, red, and blue.
primarily one big CPU, was 8 feet tall, 100 feet long, and weighed 30 tons. 7.33 You pass a list of values as an argument. The pie function will calculate
Today, CPUs are small chips known as microprocessors. Figure 1-4 shows a photo of a lab the sum of the values in the list, then use that sum as the value of the whole.
technician holding a modern microprocessor. In addition to being much smaller than the old
electromechanical CPUs in early computers, microprocessors are also much more powerful.
Appendix G Answers to Checkpoints 717 26 Chapter 1 Introduction to Computers and Programming
6.18 You copy all the original file’s records to the temporary file, except for the Figure 1-3 The ENIAC computer
record that is to be deleted. The temporary file then takes the place of the
original file. You delete the original file and rename the temporary file, giving
it the name that the original file had on the computer’s disk.
6.19 An exception is an error that occurs while a program is running. In most
cases, an exception causes a program to abruptly halt.
6.20 The program halts.
6.21 IOError
6.22 ValueError
Chapter 7
7.1 [1, 2, 99, 4, 5]
7.2 [0, 1, 2]
7.4 1
courtesy of U.S. Army Historic Computer Images
3
5
7
9
Figure 1-4 A lab technician holds a modern microprocessor
7.5 4
7.8 [1, 2, 3]
[10, 20, 30, 1, 2, 3]
7.9 [2, 3]
7.10 [2, 3]
7.11 [1]
7.12 [1, 2, 3, 4, 5]
7.13 [3, 4, 5]
7.15 The remove method searches for and removes an element containing a
Creativa/Shutterstock
specific value. The del statement removes an element at a specific index.
7.16 You can use the built-in min and max functions.
1.2 Hardware and Software 27 716 Appendix G Answers to Checkpoints
Main Memory has not been converted to text. As a consequence, you cannot view the con-
tents of a binary file with a text editor.
You can think of main memory as the computer’s work area. This is where the computer
stores a program while the program is running, as well as the data that the program is 6.5 Sequential and direct access. When you work with a sequential access file,
working with. For example, suppose you are using a word processing program to write an you access data from the beginning of the file to the end of the file. When
essay for one of your classes. While you do this, both the word processing program and the you work with a direct access file, you can jump directly to any piece of data
essay are stored in main memory. in the file without reading the data that comes before it.
Main memory is commonly known as random-access memory, or RAM. It is called this 6.6 The file’s name on the disk and the name of a variable that references a file
because the CPU is able to quickly access data stored at any random location in RAM. object.
RAM is usually a volatile type of memory that is used only for temporary storage while
6.7 The file’s contents are erased.
a program is running. When the computer is turned off, the contents of RAM are erased.
Inside your computer, RAM is stored in chips, similar to the ones shown in Figure 1-5. 6.8 Opening a file creates a connection between the file and the program. It also
creates an association between the file and a file object.
6.9 Closing a file disconnects the program from the file.
Figure 1-5 Memory chips
6.10 A file’s read position marks the location of the next item that will be read
from the file. When an input file is opened, its read position is initially set to
the first item in the file.
6.11 You open the file in append mode. When you write data to a file in append
mode, the data is written to the end of the file’s existing contents.
Garsya/Shutterstock 6.12 outfile = open('numbers.txt', 'w')
for num in range(1, 11):
outfile.write(str(num) + '\n')
outfile.close()
Secondary Storage Devices
6.13 The readline method returns an empty string ('') when it has attempted to
Secondary storage is a type of memory that can hold data for long periods of time, even
read beyond the end of a file.
when there is no power to the computer. Programs are normally stored in secondary mem-
ory and loaded into main memory as needed. Important data, such as word processing 6.14 infile = open('numbers.txt', 'r')
documents, payroll data, and inventory records, is saved to secondary storage as well. line = infile.readline()
while line != '':
The most common type of secondary storage device is the disk drive. A traditional disk
print(line)
drive stores data by magnetically encoding it onto a spinning circular disk. Solid-state
line = infile.readline()
drives, which store data in solid-state memory, are increasingly becoming popular. A solid-
state drive has no moving parts and operates faster than a traditional disk drive. Most in le.close()
computers have some sort of secondary storage device, either a traditional disk drive or a 6.15 infile = open('data.txt', 'r')
solid-state drive, mounted inside their case. External storage devices, which connect to one for line in infile:
of the computer’s communication ports, are also available. External storage devices can print(line)
be used to create backup copies of important data or to move data to another computer. infile.close()
In addition to external storage devices, many types of devices have been created for copy- 6.16 A record is a complete set of data that describes one item, and a field is a
ing data and for moving it to other computers. For example, USB drives are small devices single piece of data within a record.
that plug into the computer’s USB (universal serial bus) port and appear to the system as
a disk drive. These drives do not actually contain a disk, however. They store data in a 6.17 You copy all the original file's records to the temporary file, but when you
special type of memory known as flash memory. USB drives, which are also known as get to the record that is to be modified, you do not write its old contents
memory sticks and flash drives, are inexpensive, reliable, and small enough to be carried to the temporary file. Instead, you write its new, modified values to the
in your pocket. temporary file. Then, you finish copying any remaining records from the
original file to the temporary file.
Appendix G Answers to Checkpoints 715 28 Chapter 1 Introduction to Computers and Programming
be changed during the program’s execution, you do not have to worry about Optical devices such as the CD (compact disc) and the DVD (digital versatile disc) are
its value being altered. also popular for data storage. Data is not recorded magnetically on an optical disc, but is
encoded as a series of pits on the disc surface. CD and DVD drives use a laser to detect
5.21 The difference is that a value returning function returns a value back to the
the pits and thus read the encoded data. Optical discs hold large amounts of data, and
statement that called it. A simple function does not return a value.
for that reason, recordable CD and DVD drives are commonly used for creating backup
5.22 A prewritten function that performs some commonly needed task copies of data.
5.23 The term “black box” is used to describe any mechanism that accepts input,
performs some operation (that cannot be seen) using the input, and produces Input Devices
output.
Input is any data the computer collects from people and from other devices. The compo-
5.24 It assigns a random integer in the range of 1 through 100 to the variable x. nent that collects the data and sends it to the computer is called an input device. Common
5.25 It prints a random integer in the range of 1 through 20. input devices are the keyboard, mouse, touchscreen, scanner, microphone, and digital cam-
era. Disk drives and optical drives can also be considered input devices, because programs
5.26 It prints a random integer in the range of 10 through 19. and data are retrieved from them and loaded into the computer’s memory.
5.27 It prints a random floating-point number in the range of 0.0 up to, but not
including, 1.0.
Output Devices
5.28 It prints a random floating-point number in the range of 0.1 through 0.5.
Output is any data the computer produces for people or for other devices. It might be
5.29 It uses the system time, retrieved from the computer’s internal clock. a sales report, a list of names, or a graphic image. The data is sent to an output device,
5.30 If the same seed value were always used, the random number functions which formats and presents it. Common output devices are video displays and printers.
would always generate the same series of pseudorandom numbers. Disk drives can also be considered output devices because the system sends data to them
in order to be saved.
5.31 It returns a value back to the part of the program that called it.
Software Development Tools Software development tools are the programs that pro- 5.5 When a program is developed as a set of functions in which each performs
grammers use to create, modify, and test software. Assemblers, compilers, and interpret- an individual task, then different programmers can be assigned the job of
ers are examples of programs that fall into this category. writing different functions.
5.6 A function definition has two parts: a header and a block. The header
Application Software indicates the starting point of the function, and the block is a list of
statements that belong to the function.
Programs that make a computer useful for everyday tasks are known as application soft-
ware. These are the programs that people normally spend most of their time running on 5.7 To call a function means to execute the function.
their computers. Figure 1-1, at the beginning of this chapter, shows screens from two com- 5.8 When the end of the function is reached, the computer returns back to the
monly used applications: Microsoft Word, a word processing program, and PowerPoint, a part of the program that called the function, and the program resumes
presentation program. Some other examples of application software are spreadsheet pro- execution at that point.
grams, email programs, web browsers, and game programs.
5.9 Because the Python interpreter uses the indentation to determine where a
block begins and ends
Checkpoint
5.10 A local variable is a variable that is declared inside a function. It belongs to
1.1 What is a program?
the function in which it is declared, and only statements in the same function
1.2 What is hardware? can access it.
1.3 List the five major components of a computer system.
5.11 The part of a program in which a variable may be accessed
1.4 What part of the computer actually runs programs?
5.12 Yes, it is permissible.
1.5 What part of the computer serves as a work area to store a program and its data
while the program is running? 5.13 Arguments
1.6 What part of the computer holds data for long periods of time, even when there is 5.14 Parameters
no power to the computer?
5.15 A parameter variable’s scope is the entire function in which the parameter is
1.7 What part of the computer collects data from people and from other devices?
declared.
1.8 What part of the computer formats and presents data for people or other devices?
5.16 No, it does not.
1.9 What fundamental set of programs control the internal operations of the
computer’s hardware? 5.17 a. passes by keyword argument
1.10 What do you call a program that performs a specialized task, such as a virus b. passes by position
scanner, a file compression program, or a data backup program? 5.18 The entire program
1.11 Word processing programs, spreadsheet programs, email programs, web browsers,
5.19 Here are three:
and game programs belong to what category of software?
Global variables make debugging difficult. Any statement in a program can
change the value of a global variable. If you find that the wrong value is being
stored in a global variable, you have to track down every statement that
1.3 How Computers Store Data accesses it to determine where the bad value is coming from. In a program
with thousands of lines of code, this can be difficult.
CONCEPT: All data that is stored in a computer is converted to sequences of 0s Functions that use global variables are usually dependent on those variables.
and 1s. If you want to use such a function in a different program, you will most likely
have to redesign it so it does not rely on the global variable.
A computer’s memory is divided into tiny storage locations known as bytes. One byte is Global variables make a program hard to understand. A global variable
only enough memory to store a letter of the alphabet or a small number. In order to do can be modified by any statement in the program. If you are to understand
anything meaningful, a computer has to have lots of bytes. Most computers today have any part of the program that uses a global variable, you have to be aware
millions, or even billions, of bytes of memory. of all the other parts of the program that access the global variable.
Each byte is divided into eight smaller storage locations known as bits. The term bit stands 5.20 A global constant is a name that is available to every function in the
for binary digit. Computer scientists usually think of bits as tiny switches that can be either program. It is permissible to use global constants. Because their value cannot
Appendix G Answers to Checkpoints 713 30 Chapter 1 Introduction to Computers and Programming
4.13 A variable that is used to accumulate the total of a series of numbers on or off. Bits aren’t actual “switches,” however, at least not in the conventional sense. In
most computer systems, bits are tiny electrical components that can hold either a positive
4.14 Yes, it should be initialized with the value 0. This is because values are added
or a negative charge. Computer scientists think of a positive charge as a switch in the on
to the accumulator by a loop. If the accumulator does not start at the value 0,
position, and a negative charge as a switch in the off position. Figure 1-6 shows the way
it will not contain the correct total of the numbers that were added to it when
that a computer scientist might think of a byte of memory: as a collection of switches that
the loop ends.
are each flipped to either the on or off position.
4.15 15
4.16 15
Figure 1-6 Think of a byte as eight switches
5
4.17 a) quantity += 1 ON ON ON ON
b) days_left −= 5
c) price *= 10
d) price /= 2
4.18 A sentinel is a special value that marks the end of a list of items.
4.19 A sentinel value must be unique enough that it will not be mistaken as a OFF OFF OFF OFF
regular value in the list.
4.20 It means that if bad data (garbage) is provided as input to a program, the
program will produce bad data (garbage) as output. When a piece of data is stored in a byte, the computer sets the eight bits to an on/off
4.21 When input is given to a program, it should be inspected before it is pattern that represents the data. For example, the pattern on the left in Figure 1-7 shows
processed. If the input is invalid, then it should be discarded and the user how the number 77 would be stored in a byte, and the pattern on the right shows how the
should be prompted to enter the correct data. letter A would be stored in a byte. We explain below how these patterns are determined.
4.22 The input is read, then a pretest loop is executed. If the input data is invalid,
the body of the loop executes. In the body of the loop, an error message is Figure 1-7 Bit patterns for the number 77 and the letter A
displayed so the user will know that the input was invalid, and then the
input read again. The loop repeats as long as the input is invalid. ON ON ON ON ON ON
4.23 It is the input operation that takes place just before an input validation loop.
The purpose of the priming read is to get the first input value.
4.24 None OFF
OFF OFF OFF OFF OFF OFF OFF OFF OFF
The position of each digit in a binary number has a value assigned to it. Starting with 3.26 You use the turtle.pencolor() function to determine the pen color.
the rightmost digit and moving left, the position values are 20, 21, 22, 23, and so forth, as You use the turtle.fillcolor() function to determine the current fill
shown in Figure 1-8. Figure 1-9 shows the same diagram with the position values calcu- color. You use the turtle.bgcolor() function to determine the current
lated. Starting with the rightmost digit and moving left, the position values are 1, 2, 4, 8, background color of the turtle’s graphics window.
and so forth.
3.27 You use the turtle.pensize() function.
3.28 You use the turtle.speed() function.
Figure 1-8 The values of binary digits as powers of 2
10011101 Chapter 4
0 4.1 A structure that causes a section of code to repeat
2
21 4.2 A loop that uses a true/false condition to control the number of times that it
22
23 repeats
24
25 4.3 A loop that repeats a specific number of times
26
27 4.4 An execution of the statements in the body of the loop
4.5 Before
Figure 1-9 The values of binary digits 4.6 None. The condition count < 0 will be false to begin with.
4.7 A loop that has no way of stopping and repeats until the program is
10011101 interrupted.
1 4.8 for x in range(6):
2
4 print('I love to program!')
8
16 4.9 0
32 1
64
128
2
3
4
5
To determine the value of a binary number, you simply add up the position values of all the
1s. For example, in the binary number 10011101, the position values of the 1s are 1, 4, 8, 4.10 2
16, and 128. This is shown in Figure 1-10. The sum of all of these position values is 157. 3
So, the value of the binary number 10011101 is 157. 4
5
3.13 if number == 1: Figure 1-11 shows how you can picture the number 157 stored in a byte of memory. Each
print('One') 1 is represented by a bit in the on position, and each 0 is represented by a bit in the off
elif number == 2: position.
print('Two')
elif number == 3:
print('Three') Figure 1-11 The bit pattern for 157
else:
print('Unknown')
Any piece of data that is stored in a computer’s memory must be stored as a binary num- 2.39 turtle.setup(500, 200)
ber. That includes characters, such as letters and punctuation marks. When a character is 2.40 turtle.goto(100, 50)
stored in memory, it is first converted to a numeric code. The numeric code is then stored
in memory as a binary number. 2.41 turtle.pos()
Over the years, different coding schemes have been developed to represent characters in 2.42 turtle.speed(10)
computer memory. Historically, the most important of these coding schemes is ASCII, 2.43 turtle.speed(0)
which stands for the American Standard Code for Information Interchange. ASCII is a set
of 128 numeric codes that represent the English letters, various punctuation marks, and 2.44 To fill a shape with a color, you use the turtle.begin_fill() command
other characters. For example, the ASCII code for the uppercase letter A is 65. When you before drawing the shape, then you use the turtle.end_fill() command
type an uppercase A on your computer keyboard, the number 65 is stored in memory (as after the shape is drawn. When the turtle.end_fill() command executes,
a binary number, of course). This is shown in Figure 1-13. the shape will be filled with the current fill color.
2.45 With the turtle.write()command
Figure 1-13 The letter A is stored in memory as the number 65
Chapter 3
1 1
A
3.1 A logical design that controls the order in which a set of statements execute
65 3.2 It is a program structure that can execute a set of statements only under
0 0 0 0 0 0
certain circumstances.
3.3 A decision structure that provides a single alternative path of execution.
If the condition that is being tested is true, the program takes the alternative
TIP : The acronym ASCII is pronounced “askee.” path.
3.4 An expression that can be evaluated as either true or false
In case you are curious, the ASCII code for uppercase B is 66, for uppercase C is 67, and so 3.5 You can determine whether one value is greater than, less than, greater than
forth. Appendix C shows all of the ASCII codes and the characters they represent. or equal to, less than or equal to, equal to, or not equal to another value.
The ASCII character set was developed in the early 1960s and was eventually adopted by 3.6 if y == 20:
almost all computer manufacturers. ASCII is limited, however, because it defines codes for x = 0
only 128 characters. To remedy this, the Unicode character set was developed in the early 3.7 if sales >= 10000:
1990s. Unicode is an extensive encoding scheme that is compatible with ASCII, but can commissionRate = 0.2
also represent characters for many of the languages in the world. Today, Unicode is quickly
becoming the standard character set used in the computer industry. 3.8 A dual alternative decision structure has two possible paths of execution;
one path is taken if a condition is true, and the other path is taken if the
condition is false.
Advanced Number Storage 3.9 if-else
Earlier, you read about numbers and how they are stored in memory. While reading that 3.10 When the condition is false
section, perhaps it occurred to you that the binary numbering system can be used to repre-
sent only integer numbers, beginning with 0. Negative numbers and real numbers (such as 3.11 z is not less than a.
3.14159) cannot be represented using the simple binary numbering technique we discussed. 3.12 Boston
Computers are able to store negative numbers and real numbers in memory, but to do so New York
they use encoding schemes along with the binary numbering system. Negative numbers are
encoded using a technique known as two’s complement, and real numbers are encoded in
floating-point notation. You don’t need to know how these encoding schemes work, only
that they are used to convert negative numbers and real numbers to binary format.
Appendix G Answers to Checkpoints 709 34 Chapter 1 Introduction to Computers and Programming
01
0
2.20 4
00
10
101
101
2.21 1
2.22 If you do not want the print function to start a new line of output when it
finishes displaying its output, you can pass the special argument end = ' '
to the function.
The music that you play on your CD player, iPod, or MP3 player is also digital. A digital
2.23 You can pass the argument sep= to the print function, specifying the song is broken into small pieces known as samples. Each sample is converted to a binary
desired character. number, which can be stored in memory. The more samples that a song is divided into, the
2.24 It is the newline escape character. more it sounds like the original music when it is played back. A CD quality song is divided
into more than 44,000 samples per second!
2.25 It is the string concatenation operator, which joins two strings together.
2.26 65.43 Checkpoint
2.27 987,654.13 1.12 What amount of memory is enough to store a letter of the alphabet or a small
number?
2.28 (1) Named constants make programs more self-explanatory, (2) widespread
changes can easily be made to the program, and (3) they help to prevent the 1.13 What do you call a tiny “switch” that can be set to either on or off?
typographical errors that are common when using magic numbers. 1.14 In what numbering system are all numeric values written as sequences of 0s and 1s?
2.35 turtle.circle(100) CONCEPT : A computer’s CPU can only understand instructions that are written in
machine language. Because people find it very difficult to write entire
2.36 turtle.pensize(8)
programs in machine language, other programming languages have been
2.37 turtle.pencolor('blue') invented.
1.4 How a Program Works 35 708 Appendix G Answers to Checkpoints
Earlier, we stated that the CPU is the most important component in a computer because it is 1.18 Machine language
the part of the computer that runs programs. Sometimes the CPU is called the “computer’s
1.19 Main memory, or RAM
brain” and is described as being “smart.” Although these are common metaphors, you
should understand that the CPU is not a brain, and it is not smart. The CPU is an electronic 1.20 The fetch-decode-execute cycle
device that is designed to do specific things. In particular, the CPU is designed to perform
1.21 It is an alternative to machine language. Instead of using binary numbers
operations such as the following:
for instructions, assembly language uses short words that are known as
Reading a piece of data from main memory mnemonics.
Adding two numbers
1.22 A high-level language
Subtracting one number from another number
Multiplying two numbers 1.23 Syntax
Dividing one number by another number
1.24 A compiler
Moving a piece of data from one memory location to another
Determining whether one value is equal to another value 1.25 An interpreter
As you can see from this list, the CPU performs simple operations on pieces of data. The 1.26 A syntax error
CPU does nothing on its own, however. It has to be told what to do, and that’s the purpose
of a program. A program is nothing more than a list of instructions that cause the CPU to
perform operations. Chapter 2
Each instruction in a program is a command that tells the CPU to perform a specific opera- 2.1 Any person, group, or organization that is asking you to write a program
tion. Here’s an example of an instruction that might appear in a program: 2.2 A single function that the program must perform in order to satisfy the
10110000 customer
To you and me, this is only a series of 0s and 1s. To a CPU, however, this is an instruction 2.3 A set of well-defined logical steps that must be taken to perform a task
to perform an operation.1 It is written in 0s and 1s because CPUs only understand instruc- 2.4 An informal language that has no syntax rules and is not meant to be
tions that are written in machine language, and machine language instructions always have compiled or executed. Instead, programmers use pseudocode to create
an underlying binary structure. models, or “mock-ups,” of programs.
A machine language instruction exists for each operation that a CPU is capable of perform- 2.5 A diagram that graphically depicts the steps that take place in a program
ing. For example, there is an instruction for adding numbers, there is an instruction for
subtracting one number from another, and so forth. The entire set of instructions that a 2.6 Ovals are terminal symbols. Parallelograms are either output or input
CPU can execute is known as the CPU’s instruction set. symbols. Rectangles are processing symbols.
2.7 print('Jimmy Smith')
The machine language instruction that was previously shown is an example of only one
instruction. It takes a lot more than one instruction, however, for the computer to do any-
thing meaningful. Because the operations that a CPU knows how to perform are so basic in
nature, a meaningful task can be accomplished only if the CPU performs many operations.
For example, if you want your computer to calculate the amount of interest that you will
APP ENDIX
earn from your savings account this year, the CPU will have to perform a large number of
G
instructions, carried out in the proper sequence. It is not unusual for a program to contain
Answers to Checkpoints thousands or even millions of machine language instructions.
Programs are usually stored on a secondary storage device such as a disk drive. When you
install a program on your computer, the program is typically copied to your computer’s disk
drive from a CD-ROM, or downloaded from a website.
Although a program can be stored on a secondary storage device such as a disk drive,
it has to be copied into main memory, or RAM, each time the CPU executes it. For
example, suppose you have a word processing program on your computer’s disk. To
execute the program, you use the mouse to double-click the program’s icon. This causes
Chapter 1
the program to be copied from the disk into main memory. Then, the computer’s CPU
1.1 A program is a set of instructions that a computer follows to perform a task. executes the copy of the program that is in main memory. This process is illustrated in
1.2 Hardware is all the physical devices, or components, of which a computer is Figure 1-15.
made.
1.3 The central processing unit (CPU), main memory, secondary storage devices, Figure 1-15 A program is copied into main memory and then executed
input devices, and output devices
The program is copied
1.4 The CPU The CPU executes
from secondary storage
the program in
to main memory.
1.5 Main memory main memory.
Main memory
1.6 Secondary storage (RAM)
1.7 Input device
1.8 Output device
1.9 The operating system Disk drive CPU
707
1.4 How a Program Works 37
10100001
Fetch the next instruction
1
in the program.
10100001
10111000 Decode the instruction
10011110 2 to determine which
00011010 operation to perform.
11011100
and so forth... CPU
Execute the instruction
3
(perform the operation).
Main memory
(RAM)
N OTE : There are many different versions of assembly language. It was mentioned
earlier that each brand of CPU has its own machine language instruction set. Each
brand of CPU typically has its own assembly language as well.
Assembly language programs cannot be executed by the CPU, however. The CPU only
understands machine language, so a special program known as an assembler is used to
translate an assembly language program to a machine language program. This process is
shown in Figure 1-17. The machine language program that is created by the assembler can
then be executed by the CPU.
2
The first assembly language was most likely that developed in the 1940s at Cambridge University
for use with a historic computer known as the EDSAC.
38 Chapter 1 Introduction to Computers and Programming
F
mov eax, Z 10100001
add eax, 2
mov Y, eax 10111000
High-Level Languages
Although assembly language makes it unnecessary to write binary machine language instruc-
The Python standard library provides classes and functions that your programs can use to tions, it is not without difficulties. Assembly language is primarily a direct substitute for
perform basic operations, as well as many advanced tasks. There are operations, however, machine language, and like machine language, it requires that you know a lot about the
that the standard library cannot perform. When you need to do something that is beyond CPU. Assembly language also requires that you write a large number of instructions for even
the scope of the standard library, you have two choices: write the code yourself, or use code the simplest program. Because assembly language is so close in nature to machine language,
that someone else has already written. it is referred to as a low-level language.
Fortunately, there are thousands of Python modules, written by independent programmers, In the 1950s, a new generation of programming languages known as high-level languages
that provide capabilities that the standard Python library does not offer. These are known began to appear. A high-level language allows you to create powerful and complex pro-
as third-party modules. A large collection of third-party modules exists at the website pypi. grams without knowing how the CPU works and without writing large numbers of low-level
python.org, which is known as the Python Package Index, or PyPI. instructions. In addition, most high-level languages use words that are easy to understand.
For example, if a programmer were using COBOL (which was one of the early high-level
The modules that are available at PyPI are organized as packages. A package is simply a coll- languages created in the 1950s), he or she would write the following instruction to display
ection of one or more related modules. The easiest way to download and install a package the message Hello world on the computer screen:
is with the pip utility. The pip utility is a program that is part of the standard Python
installation, beginning with Python 3.4. To install a package on a Windows system with DISPLAY "Hello world"
the pip utility, you must open a command prompt window, and type a command following Python is a modern, high-level programming language that we will use in this book. In
this format: Python you would display the message Hello world with the following instruction:
pip install package_name print('Hello world')
package_name is the name of a package that you want to download and install. If you are
Doing the same thing in assembly language would require several instructions and an inti-
running a Mac or a Linux system, you must use the pip3 command instead of the pip com-
mate knowledge of how the CPU interacts with the computer’s output device. As you can see
mand. In addition, you will need superuser privileges to execute the pip3 command on a
from this example, high-level languages allow programmers to concentrate on the tasks they
Mac or Linux system, so you will have to prefix the command with sudo, as shown here: want to perform with their programs, rather than the details of how the CPU will execute
sudo pip3 install package_name those programs.
Once you enter the command, the pip utility will start downloading and installing the Since the 1950s, thousands of high-level languages have been created. Table 1-1 lists several
package. Depending on the size of the package, it may take a few minutes to complete the of the more well-known languages.
installation process. Once the process is finished, you can typically verify that the package
was correctly installed by starting IDLE and entering the command
Key Words, Operators, and Syntax: An Overview
>>> import package_name
Each high-level language has its own set of predefined words that the programmer must
where package_name is the name of the package that you installed. If you do not see an use to write a program. The words that make up a high-level programming language are
error message, you can assume the package was successfully installed. known as key words or reserved words. Each key word has a specific meaning, and cannot
In Chapter 7, you will explore a popular third-party package named matplotlib. You can be used for any other purpose. Table 1-2 shows all of the Python key words.
use the matplotlib package to create charts and graphs.
705
1.4 How a Program Works 39
Using an Alias In addition to key words, programming languages have operators that perform various
operations on data. For example, all programming languages have math operators that
You can use the as keyword to assign an alias to a module when you import it. The follow- perform arithmetic. In Python, as well as most other languages, the + sign is an operator
ing statement shows an example: that adds two numbers. The following adds 12 and 75:
import math as mt 12 + 75
This statement loads the math module into memory, assigning the module the alias mt. There are numerous other operators in the Python language, many of which you will learn
To use any of the items that are in the module, you prefix the item’s name with the alias, about as you progress through this text.
followed by a dot. For example, to call the sqrt function, you would use the name
mt.sqrt. The following interactive session shows an example: In addition to key words and operators, each language also has its own syntax, which is a
set of rules that must be strictly followed when writing a program. The syntax rules dictate
>>> import math as mt how key words, operators, and various punctuation characters must be used in a program.
>>> x = mt.sqrt(25) When you are learning a programming language, you must learn the syntax rules for that
>>> a = mt.radians(180) particular language.
>>> print(x)
5.0 The individual instructions that you use to write a program in a high-level programming
>>> print(a) language are called statements. A programming statement can consist of key words, oper-
3.141592653589793 ators, punctuation, and other allowable programming elements, arranged in the proper
>>> sequence to perform an operation.
You can also assign an alias to a specific function or class when you import it. The follow-
ing statement imports the sqrt function from the math module, and assigns the function Compilers and Interpreters
the alias square_root:
Because the CPU understands only machine language instructions, programs that are writ-
from math import sqrt as square_root ten in a high-level language must be translated into machine language. Depending on the
language in which a program has been written, the programmer will use either a compiler
After using this import statement, you would use the name square_root to call the sqrt
or an interpreter to make the translation.
function. The following interactive session shows an example:
A compiler is a program that translates a high-level language program into a separate
>>> from math import sqrt as square_root
machine language program. The machine language program can then be executed any time
>>> x = square_root(25)
it is needed. This is shown in Figure 1-18. As shown in the figure, compiling and executing
>>> print(x)
are two different processes.
5.0
>>> Figure 1-18 Compiling a high-level program and executing it
In the following interactive session, we import two functions from the math module, giving
High-level language Machine language
each of them an alias. The sqrt function is imported as square_root, and the tan func- program
program
tion is imported as tangent:
The compiler is used 10100001
print ("Hello
>>> from math import sqrt as square_root, tan as tangent 1 to translate the high-level Earthling") 10111000
language program to a Compiler
>>> x = square_root(25) 10011110
machine language program. and so forth... and so forth...
>>> y = tangent(45)
>>> print(x)
5.0
>>> print(y)
1.6197751905438615
Machine language
CPU
program
The machine language 10100001
2 program can be executed 10111000
at any time, without using 10011110
the compiler. and so forth...
1.4 How a Program Works 41 702 Appendix E More About the import Statement
The Python language uses an interpreter, which is a program that both translates and This statement causes only the sqrt function to be imported from the math module. It also
executes the instructions in a high-level language program. As the interpreter reads allows you to call the sqrt function without prefixing the function’s name with the name
each individual instruction in the program, it converts it to machine language instruc- of the module. The following interactive session shows an example:
tions then immediately executes them. This process repeats for every instruction in
>>> from math import sqrt
the program. This process is illustrated in Figure 1-19. Because interpreters combine
>>> x = sqrt(25)
translation and execution, they typically do not create separate machine language
>>> print(x)
programs.
5.0
>>>
Figure 1-19 Executing a high-level program with an interpreter You can specify the names of multiple items, separated with commas, when you use this
form of the import statement. For example, the import statement in the following interac-
High-level language tive session imports only the sqrt function and the radians function from the math
program CPU module:
Machine language
print ("Hello instruction
>>> from math import sqrt, radians
Earthling") Interpreter 10100001
>>> x = sqrt(25)
and so forth... >>> a = radians(180)
>>> print(x)
5.0
The interpreter translates each high-level instruction to
>>> print(a)
its equivalent machine language instructions then 3.141592653589793
immediately executes them. >>>
This process is repeated for each high-level instruction.
Wildcard Imports
The statements that a programmer writes in a high-level language are called source A wildcard import statement loads the entire contents of a module. Here is an example:
code, or simply code. Typically, the programmer types a program’s code into a text
editor then saves the code in a file on the computer’s disk. Next, the programmer uses from math import *
a compiler to translate the code into a machine language program, or an interpreter to The difference between this statement and the import math statement is that the wildcard
translate and execute the code. If the code contains a syntax error, however, it cannot import statement does not require you to use the qualified names of the items in the mod-
be translated. A syntax error is a mistake such as a misspelled key word, a missing ule. For example, here is an interactive session that uses a wildcard import statement:
punctuation character, or the incorrect use of an operator. When this happens, the
compiler or interpreter displays an error message indicating that the program contains >>> from math import*
a syntax error. The programmer corrects the error then attempts once again to translate >>> x = sqrt(25)
the program. >>> a = radians(180)
>>>
And, here is an interactive session that uses the regular import statement:
N OTE : Human languages also have syntax rules. Do you remember when you took >>> import math
your first English class, and you learned all those rules about commas, apostrophes, >>> x = math.sqrt(25)
capitalization, and so forth? You were learning the syntax of the English language. >>> a = math.radians(180)
>>>
Although people commonly violate the syntax rules of their native language when
speaking and writing, other people usually understand what they mean. Unfortunately, Typically, you should avoid using the wildcard import statement because it can lead to
compilers and interpreters do not have this ability. If even a single syntax error appears name clashes when you are importing several modules. A name clash occurs when a
in a program, the program cannot be compiled or executed. When an interpreter program imports two modules that have functions or classes with the same name. Name
encounters a syntax error, it stops executing the program. clashes do not occur when you are using the qualified names of a module’s functions
and/or classes.
42 Chapter 1 Introduction to Computers and Programming
Checkpoint
1.18 A CPU understands instructions that are written only in what language?
1.19 A program has to be copied into what type of memory each time the CPU
executes it?
1.20 When a CPU executes the instructions in a program, it is engaged in what process?
More About the import
APP ENDIX
E
1.21 What is assembly language?
1.22 What type of programming language allows you to create powerful and complex
Statement 1.23
programs without knowing how the CPU works?
Each language has a set of rules that must be strictly followed when writing a
program. What is this set of rules called?
1.24 What do you call a program that translates a high-level language program into a
separate machine language program?
1.25 What do you call a program that both translates and executes the instructions in
A module is a Python source code file that contains functions and/or classes. Many of the a high-level language program?
functions in the Python standard library are stored in modules. For example, the math mod- 1.26 What type of mistake is usually caused by a misspelled key word, a missing
ule contains various mathematical functions, and the random module contains functions for punctuation character, or the incorrect use of an operator?
working with random numbers.
In order to use the functions and/or classes that are stored in a module, you must import the
module. To import a module, you write an import statement at the top of your program.
1.5 Using Python
Here is an import statement that imports the math module:
CONCEPT : The Python interpreter can run Python programs that are saved in files
import math
or interactively execute Python statements that are typed at the keyboard.
This statement causes the Python interpreter to load the contents of the math module into Python comes with a program named IDLE that simplifies the process of
memory, making the functions and/or classes that are stored in the math module available writing, executing, and testing programs.
to the program. To use any item that is in the module, you must use the item’s qualified
name. This means that you must prefix the item’s name with the name of the module, fol-
lowed by a dot. For example, the math module has a function named sqrt that returns the Installing Python
square root of a number. To call the sqrt function, you would use the name math.sqrt. Before you can try any of the programs shown in this book, or write any programs of your
The following interactive session shows an example: own, you need to make sure that Python is installed on your computer and properly con-
>>> import math
figured. If you are working in a computer lab, this has probably been done already. If you
>>> x = math.sqrt(25)
are using your own computer, you can follow the instructions in Appendix A to download
>>> print(x)
and install Python.
5.0
>>> The Python Interpreter
You learned earlier that Python is an interpreted language. When you install the Python
language on your computer, one of the items that is installed is the Python interpreter. The
Importing a Specific Function or Class Python interpreter is a program that can read Python programming statements and execute
The previously shown form of the import statement loads the entire contents of a module them. (Sometimes, we will refer to the Python interpreter simply as the interpreter.)
into memory. Sometimes you want to import only a specific function or class from a mod-
You can use the interpreter in two modes: interactive mode and script mode. In interac-
ule. When this is the case, you can use the from keyword with the import statement, as
tive mode, the interpreter waits for you to type Python statements on the keyboard. Once
shown here:
you type a statement, the interpreter executes it and then waits for you to type another
from math import sqrt statement. In script mode, the interpreter reads the contents of a file that contains Python
statements. Such a file is known as a Python program or a Python script. The interpreter
executes each statement in the Python program as it reads it.
701
1.5 Using Python 43
Interactive Mode
Once Python has been installed and set up on your system, you start the interpreter in
interactive mode by going to the operating system’s command line and typing the follow-
ing command:
python
If you are using Windows, you can alternatively type python in the Windows search box.
In the search results, you will see a program named something like Python 3.5. (The “3.5”
is the version of Python that is installed. At the time this is being written, Python 3.5 is
the latest version.) Clicking this item will start the Python interpreter in interactive mode.
When the Python interpreter starts in interactive mode, you will see something like the fol-
lowing displayed in a console window:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48)
[MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license"
for more information. This page intentionally left blank
>>>
The >>> that you see is a prompt that indicates the interpreter is waiting for you to type
a Python statement. Let’s try it out. One of the simplest things that you can do in Python
is print a message on the screen. For example, the following statement prints the message
Python programming is fun! on the screen:
print('Python programming is fun!')
You can think of this as a command that you are sending to the Python interpreter. If
you type the statement exactly as it is shown, the message Python programming is fun! is
printed on the screen. Here is an example of how you type this statement at the interpreter’s
prompt:
>>> print('Python programming is fun!') Enter
After typing the statement, you press the Enter key, and the Python interpreter executes the
statement, as shown here:
>>> print('Python programming is fun!') Enter
Python programming is fun!
>>>
Appendix D Predefined Named Colors 699 44 Chapter 1 Introduction to Computers and Programming
'gray3' 'gray4' 'gray5' After the message is displayed, the >>> prompt appears again, indicating the interpreter is
'gray6' 'gray7' 'gray8' waiting for you to enter another statement. Let’s look at another example. In the following
sample session, we have entered two statements:
'gray9' 'gray10' 'gray11'
>>> print('To be or not to be') Enter
'gray12' 'gray13' 'gray14'
To be or not to be
'gray15' 'gray16' 'gray17' >>> print('That is the question.') Enter
'gray18' 'gray19' 'gray20' That is the question.
>>>
'gray21' 'gray22' 'gray23'
'gray24' 'gray25' 'gray26' If you incorrectly type a statement in interactive mode, the interpreter will display an error
message. This will make interactive mode useful to you while you learn Python. As you
'gray27' 'gray28' 'gray29'
learn new parts of the Python language, you can try them out in interactive mode and get
'gray30' 'gray31' 'gray32' immediate feedback from the interpreter.
'gray33' 'gray34' 'gray35' To quit the Python interpreter in interactive mode on a Windows computer, press Ctrl-Z
'gray36' 'gray37' 'gray38' (pressing both keys together) followed by Enter. On a Mac, Linux, or UNIX computer,
press Ctrl-D.
'gray39' 'gray40' 'gray42'
'gray43' 'gray44' 'gray45'
'gray46' 'gray47' 'gray48' N O TE : In Chapter 2, we will discuss the details of statements like the ones previously
shown. If you want to try them now in interactive mode, make sure you type them exactly
'gray49' 'gray50' 'gray51'
as shown.
'gray52' 'gray53' 'gray54'
'gray55' 'gray56' 'gray57'
'gray58' 'gray59' 'gray60' Writing Python Programs and Running
'gray61' 'gray62' 'gray63' Them in Script Mode
'gray64' 'gray65' 'gray66' Although interactive mode is useful for testing code, the statements that you enter in interac-
tive mode are not saved as a program. They are simply executed and their results displayed on
'gray67' 'gray68' 'gray69'
the screen. If you want to save a set of Python statements as a program, you save those state-
'gray70' 'gray71' 'gray72' ments in a file. Then, to execute the program, you use the Python interpreter in script mode.
'gray73' 'gray74' 'gray75' For example, suppose you want to write a Python program that displays the following three
'gray76' 'gray77' 'gray78' lines of text:
'gray79' 'gray80' 'gray81' Nudge nudge
'gray82' 'gray83' 'gray84' Wink wink
Know what I mean?
'gray85' 'gray86' 'gray87'
'gray88' 'gray89' 'gray90'
To write the program you would use a simple text editor like Notepad (which is installed
on all Windows computers) to create a file containing the following statements:
'gray91' 'gray92' 'gray93'
print('Nudge nudge')
'gray94' 'gray95' 'gray97'
print('Wink wink')
'gray98' 'gray99' print('Know what I mean?')
N O TE : It is possible to use a word processor to create a Python program, but you must
be sure to save the program as a plain text file. Otherwise, the Python interpreter will
not be able to read its contents.
GLOBAL GLOBAL
EDITION EDITION
RESPECTIVE SUPPLIERS HEREBY DISCLAIM ALL WARRANTIES AND CONDITIONS WITH REGARD TO
THIS INFORMATION, INCLUDING ALL WARRANTIES AND CONDITIONS OF MERCHANTABILITY,
Digital Resources for Students WHETHER EXPRESS, IMPLIED OR STATUTORY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND
NON-INFRINGEMENT. IN NO EVENT SHALL MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS
BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
Your new textbook provides 12-month access to digital resources that may include WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION
VideoNotes (step-by-step video tutorials on programming concepts), source code, web
WITH THE USE OR PERFORMANCE OF INFORMATION AVAILABLE FROM THE SERVICES. THE
chapters, quizzes, and more. Refer to the preface in the textbook for a detailed list of DOCUMENTS AND RELATED GRAPHICS CONTAINED HEREIN COULD INCLUDE TECHNICAL
resources. INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES ARE PERIODICALLY ADDED TO
THE INFORMATION HEREIN. MICROSOFT AND/OR ITS RESPECTIVE SUPPLIERS MAY MAKE
Follow the instructions below to register for the Companion Website for Tony Gaddis’ IMPROVEMENTS AND/OR CHANGES IN THE PRODUCT(S) AND/OR THE PROGRAM(S) DESCRIBED
Starting Out with Python, Fourth Edition, Global Edition. HEREIN AT ANY TIME. PARTIAL SCREEN SHOTS MAY BE VIEWED IN FULL WITHIN THE SOFTWARE
VERSION SPECIFIED.
1. Go to www.pearsonglobaleditions.com/gaddis
2. Enter the title of your textbook or browse by author name.
3. Click Companion Website.
4. Click Register and follow the on-screen instructions to create a login name
and password.
ISSGPY-PRANK-CURRY-PIQUE-METIS-ROUSE
Use the login name and password you created during registration to start using the
online resources that accompany your textbook.
IMPORTANT:
This prepaid subscription does not include access to MyProgrammingLab, which is
available at www.myprogramminglab.com for purchase.
This subscription is valid for 12 months upon activation and is not transferable.
743
742 Index
P
defined, 261 Widgets
general format, 272 arrangement of, 630
how to use, 274–276 Button, 622, 630–633
®
and IPO charts, 276–277 Canvas, 622
randint and, 263–266 Checkbutton, 622, 648–650
random number generation, 262–271 defined, 622
randrange and, 269–270 Entry, 622, 633–636
returning multiple values, 282–283 Frame, 622, 629
return statement, 272–274 with frames, organizing, 627–630
for simplifying mathematical expressions, 274–276 Label, 622, 625–626, 629, 636–640
values, 261, 274 Listbox, 622
void functions and, 233 list of, 641
F OUR TH ED ITION writing, 272–283
Values
Menu, 622
Menubutton, 622
P
str data type, 69–70 as base classes, 574
str function defined, 574
defined, 326 in UML diagrams, 582–583
®
example use, 323 writing, 575
String comparisons, 144–147, 444–445, 463, 464 Supersets, 492
String concatenation SUV class, 580–581
defined, 90, 434 Symbols, flowchart, 56
example, 90 symmetric_difference method, 491
interactive sessions, 434 Symmetric difference of sets, 491
newline to, 319–320 Syntax
with + operator, 90 defined, 40
with += operator, 435 human language, 41
F OUR TH ED ITION String literals
defined, 59
Syntax errors
correcting, 54
GLOBA L EDITION enclosing in triple quotes, 60
Strings
defined, 41
reporting, 691
characters, accessing, 430–434 running programs and, 691
comparing, 144–148 System software, 28–29
defined, 59
extracting characters from, 438–440 T
as immutable, 435–436 tan() function, 285
Tony Gaddis
indexes, 432–433 Target variables
iterating with for loop, 430–432 defined, 192
list of, 366 inside for loops, 194–196
Haywood Community College method call format, 442 use example, 195
modification methods, 444–445 Terminal symbols, 56
operations, 429–436 Testing
raw, 314 dictionary values, 463–464
reading as input, 429 programs, 54–55
repetition operator (*) with, 450–451 set values, 488–489
returning, 280 string methods, 442–443
search and replace methods, 445–446 strings, 441
slicing, 437–438 Text
space character at end, 73 drawing with Canvas widget, 667–672
splitting, 451–452 displaying with Label widget, 624–627
storing with str data type, 69–70 editing, 687–688
stripping newline from, 320–322 font setting, 670–672
testing, 441 Text files
testing methods, 442–443 defined, 311
writing as output, 429 reading numbers from, 324
written to files, 316 Text widget, 622
StringVar object, 636–637 third-party modules, 705
strip() method, 444 Tkinter module
Stripping newline from string, 320–322 defined, 621
Structure charts. See Hierarchy charts programs using, 622
Subclasses widgets, 622
defined, 574 Top-down design
as derived classes, 574 defined, 240
method override, 588 process, 240–241
�)è“ÜÊÃ�ZãØ——ã �B—ô�xÊع �Bx�
Index 739
Running programs, 690–691 set method, 640, 647 Senior Vice President Courseware Portfolio Management: Marcia J. Horton
Running totals Sets Director, Portfolio Management: Engineering,
calculating, 201–204 adding elements, 486–487 Computer Science & Global Editions: Julian Partridge
defined, 201 creating, 485
Portfolio Manager: Matt Goldstein
elements for calculating, 201 defined, 484
example, 202 difference of, 490–491
Acquisitions Editor, Global Edition: Sourabh Maheshwari
logic for calculating, 201 duplicate elements, 485 Portfolio Management Assistant: Kristy Alaura
elements, as unique, 484 Field Marketing Manager: Demetrius Hall
S elements, number of, 486 Product Marketing Manager: Yvonne Vannatta
Samples, 34 elements, removing, 487–488 Managing Producer, ECS and Math: Scott Disanno
Saving programs, 690 intersection of, 490 Content Producer: Sandra L. Rodriguez
SavingsAccount class, 584, 585 for loop iteration over, 488
Project Editors, Global Edition: Tanima Ghosh and Neelakantan K.K.
Scale widget, 622 operations, 493–495
Scientific notation, 92 subsets, 492
Senior Manufacturing Controller, Global Edition: Jerry Kataria
Scope supersets, 492 Manager, Media Production, Global Edition: Vikram Kumar
defined, 245 symmetric difference of, 491 Cover Designer: Lumina Datamatics
local variables and, 245–247 union of, 489 Cover Photo: Africa Studio/Shutterstock
parameter variable, 249 unordered, 484
Credits and acknowledgments borrowed from other sources and reproduced, with permission, appear
Script mode, running programs in, 45 values, testing, 488–489
Scrollbar widget, 622 Settings. See Mutator methods
on the Credits page in the endmatter of this textbook.
Searching Showinfo function, 630 Pearson Education Limited
lists, 376–377 sin() function, 285
KAO Two
records, 339–341 Single alternative decision structures, 132
strings, 445–446 Slices KAO Park
Secondary storage defined, 373 Harlow
defined, 27 example use, 373–375 CM17 9NA
devices, 27–28 general format, 373 United Kingdom
Seeds, random number, 270–271 invalid indexes and, 375
Seed value, 270 list, 373–376 and Associated Companies throughout the world
Selection structures. See Decision structures start and end index, 374
Visit us on the World Wide Web at: www.pearsonglobaleditions.com
Sentinels string, 437–438
defined, 204, 205 Software © Pearson Education Limited 2019
using, 205–206 application, 29
values, 204–205 defined, 23 The rights of Tony Gaddis to be identified as the author of this work has been asserted by him in accor-
Separators developers. See Programmers dance with the Copyright, Designs and Patents Act 1988.
comma, 92–93 development tools, 29
item, 88–89 operating system, 28 Authorized adaptation from the United States edition, entitled Starting Out with Python, 4th Edition,
split method, 451–452 requirements, 55 ISBN 978-0-13-444432-1 by Tony Gaddis, published by Pearson Education © 2018.
Sequences. See also Lists system, 28–29
accepting as argument, 383–384 types of, 28 All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted
defined, 365 utility programs, 28 in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without either
length, returning, 369 Sorting, item list, 381–382 the prior written permission of the publisher or a license permitting restricted copying in the United Kingdom
tuples, 402–404 sort method, 378, 381–382
issued by the Copyright Licensing Agency Ltd, Sa ron House, 6–10 Kirby Street, London EC1N 8TS.
Sequence structures Source code. See Code
with decision structure, 147 Specialization, 573–574 All trademarks used herein are the property of their respective owners. The use of any trademark in this
defined, 131 split method, 451 text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor
example, 131 Splitting strings, 451–452
does the use of such trademarks imply any a liation with or endorsement of this book by such owners.
nested inside decision structure, 148 sqrt() function, 285
structure, 147, 148 startswith method, 445, 446
British Library Cataloguing-in-Publication Data
use in programming, 131–132 Statements
Serializing objects for, 190, 194, 196 A catalogue record for this book is available from the British Library
defined, 496 assignment, 62–65
10 9 8 7 6 5 4 3 2 1
example, 498–500, 542–544 in blocks, 133, 235
pickle module, 496–497 breaking into multiple lines, 86–87 ISBN 10: 1-292-22575-0
unserializing, 500–502, 543–544 converting math formulas to, 83–85 ISBN 13: 978-1-292-22575-3
ServiceQuote class, 563–565 defined, 40
set function, 485 del, 383 Typeset by iEnergizer Aptara®, Ltd.
Printed and bound in Malaysia
738 Index
7
Index 735 8 Contents
Chapter 8 More About Strings 429 not operator, 155, 157 multiplication (*), 76, 79, 367
8.1 Basic String Operations 429 Nouns, list refining, 557–560 not in. See Not in operator
8.2 String Slicing 437 Numbers or, 155–157, 159, 160
advanced storage, 34 precedence, 79
8.3 Testing, Searching, and Manipulating Strings 441
binary, 31–32 relational, 133–134, 145–146
Review Questions 453 factorial of, 603–605 remainder (%), 76, 79, 82–83
Programming Exercises 456 Fibonacci, 607–609 repetition (*), 367, 450–451
floating-point, 33, 94 subtraction (−), 76, 79
Chapter 9 Dictionaries and Sets 461 formatting, 90–91 Optical devices, 28
9.1 Dictionaries 461 pseudorandom, 270–271 or operator, 155–157, 159, 160
9.2 Sets 484 random, 262–271 Output
9.3 Serializing Objects 496 running totals, 201–204 in computer program process, 57–58
storage, 31–33 data, 87–95
Review Questions 502
Numeric literals, 69 defined, 28
Programming Exercises 507 Numeric ranges, with logical operators, 160 displaying, 58–61
Output devices, 28
Chapter 10 Classes and Object-Oriented Programming 511 Output files, 310, 311, 315, 322, 326
10.1 Procedural and Object-Oriented Programming 511 O
Overhead, 602
Object-oriented programming (OOP)
10.2 Classes 515 class design, 554–565
Overriding, method, 588
10.3 Working with Instances 532 classes, 515–532
10.4 Techniques for Designing Classes 554 data hiding, 512
P
pack method, 625–627, 629, 634
Review Questions 565 defined, 512
Parameter lists, 252
Programming Exercises 568 encapsulation, 512
Parentheses, grouping with, 80
instances, 515, 532–554
Pascal, 39
Chapter 11 Inheritance 573 Objects, 629. See also Classes
Passing arguments. See also Arguments
11.1 Introduction to Inheritance 573 characteristics description, 515
to function, 248–251
11.2 Polymorphism 588 defined, 512
function parameter variable, 253–255
dictionary, 461–484
Review Questions 594 to index method, 379–381
everyday example of, 513–514
Programming Exercises 596 list as function, 389–390
exception, 359 multiple, 251–253
file, 316–317 and objects, 540–541
Chapter 12 Recursion 599 list, 365, 366 by position, 252
12.1 Introduction to Recursion 599 “is a” relationship, 574 by value, 255
12.2 Problem Solving with Recursion 602 passing as arguments, 540–541 Passwords, validating characters in, 446–449
12.3 Examples of Recursive Algorithms 606 pickling, 542–544 Pattern printing using nested loops, 215–218
Review Questions 614 reusability, 513 Percentages, calculations, 77–78
Programming Exercises 616 sequence, 365 Pickle module, 497–498, 542, 547
serializing, 496–502 Pickling, 496–498, 500, 542–544
Chapter 13 GUI Programming 619 set, 484–496 pi variable, 285
storing in dictionaries, 544–554 pie chart, plotting, 418–420
13.1 Graphical User Interfaces 619
storing in lists, 538–540 pip utility, 705
13.2 Using the tkinter Module 621 StringVar, 636–637 Pixels, 34
13.3 Display Text with Label Widgets 624 unpickling, 543–544 plot() function, 406–407
13.4 Organizing Widgets with Frames 627 open function, 313, 314, 318 Polymorphism
13.5 Button Widgets and Info Dialog Boxes 630 Operands, 76 behavior, ingredients of, 588
13.6 Getting Input with the Entry Widget 633 Operating systems, 28 defined, 588
Operators isinstance function, 591–594
13.7 Using Labels as Output Fields 636
and, 156–158 popitem method, 473, 477
13.8 Radio Buttons and Check Buttons 644 in. See In operator pop method, 472, 720
13.9 Drawing Shapes with the Canvas Widget 651 addition (+), 76, 79, 90 Positional arguments, 257
Review Questions 673 assignment, 135, 203–204 Precedence, operator, 79
Programming Exercises 676 augmented assignment, 203–204 Predefined names colors, 695–699
exponent (**), 76, 80–82 Pretest loops
logical. See Logical operators defined, 186
math, 75–76 while loops as, 186–187
Index 733 10 Contents
Error handlers, 209 defined, 607–608 The new Turtle Graphics sections are designed with flexibility in mind. They can be
Error messages, 41, 44 recursive function calculation, 608–609 assigned as optional material, incorporated into your existing syllabus, or skipped
default, displaying, 355–356 Field widths
altogether.
loop displaying, 208–209 columns, 93
traceback, 349, 351 minimum, specifying, 93–94 ● Chapter 2 has a new section on named constants. Although Python does not support
Errors. See Exceptions File modes, 317 true constants, you can create variable names that symbolize values that should not
Error traps, 209 Filename extensions, 312
change as the program executes. This section teaches the student to avoid the use
Escape characters, 89–90 File objects
Event handlers, callback functions as, 630 close method, 315, 497 of “magic numbers,” and to create symbolic names that make his or her code more
Exception handling defined, 312 self-documenting and easier to maintain.
defined, 352 read method, 316–319 ● Chapter 7 has a new section on using the matplotlib package to plot charts and graphs
multiple exceptions, 352–355 variable name referencing, 312–314 from lists. The new section describes how to install the matplotlib package, and use it to
with try/except statement, 357–358 writelines method, 395–398
plot line graphs, bar charts, and pie charts.
Exception objects, 359 write method, 314
Exceptions finally clause, with try/except statement, 358
● Chapter 13 has a new section on creating graphics in a GUI application with the
catching all, with one except clause, 354–355 Finally suite, 358 Canvas widget. The new section describes how to use the Canvas widget to draw lines,
code response to, 348 find method, 446 rectangles, ovals, arcs, polygons, and text.
default error message display, 355–356 Flags, 162 ● Several new, more challenging, programming problems have been added throughout
defined, 75, 346 Flash drives, 28 the book.
IndexError, 368–369, 433 Flash memory, 28
IOError, 351–352, 354, 358 float data type, 69, 85–86
● Appendix E is a new appendix that discusses the various forms of the import statement.
KeyError, 463, 465, 487 float() function, 73, 74, 75, 86
● Appendix F is a new appendix that discusses installing third-party modules with the
multiple, 352–354 Floating-point division, 78, 79 pip utility.
unhandled, 358–359 Floating-point notation, 33
ValueError, 349–350, 354, 355, Floating-point numbers, 94
356, 358, 382 floor() function, 285 Brief Overview of Each Chapter
ZeroDivisionError, 358 Floppy disk drives, 27
Execution, 223 Flowchart, 56
in fetch-decode-execute cycle, 36 clock simulator, 213
Chapter 1: Introduction to Computers and Programming
pausing, 244 decision structure, 132, 133, 137 This chapter begins by giving a very concrete and easy-to-understand explanation of how
Python interpreter, 686–687 dual alternative decision structure, 130
computers work, how data is stored and manipulated, and why we write programs in high-
try/except statement, 349 input validation loop, 208
while loop, 209 logic for file end detection, 328 level languages. An introduction to Python, interactive mode, script mode, and the IDLE
Exercises nested decision structure, 149, 152 environment are also given.
decision structures, 173–179 pay calculating program, 57
dictionaries and sets, 507–510 program development cycle, 53
files and exceptions, 366–368 running total calculation, 201 Chapter 2: Input, Processing, and Output
functions, 302–308 sequence structure nested inside decision
This chapter introduces the program development cycle, variables, data types, and simple
GUI programming, 676–679 structure, 148
inheritance, 596–597 sequence structures with decision structure, 147–148 programs that are written as sequence structures. The student learns to write simple pro-
input, processing, and output, 126–130 while loop, 183 grams that read input from the keyboard, perform mathematical operations, and produce
introduction, 50–51 Font class, 670–672 screen output. Pseudocode and flowcharts are also introduced as tools for designing pro-
lists and tuples, 424–428 keyword arguments for, 671 grams. The chapter also includes an optional introduction to the turtle graphics library.
programming, 568–572 for loops. See also Loops
recursion, 616–617 as count-controlled loops, 190–200
repetition structures, 265–267 defined, 190–191 Chapter 3: Decision Structures and Boolean Logic
strings, 456–460 in turtle graphics, 219
exp() function, 285 iterating lists with, 368 In this chapter, the student learns about relational operators and Boolean expressions and is
Exponent (**) operator, 76, 80–82 iterating over dictionaries with, 468–469 shown how to control the flow of a program with decision structures. The if, if-else, and
iterating over list of strings with, 192 if-elif-else statements are covered. Nested decision structures and logical operators are
F iterating over sets, 488
discussed as well. The chapter also includes an optional turtle graphics section, with a discus-
Factorial function, 604–605 iterations, 198–200
Factorials iterations, user control, 198–200 sion of how to use decision structures to test the state of the turtle.
calculation with recursion, 602–606 range function with, 190–194
definition rules, 606, 609 target variables, 194–198
Fetch-decode-execute cycle, 36–37 format function, 91, 94
Chapter 4: Repetition Structures
Fibonacci series Format specifiers, 91–94 This chapter shows the student how to create repetition structures using the while loop and
for loop. Counters, accumulators, running totals, and sentinels are discussed, as well as
Preface 15 728 Index
techniques for writing input validation loops. The chapter also includes an optional section create_polygon method, 665–667 defined, 461
on using loops to draw designs with the turtle graphics library. optional arguments to, 667 elements, adding, 464
create_rectangle method, 655–657 elements, deleting, 465, 469
optional arguments to, 657 elements, display order, 462
Chapter 5: Functions create_text method, 667–672 elements, number of, 465–466
optional arguments to, 669 empty, creating, 467–468
In this chapter, the student first learns how to write and call void functions. The chapter C# programming language, 39 example, 474–477, 477–483
shows the benefits of using functions to modularize programs and discusses the top-down Customer class, 561–562 iteration, 468–469
design approach. Then, the student learns to pass arguments to functions. Common library keys, 461, 462
functions, such as those for generating random numbers, are discussed. After learning how D key-value pairs, 461, 464
Data methods, 469–474
to call library functions and use their return value, the student learns to define and call his mixing data types in, 466–467
appending to files, 322
or her own functions. Then the student learns how to use modules to organize functions. An binary file, 311 parts of, 461
optional section includes a discussion of modularizing turtle graphics code with functions. digital, 34 retrieving value from, 462–463
hiding, 512 storing objects in, 544–554
output, 87–95 values, 463–464
Chapter 6: Files and Exceptions processing, 333–346 Dictionary views
reading from files, 310–311, 316–319 defined, 470
This chapter introduces sequential file input and output. The student learns to read and write
text file, 311 elements, 470
large sets of data and store data as fields and records. The chapter concludes by discussing keys returned as, 471
writing to files, 310, 314–316
exceptions and shows the student how to write exception-handling code. Data attributes, 512 values returned as, 473–474
hidden, 513 dict() method, 468
hiding, 522–525 difference method, 490–491
Chapter 7: Lists and Tuples Digital data, 34
initializing, 518
This chapter introduces the student to the concept of a sequence in Python and explores the instance, 532–554 Digital devices, 34
Data storage, 29–33 Direct access files, 312, 343, 346
use of two common Python sequences: lists and tuples. The student learns to use lists for
characters, 33 Direct recursion, 606
arraylike operations, such as storing objects in a list, iterating over a list, searching for items music, 34 discard method, 487
in a list, and calculating the sum and average of items in a list. The chapter discusses slic- Data types Disk drives
ing and many of the list methods. One- and two-dimensional lists are covered. The chapter bool, 161 defined, 27
also includes a discussion of the matplotlib package, and how to use it to plot charts and conversion and mixed-type expressions, 85–86 program storage on, 36
graphs from lists. and literals, 68–69 Divide and conquer approach, 232
mixing, 466–467 Division
str, 69–70 floating-point, 78
Chapter 8: More About Strings Debugging, 54, 154 integer, 76, 78
global variables and, 258–259 / operator, 76, 78, 79
In this chapter, the student learns to process strings at a detailed level. String slicing and Decision structures, 132 Dog class, 589–590
algorithms that step through the individual characters in a string are discussed, and several actions performed in, 132–133 Dot notation, 263, 285
built-in functions and string methods for character and text processing are introduced. combining sequence structures with, 147–148 Dual alternative decision structure,
dual alternative, 140 139–140
in flowcharts, 132 dump method, 497
Chapter 9: Dictionaries and Sets if-elif-else statement, 153–154 DVD drives, 28
if-else statement, 140–143 DVDs (digital versatile discs), 28
This chapter introduces the dictionary and set data structures. The student learns to store data if statement, 131–139
as key-value pairs in dictionaries, search for values, change existing values, add new key-value inside, 148 E
pairs, and delete key-value pairs. The student learns to store values as unique elements in sets nested, 147–155 else clause, 143, 150
and perform common set operations such as union, intersection, di erence, and symmetric single alternative, 132 execution, 140
degrees() function, 285 with try/except statement, 357–358
di erence. The chapter concludes with a discussion of object serialization and introduces the
del statement, 383 else suite, 357
student to the Python pickle module. Depth of recursion, 602 Encapsulation, 512
Derived classes, 574 end–of–file, 500–501, 543
Chapter 10: Classes and Object-Oriented Programming Dialog boxes endswith method, 445, 446
defined, 619 ENIAC computer, 25, 26
This chapter compares procedural and object-oriented programming practices. It covers the illustrated, 620–621 Entry widget
fundamental concepts of classes and objects. Attributes, methods, encapsulation and data info, 630–633 defined, 622, 633
Dictionaries getting input with, 633–636
hiding, _ _init_ _ functions (which are similar to constructors), accessors, and mutators are
creating, 462 use example, 634–636
discussed. The student learns how to model classes with UML and how to find the classes
in a particular problem.
Index 727 16 Preface
VideoNotes Online videos developed specifically for this book are available
for viewing at www.pearsonglobaleditions.com/gaddis. Icons appear
throughout the text alerting the student to videos about specific
topics.
Notes Notes appear at several places throughout the text. They are
short explanations of interesting or often misunderstood points
relevant to the topic at hand.
Index Tips Tips advise the student on the best techniques for approaching
di erent programming problems.
Warnings Warnings caution students about programming techniques or
practices that can lead to malfunctioning programs or lost data.
Checkpoints Checkpoints are questions placed at intervals throughout each
chapter. They are designed to query the student’s knowledge
Symbols defined, 134 quickly after learning a new topic.
!= operator in string comparisons, 144
defined, 136 use example, 138 Review Questions Each chapter presents a thorough and diverse set of review
example use, 136, 138 > operator questions and exercises. They include Multiple Choice, True/
" (double-quote marks), 60 defined, 134 False, Algorithm Workbench, and Short Answer.
""" or "' (triple quotes), 60 in string comparisons, 146
# character, 61 use example, 134, 135–136 Programming Each chapter o ers a pool of programming exercises designed
% (remainder) operator >= operator Exercises to solidify the student’s knowledge of the topics currently being
defined, 76, 82 defined, 134 studied.
function of, 281 in superset determination, 492
%= operator, 203 relationship testing, 135
& operator, for intersection of sets, 490 >>> prompt, 43, 44
Supplements
' (single-quote marks), 59–60 ^ operator, 491
* operator _ _init_ _ method, 521, 555, 561, 563, 583 Student Online Resources
multiplication, 76 {}(curly braces), 462
Many student resources are available for this book from the publisher. The following items
repetition, 367
are available at www.pearsonglobaleditions.com/gaddis
** (exponent) operator, 76, 80–82 A
*= operator, 203 Accessor methods, 537 ● The source code for each example program in the book
+ operator acos(x) function, 285 ● Access to the book’s companion VideoNotes
defined, 76 Actions
displaying multiple items with, 90 conditionally executed, 132
in list concatenation, 371 in decision structures, 133 Instructor Resources
+= operator Ada programming language, 39
defined, 203
The following supplements are available to qualified instructors only:
Addition (+) operator
in list concatenation, 372 defined, 76 ● Answers to all of the Review Questions
in string concatenation, 435 displaying multiple items with, 90 ● Solutions for the exercises
− (subtraction) operator, 76 precedence, 79
_ _str_ _ method, 529–532 add method, 486
● PowerPoint presentation slides for each chapter
−= operator, 203 Algebraic expressions, 83–84 ● Test bank
/ (division) operator, 76, 78 Algorithms
// (integer division) operator, 76, 78 defined, 55 Visit the Pearson Instructor Resource Center (www.pearsonglobaleditions.com/gaddis) or
/= operator, 203 example, 55 contact your local Pearson campus representative for information on how to access them.
= operator recursive, 602, 603, 606–613
defined, 134 and operator
in subset determination, 492 defined, 156
relationship testing, 135 false, 158
= (assignment) operator, 135 short-circuit evaluation, 157
== operator truth table, 156
assignment operator versus, 136 Appending data, 322
725
Preface 19 724 Appendix G Answers to Checkpoints
I would like to thank the following faculty reviewers for their insight, expertise, and thought- 13.16 You would use check buttons.
ful recommendations: 13.17 When you create a group of Radiobuttons, you associate them all with
Sonya Dennis Anita Sutton the same IntVar object. You also assign a unique integer value to each
Morehouse College Germanna Community College Radiobutton widget. When one of the Radiobutton widgets is selected,
it stores its unique integer value in the IntVar object.
Diane Innes Christopher Urban
Sandhills Community College SUNY Institute of Technology 13.18 You associate a different IntVar object with each Checkbutton. When a
Checkbutton is selected, its associated IntVar object will hold the value 1.
John Kinuthia Nanette Veilleux When a Checkbutton is deselected, its associated IntVar object will hold the
Nazareth College of Rochester Simmons College value 0.
Frank Liu Brent Wilson 13.19 (0, 0)
Sam Houston State University George Fox University
13.20 (139, 479)
Haris Ribic
SUNY at Binghamton 13.21 With the Canvas widget, the point (0, 0) is in the upper-left corner of the
window. In turtle graphics, the point (0, 0) is in the center of the window.
Reviewers of Previous Editions Also, with the Canvas widget, the Y coordinates increase as you move down
Paul Amer Shyamal Mitra the screen. In turtle graphics, the Y coordinates decrease as you move down
University of Delaware University of Texas at Austin the screen.
Chapter 12 I would also like to thank my family and friends for their support in all of my projects.
I am extremely fortunate to have Matt Goldstein as my editor, and Kristy Alaura as edito-
12.1 A recursive algorithm requires multiple method calls. Each method call rial assistant. Their guidance and encouragement make it a pleasure to write chapters and
requires several actions to be performed by the JVM. These actions include meet deadlines. I am also fortunate to have Demetrius Hall as my marketing manager. His
allocating memory for parameters and local variables and storing the address hard work is truly inspiring, and he does a great job of getting this book out to the academic
of the program location where control returns after the method terminates. community. The production team, led by Sandra Rodriguez, worked tirelessly to make this
All these actions are known as overhead. In an iterative algorithm, which book a reality. Thanks to you all!
uses a loop, such overhead is unnecessary.
12.2 A case in which the problem can be solved without recursion Acknowledgments for the Global Edition
12.3 Cases in which the problem is solved using recursion Pearson would like to thank and acknowledge the following for their contributions to the
12.4 When it reaches the base case Global Edition.
12.5 In direct recursion, a recursive method calls itself. In indirect recursion, Contributor
method A calls method B, which in turn calls method A. Gregory Baatard, Edith Cowan University
Kenneth Eustace, Charles Sturt University
Chapter 13 Reviewers
Lindsay Ward, James Cook University
13.1 The part of a computer and its operating system with which the user
Ajay Mittal, University Institute of Engineering and Technology
interacts
Khyat Sharma
13.2 A command line interface typically displays a prompt, and the user types a
command, which is then executed. About the Author
13.3 The program Tony Gaddis is the principal author of the Starting Out with series of textbooks. Tony has
13.4 A program that responds to events that take place, such as the user clicking a nearly two decades of experience teaching computer science courses at Haywood Com-
button munity College. He is a highly acclaimed instructor who was previously selected as the
North Carolina Community College “Teacher of the Year” and has received the Teaching
13.5 a) Label—An area that displays one line of text or an image Excellence award from the National Institute for Sta and Organizational Development.
b) Entry—An area in which the user may type a single line of input from the The Starting Out with series includes introductory books covering C++, Java™, Microsoft®
keyboard Visual Basic®, Microsoft® C#®, Python®, Programming Logic and Design, Alice, and App
c) Button—A button that can cause an action to occur when it is clicked Inventor, all published by Pearson.
d) Frame—A container that can hold other widgets
13.6 You create an instance of the tkinter module’s Tk class.
13.7 This function runs like an infinite loop until you close the main window.
13.8 The pack method arranges a widget in its proper position, and it makes the
widget visible when the main window is displayed.
13.9 One will be stacked on top of the other.
13.10 side=–left—
13.11 You use an Entry widget’s get method to retrieve the data that the user has
typed into the widget.
13.12 It is a string.
13.13 tkinter
13.14 Any value that is stored in the StringVar object will automatically be
displayed in the Label widget.
722 Appendix G Answers to Checkpoints
Chapter 11
11.1 A superclass is a general class, and a subclass is a specialized class.
11.2 When one object is a specialized version of another object, there is an “is a”
relationship between them. The specialized object “is a” version of the
general object.
11.3 It inherits all the superclass’s attributes.
11.4 Bird is the superclass, and Canary is the subclass.
9.25 If the specified element to delete is not in the set, the remove method raises a
KeyError exception, but the discard method does not raise an exception.
9.26 You can use the in operator to test for the element.
9.27 {10, 20, 30, 100, 200, 300}
9.28 {3, 4}
9.29 {1, 2}
9.30 {5, 6}
9.33 The process of converting the object to a stream of bytes that can be saved to
a file for later retrieval.
9.34 'wb'
9.35 'rb'
9.38 pickle.load
Chapter 9
9.1 Key and value
9.2 The key
9.3 The string 'start' is the key, and the integer 1472 is the value.
Introduction to Computers
CHAPTE R
1
9.4 It stores the key-value pair 'id' : 54321 in the employee dictionary.
Computers can perform such a wide variety of tasks because they can be programmed. This 9.18 The set will contain one element: 25.
means that computers are not designed to do just one job, but to do any job that their pro-
9.19 The set will contain these elements (in no particular order): 'w', ' ', 'x',
grams tell them to do. A program is a set of instructions that a computer follows to perform
'y', and 'z'.
a task. For example, Figure 1-1 shows screens using Microsoft Word and PowerPoint, two
commonly used programs. 9.20 The set will contain these elements (in no particular order): 1, 2, 3, and 4.
Programs are commonly referred to as software. Software is essential to a computer because 9.21 The set will contain these elements (in no particular order): 'www', 'xxx',
it controls everything the computer does. All of the software that we use to make our com- 'yyy', and 'zzz'.
puters useful is created by individuals working as programmers or software developers. A
9.22 You pass the set as an argument to the len function.
programmer, or software developer, is a person with the training and skills necessary to
design, create, and test computer programs. Computer programming is an exciting and 9.23 The set will contain these elements (in no particular order): 10, 9, 8, 1, 2,
rewarding career. Today, you will find programmers’ work used in business, medicine, gov- and 3.
ernment, law enforcement, agriculture, academics, entertainment, and many other fields. 9.24 The set will contain these elements (in no particular order): 10, 9, 8, 'a',
This book introduces you to the fundamental concepts of computer programming using the 'b', and 'c'.
Python language. The Python language is a good choice for beginners because it is easy to learn
23
Appendix G Answers to Checkpoints 719 24 Chapter 1 Introduction to Computers and Programming
Then, each element in the list will become a slice in the pie chart. The size of Figure 1-1 A word processing program and an image editing program
a slice represents that element’s value as a percentage of the whole.
Chapter 8
8.1 for letter in name:
print(letter)
8.2 0
8.3 9
8.4 An IndexError exception will occur if you try to use an index that is out of
range for a particular string.
8.5 Use the built-in len function.
8.6 The second statement attempts to assign a value to an individual character
in the string. Strings are immutable, however, so the expression animal[0]
cannot appear on the left side of an assignment operator.
8.7 cde and programs can be written quickly using it. Python is also a powerful language, popular with
professional software developers. In fact, it has been reported that Python is used by Google,
8.8 defg NASA, YouTube, various game companies, the New York Stock Exchange, and many others.
8.9 abc Before we begin exploring the concepts of programming, you need to understand a few
8.10 abcdefg basic things about computers and how they work. This chapter will build a solid founda-
tion of knowledge that you will continually rely on as you study computer science. First,
8.11 if 'd' in mystring: we will discuss the physical components of which computers are commonly made. Next, we
print('Yes, it is there.')
will look at how computers store data and execute programs. Finally, you will get a quick
8.12 little = big.upper() introduction to the software that you will use to write Python programs.
8.13 if ch.isdigit():
print('Digit')
else: 1.2 Hardware and Software
print('No digit')
8.14 a A CONCEPT : The physical devices of which a computer is made are referred to as the
computer’s hardware. The programs that run on a computer are referred
8.15 again = input('Do you want to repeat ' + to as software.
'the program or quit? (R/Q) ')
while again.upper() != 'R' and again.upper() != 'Q': Hardware
again = input('Do you want to repeat the ' +
'program or quit? (R/Q) ') The term hardware refers to all of the physical devices, or components, of which a computer
is made. A computer is not one single device, but a system of devices that all work toge-
8.16 $ ther. Like the different instruments in a symphony orchestra, each device in a computer
8.17 for letter in mystring: plays its own part.
if letter.isupper(): If you have ever shopped for a computer, you’ve probably seen sales literature listing compo-
count += 1
nents such as microprocessors, memory, disk drives, video displays, graphics cards, and so on.
8.18 my_list = days.split() Unless you already know a lot about computers, or at least have a friend that does, under-
standing what these different components do might be challenging. As shown in Figure 1-2, a
8.19 my_list = values.split('$')
typical computer system consists of the following major components:
The central processing unit (CPU)
Main memory
1.2 Hardware and Software 25 718 Appendix G Answers to Checkpoints
Figure 1-2 Typical components of a computer system 7.17 You would use statement b, names.append('Wendy'). This is because
element 0 does not exist. If you try to use statement a, an error will occur.
7.18 a) The index method searches for an item in the list and returns the index of
the first element containing that item.
b) The insert method inserts an item into the list at a specified index.
Shutterstock
Central Processing c) The sort method sorts the items in the list to appear in ascending order.
Shutterstock
Unit
d) The reverse method reverses the order of the items in the list.
iko/Shutterstock
7.19 The list contains 4 rows and 2 columns.
Shutterstock
Feng Yu/Shutterstock
Output
Aquila/ Devices 7.20 mylist = [[0, 0, 0, 0], [0, 0, 0, 0],
[0, 0, 0, 0], [0, 0, 0, 0]]
Chiyacat/
Shutterstock 7.21 for r in range(4):
Peter Guess/
Shutterstock
for c in range(2):
Input
Devices
print(numbers[r][c])
jocic/Shutterstock
7.22 The primary difference between tuples and lists is that tuples are immutable.
Eikostas/Shutterstock
That means that once a tuple is created, it cannot be changed.
Main Memory
(RAM) 7.23 Here are three reasons:
Lusoimages/Shutterstock
Processing a tuple is faster than processing a list, so tuples are good
tkemot/Shutterstock Secondary
Storage Devices choices when you are processing lots of data and that data will not be
modified.
Tuples are safe. Because you are not allowed to change the contents of a
tuple, you can store data in one and rest assured that it will not be modified
(accidentally or otherwise) by any code in your program.
There are certain operations in Python that require the use of a tuple.
Vitaly Korovin/Shutterstock Andre Nitsievsky/Shutterstock.
7.24 my_tuple = tuple(my_list)
Secondary storage devices 7.25 my_list = list(my_tuple)
Input devices
Output devices 7.26 Two lists: one holding the X coordinates of the data points, and the other
holding the Y coordinates.
Let’s take a closer look at each of these components.
7.27 A line graph
The CPU 7.28 Use the xlabel and ylabel functions.
When a computer is performing the tasks that a program tells it to do, we say that the 7.29 Call the xlim and ylim functions, passing values for the xmin, xmax, ymin,
computer is running or executing the program. The central processing unit, or CPU, is the and ymax keyword arguments.
part of a computer that actually runs programs. The CPU is the most important component
7.30 Call the xticks and yticks functions. You pass two arguments to these
in a computer because without it, the computer could not run software.
functions. The first argument is a list of tick-mark locations, and the second
In the earliest computers, CPUs were huge devices made of electrical and mechanical com- argument is a list of labels to display at the specified locations.
ponents such as vacuum tubes and switches. Figure 1-3 shows such a device. The two
7.31 Two lists: one containing the X coordinates of each bar’s left edge, and
women in the photo are working with the historic ENIAC computer. The ENIAC, which
another containing the heights of each bar, along the Y axis.
is considered by many to be the world’s first programmable electronic computer, was built
in 1945 to calculate artillery ballistic tables for the U.S. Army. This machine, which was 7.32 The bars will be red, blue, red, and blue.
primarily one big CPU, was 8 feet tall, 100 feet long, and weighed 30 tons. 7.33 You pass a list of values as an argument. The pie function will calculate
Today, CPUs are small chips known as microprocessors. Figure 1-4 shows a photo of a lab the sum of the values in the list, then use that sum as the value of the whole.
technician holding a modern microprocessor. In addition to being much smaller than the old
electromechanical CPUs in early computers, microprocessors are also much more powerful.
Appendix G Answers to Checkpoints 717 26 Chapter 1 Introduction to Computers and Programming
6.18 You copy all the original file’s records to the temporary file, except for the Figure 1-3 The ENIAC computer
record that is to be deleted. The temporary file then takes the place of the
original file. You delete the original file and rename the temporary file, giving
it the name that the original file had on the computer’s disk.
6.19 An exception is an error that occurs while a program is running. In most
cases, an exception causes a program to abruptly halt.
6.20 The program halts.
6.21 IOError
6.22 ValueError
Chapter 7
7.1 [1, 2, 99, 4, 5]
7.2 [0, 1, 2]
7.4 1
courtesy of U.S. Army Historic Computer Images
3
5
7
9
Figure 1-4 A lab technician holds a modern microprocessor
7.5 4
7.8 [1, 2, 3]
[10, 20, 30, 1, 2, 3]
7.9 [2, 3]
7.10 [2, 3]
7.11 [1]
7.12 [1, 2, 3, 4, 5]
7.13 [3, 4, 5]
7.15 The remove method searches for and removes an element containing a
Creativa/Shutterstock
specific value. The del statement removes an element at a specific index.
7.16 You can use the built-in min and max functions.
1.2 Hardware and Software 27 716 Appendix G Answers to Checkpoints
Main Memory has not been converted to text. As a consequence, you cannot view the con-
tents of a binary file with a text editor.
You can think of main memory as the computer’s work area. This is where the computer
stores a program while the program is running, as well as the data that the program is 6.5 Sequential and direct access. When you work with a sequential access file,
working with. For example, suppose you are using a word processing program to write an you access data from the beginning of the file to the end of the file. When
essay for one of your classes. While you do this, both the word processing program and the you work with a direct access file, you can jump directly to any piece of data
essay are stored in main memory. in the file without reading the data that comes before it.
Main memory is commonly known as random-access memory, or RAM. It is called this 6.6 The file’s name on the disk and the name of a variable that references a file
because the CPU is able to quickly access data stored at any random location in RAM. object.
RAM is usually a volatile type of memory that is used only for temporary storage while
6.7 The file’s contents are erased.
a program is running. When the computer is turned off, the contents of RAM are erased.
Inside your computer, RAM is stored in chips, similar to the ones shown in Figure 1-5. 6.8 Opening a file creates a connection between the file and the program. It also
creates an association between the file and a file object.
6.9 Closing a file disconnects the program from the file.
Figure 1-5 Memory chips
6.10 A file’s read position marks the location of the next item that will be read
from the file. When an input file is opened, its read position is initially set to
the first item in the file.
6.11 You open the file in append mode. When you write data to a file in append
mode, the data is written to the end of the file’s existing contents.
Garsya/Shutterstock 6.12 outfile = open('numbers.txt', 'w')
for num in range(1, 11):
outfile.write(str(num) + '\n')
outfile.close()
Secondary Storage Devices
6.13 The readline method returns an empty string ('') when it has attempted to
Secondary storage is a type of memory that can hold data for long periods of time, even
read beyond the end of a file.
when there is no power to the computer. Programs are normally stored in secondary mem-
ory and loaded into main memory as needed. Important data, such as word processing 6.14 infile = open('numbers.txt', 'r')
documents, payroll data, and inventory records, is saved to secondary storage as well. line = infile.readline()
while line != '':
The most common type of secondary storage device is the disk drive. A traditional disk
print(line)
drive stores data by magnetically encoding it onto a spinning circular disk. Solid-state
line = infile.readline()
drives, which store data in solid-state memory, are increasingly becoming popular. A solid-
state drive has no moving parts and operates faster than a traditional disk drive. Most in le.close()
computers have some sort of secondary storage device, either a traditional disk drive or a 6.15 infile = open('data.txt', 'r')
solid-state drive, mounted inside their case. External storage devices, which connect to one for line in infile:
of the computer’s communication ports, are also available. External storage devices can print(line)
be used to create backup copies of important data or to move data to another computer. infile.close()
In addition to external storage devices, many types of devices have been created for copy- 6.16 A record is a complete set of data that describes one item, and a field is a
ing data and for moving it to other computers. For example, USB drives are small devices single piece of data within a record.
that plug into the computer’s USB (universal serial bus) port and appear to the system as
a disk drive. These drives do not actually contain a disk, however. They store data in a 6.17 You copy all the original file's records to the temporary file, but when you
special type of memory known as flash memory. USB drives, which are also known as get to the record that is to be modified, you do not write its old contents
memory sticks and flash drives, are inexpensive, reliable, and small enough to be carried to the temporary file. Instead, you write its new, modified values to the
in your pocket. temporary file. Then, you finish copying any remaining records from the
original file to the temporary file.
Appendix G Answers to Checkpoints 715 28 Chapter 1 Introduction to Computers and Programming
be changed during the program’s execution, you do not have to worry about Optical devices such as the CD (compact disc) and the DVD (digital versatile disc) are
its value being altered. also popular for data storage. Data is not recorded magnetically on an optical disc, but is
encoded as a series of pits on the disc surface. CD and DVD drives use a laser to detect
5.21 The difference is that a value returning function returns a value back to the
the pits and thus read the encoded data. Optical discs hold large amounts of data, and
statement that called it. A simple function does not return a value.
for that reason, recordable CD and DVD drives are commonly used for creating backup
5.22 A prewritten function that performs some commonly needed task copies of data.
5.23 The term “black box” is used to describe any mechanism that accepts input,
performs some operation (that cannot be seen) using the input, and produces Input Devices
output.
Input is any data the computer collects from people and from other devices. The compo-
5.24 It assigns a random integer in the range of 1 through 100 to the variable x. nent that collects the data and sends it to the computer is called an input device. Common
5.25 It prints a random integer in the range of 1 through 20. input devices are the keyboard, mouse, touchscreen, scanner, microphone, and digital cam-
era. Disk drives and optical drives can also be considered input devices, because programs
5.26 It prints a random integer in the range of 10 through 19. and data are retrieved from them and loaded into the computer’s memory.
5.27 It prints a random floating-point number in the range of 0.0 up to, but not
including, 1.0.
Output Devices
5.28 It prints a random floating-point number in the range of 0.1 through 0.5.
Output is any data the computer produces for people or for other devices. It might be
5.29 It uses the system time, retrieved from the computer’s internal clock. a sales report, a list of names, or a graphic image. The data is sent to an output device,
5.30 If the same seed value were always used, the random number functions which formats and presents it. Common output devices are video displays and printers.
would always generate the same series of pseudorandom numbers. Disk drives can also be considered output devices because the system sends data to them
in order to be saved.
5.31 It returns a value back to the part of the program that called it.
Software Development Tools Software development tools are the programs that pro- 5.5 When a program is developed as a set of functions in which each performs
grammers use to create, modify, and test software. Assemblers, compilers, and interpret- an individual task, then different programmers can be assigned the job of
ers are examples of programs that fall into this category. writing different functions.
5.6 A function definition has two parts: a header and a block. The header
Application Software indicates the starting point of the function, and the block is a list of
statements that belong to the function.
Programs that make a computer useful for everyday tasks are known as application soft-
ware. These are the programs that people normally spend most of their time running on 5.7 To call a function means to execute the function.
their computers. Figure 1-1, at the beginning of this chapter, shows screens from two com- 5.8 When the end of the function is reached, the computer returns back to the
monly used applications: Microsoft Word, a word processing program, and PowerPoint, a part of the program that called the function, and the program resumes
presentation program. Some other examples of application software are spreadsheet pro- execution at that point.
grams, email programs, web browsers, and game programs.
5.9 Because the Python interpreter uses the indentation to determine where a
block begins and ends
Checkpoint
5.10 A local variable is a variable that is declared inside a function. It belongs to
1.1 What is a program?
the function in which it is declared, and only statements in the same function
1.2 What is hardware? can access it.
1.3 List the five major components of a computer system.
5.11 The part of a program in which a variable may be accessed
1.4 What part of the computer actually runs programs?
5.12 Yes, it is permissible.
1.5 What part of the computer serves as a work area to store a program and its data
while the program is running? 5.13 Arguments
1.6 What part of the computer holds data for long periods of time, even when there is 5.14 Parameters
no power to the computer?
5.15 A parameter variable’s scope is the entire function in which the parameter is
1.7 What part of the computer collects data from people and from other devices?
declared.
1.8 What part of the computer formats and presents data for people or other devices?
5.16 No, it does not.
1.9 What fundamental set of programs control the internal operations of the
computer’s hardware? 5.17 a. passes by keyword argument
1.10 What do you call a program that performs a specialized task, such as a virus b. passes by position
scanner, a file compression program, or a data backup program? 5.18 The entire program
1.11 Word processing programs, spreadsheet programs, email programs, web browsers,
5.19 Here are three:
and game programs belong to what category of software?
Global variables make debugging difficult. Any statement in a program can
change the value of a global variable. If you find that the wrong value is being
stored in a global variable, you have to track down every statement that
1.3 How Computers Store Data accesses it to determine where the bad value is coming from. In a program
with thousands of lines of code, this can be difficult.
CONCEPT: All data that is stored in a computer is converted to sequences of 0s Functions that use global variables are usually dependent on those variables.
and 1s. If you want to use such a function in a different program, you will most likely
have to redesign it so it does not rely on the global variable.
A computer’s memory is divided into tiny storage locations known as bytes. One byte is Global variables make a program hard to understand. A global variable
only enough memory to store a letter of the alphabet or a small number. In order to do can be modified by any statement in the program. If you are to understand
anything meaningful, a computer has to have lots of bytes. Most computers today have any part of the program that uses a global variable, you have to be aware
millions, or even billions, of bytes of memory. of all the other parts of the program that access the global variable.
Each byte is divided into eight smaller storage locations known as bits. The term bit stands 5.20 A global constant is a name that is available to every function in the
for binary digit. Computer scientists usually think of bits as tiny switches that can be either program. It is permissible to use global constants. Because their value cannot
Appendix G Answers to Checkpoints 713 30 Chapter 1 Introduction to Computers and Programming
4.13 A variable that is used to accumulate the total of a series of numbers on or off. Bits aren’t actual “switches,” however, at least not in the conventional sense. In
most computer systems, bits are tiny electrical components that can hold either a positive
4.14 Yes, it should be initialized with the value 0. This is because values are added
or a negative charge. Computer scientists think of a positive charge as a switch in the on
to the accumulator by a loop. If the accumulator does not start at the value 0,
position, and a negative charge as a switch in the off position. Figure 1-6 shows the way
it will not contain the correct total of the numbers that were added to it when
that a computer scientist might think of a byte of memory: as a collection of switches that
the loop ends.
are each flipped to either the on or off position.
4.15 15
4.16 15
Figure 1-6 Think of a byte as eight switches
5
4.17 a) quantity += 1 ON ON ON ON
b) days_left −= 5
c) price *= 10
d) price /= 2
4.18 A sentinel is a special value that marks the end of a list of items.
4.19 A sentinel value must be unique enough that it will not be mistaken as a OFF OFF OFF OFF
regular value in the list.
4.20 It means that if bad data (garbage) is provided as input to a program, the
program will produce bad data (garbage) as output. When a piece of data is stored in a byte, the computer sets the eight bits to an on/off
4.21 When input is given to a program, it should be inspected before it is pattern that represents the data. For example, the pattern on the left in Figure 1-7 shows
processed. If the input is invalid, then it should be discarded and the user how the number 77 would be stored in a byte, and the pattern on the right shows how the
should be prompted to enter the correct data. letter A would be stored in a byte. We explain below how these patterns are determined.
4.22 The input is read, then a pretest loop is executed. If the input data is invalid,
the body of the loop executes. In the body of the loop, an error message is Figure 1-7 Bit patterns for the number 77 and the letter A
displayed so the user will know that the input was invalid, and then the
input read again. The loop repeats as long as the input is invalid. ON ON ON ON ON ON
4.23 It is the input operation that takes place just before an input validation loop.
The purpose of the priming read is to get the first input value.
4.24 None OFF
OFF OFF OFF OFF OFF OFF OFF OFF OFF
The position of each digit in a binary number has a value assigned to it. Starting with 3.26 You use the turtle.pencolor() function to determine the pen color.
the rightmost digit and moving left, the position values are 20, 21, 22, 23, and so forth, as You use the turtle.fillcolor() function to determine the current fill
shown in Figure 1-8. Figure 1-9 shows the same diagram with the position values calcu- color. You use the turtle.bgcolor() function to determine the current
lated. Starting with the rightmost digit and moving left, the position values are 1, 2, 4, 8, background color of the turtle’s graphics window.
and so forth.
3.27 You use the turtle.pensize() function.
3.28 You use the turtle.speed() function.
Figure 1-8 The values of binary digits as powers of 2
10011101 Chapter 4
0 4.1 A structure that causes a section of code to repeat
2
21 4.2 A loop that uses a true/false condition to control the number of times that it
22
23 repeats
24
25 4.3 A loop that repeats a specific number of times
26
27 4.4 An execution of the statements in the body of the loop
4.5 Before
Figure 1-9 The values of binary digits 4.6 None. The condition count < 0 will be false to begin with.
4.7 A loop that has no way of stopping and repeats until the program is
10011101 interrupted.
1 4.8 for x in range(6):
2
4 print('I love to program!')
8
16 4.9 0
32 1
64
128
2
3
4
5
To determine the value of a binary number, you simply add up the position values of all the
1s. For example, in the binary number 10011101, the position values of the 1s are 1, 4, 8, 4.10 2
16, and 128. This is shown in Figure 1-10. The sum of all of these position values is 157. 3
So, the value of the binary number 10011101 is 157. 4
5
3.13 if number == 1: Figure 1-11 shows how you can picture the number 157 stored in a byte of memory. Each
print('One') 1 is represented by a bit in the on position, and each 0 is represented by a bit in the off
elif number == 2: position.
print('Two')
elif number == 3:
print('Three') Figure 1-11 The bit pattern for 157
else:
print('Unknown')
Any piece of data that is stored in a computer’s memory must be stored as a binary num- 2.39 turtle.setup(500, 200)
ber. That includes characters, such as letters and punctuation marks. When a character is 2.40 turtle.goto(100, 50)
stored in memory, it is first converted to a numeric code. The numeric code is then stored
in memory as a binary number. 2.41 turtle.pos()
Over the years, different coding schemes have been developed to represent characters in 2.42 turtle.speed(10)
computer memory. Historically, the most important of these coding schemes is ASCII, 2.43 turtle.speed(0)
which stands for the American Standard Code for Information Interchange. ASCII is a set
of 128 numeric codes that represent the English letters, various punctuation marks, and 2.44 To fill a shape with a color, you use the turtle.begin_fill() command
other characters. For example, the ASCII code for the uppercase letter A is 65. When you before drawing the shape, then you use the turtle.end_fill() command
type an uppercase A on your computer keyboard, the number 65 is stored in memory (as after the shape is drawn. When the turtle.end_fill() command executes,
a binary number, of course). This is shown in Figure 1-13. the shape will be filled with the current fill color.
2.45 With the turtle.write()command
Figure 1-13 The letter A is stored in memory as the number 65
Chapter 3
1 1
A
3.1 A logical design that controls the order in which a set of statements execute
65 3.2 It is a program structure that can execute a set of statements only under
0 0 0 0 0 0
certain circumstances.
3.3 A decision structure that provides a single alternative path of execution.
If the condition that is being tested is true, the program takes the alternative
TIP : The acronym ASCII is pronounced “askee.” path.
3.4 An expression that can be evaluated as either true or false
In case you are curious, the ASCII code for uppercase B is 66, for uppercase C is 67, and so 3.5 You can determine whether one value is greater than, less than, greater than
forth. Appendix C shows all of the ASCII codes and the characters they represent. or equal to, less than or equal to, equal to, or not equal to another value.
The ASCII character set was developed in the early 1960s and was eventually adopted by 3.6 if y == 20:
almost all computer manufacturers. ASCII is limited, however, because it defines codes for x = 0
only 128 characters. To remedy this, the Unicode character set was developed in the early 3.7 if sales >= 10000:
1990s. Unicode is an extensive encoding scheme that is compatible with ASCII, but can commissionRate = 0.2
also represent characters for many of the languages in the world. Today, Unicode is quickly
becoming the standard character set used in the computer industry. 3.8 A dual alternative decision structure has two possible paths of execution;
one path is taken if a condition is true, and the other path is taken if the
condition is false.
Advanced Number Storage 3.9 if-else
Earlier, you read about numbers and how they are stored in memory. While reading that 3.10 When the condition is false
section, perhaps it occurred to you that the binary numbering system can be used to repre-
sent only integer numbers, beginning with 0. Negative numbers and real numbers (such as 3.11 z is not less than a.
3.14159) cannot be represented using the simple binary numbering technique we discussed. 3.12 Boston
Computers are able to store negative numbers and real numbers in memory, but to do so New York
they use encoding schemes along with the binary numbering system. Negative numbers are
encoded using a technique known as two’s complement, and real numbers are encoded in
floating-point notation. You don’t need to know how these encoding schemes work, only
that they are used to convert negative numbers and real numbers to binary format.
Appendix G Answers to Checkpoints 709 34 Chapter 1 Introduction to Computers and Programming
01
0
2.20 4
00
10
101
101
2.21 1
2.22 If you do not want the print function to start a new line of output when it
finishes displaying its output, you can pass the special argument end = ' '
to the function.
The music that you play on your CD player, iPod, or MP3 player is also digital. A digital
2.23 You can pass the argument sep= to the print function, specifying the song is broken into small pieces known as samples. Each sample is converted to a binary
desired character. number, which can be stored in memory. The more samples that a song is divided into, the
2.24 It is the newline escape character. more it sounds like the original music when it is played back. A CD quality song is divided
into more than 44,000 samples per second!
2.25 It is the string concatenation operator, which joins two strings together.
2.26 65.43 Checkpoint
2.27 987,654.13 1.12 What amount of memory is enough to store a letter of the alphabet or a small
number?
2.28 (1) Named constants make programs more self-explanatory, (2) widespread
changes can easily be made to the program, and (3) they help to prevent the 1.13 What do you call a tiny “switch” that can be set to either on or off?
typographical errors that are common when using magic numbers. 1.14 In what numbering system are all numeric values written as sequences of 0s and 1s?
2.35 turtle.circle(100) CONCEPT : A computer’s CPU can only understand instructions that are written in
machine language. Because people find it very difficult to write entire
2.36 turtle.pensize(8)
programs in machine language, other programming languages have been
2.37 turtle.pencolor('blue') invented.
1.4 How a Program Works 35 708 Appendix G Answers to Checkpoints
Earlier, we stated that the CPU is the most important component in a computer because it is 1.18 Machine language
the part of the computer that runs programs. Sometimes the CPU is called the “computer’s
1.19 Main memory, or RAM
brain” and is described as being “smart.” Although these are common metaphors, you
should understand that the CPU is not a brain, and it is not smart. The CPU is an electronic 1.20 The fetch-decode-execute cycle
device that is designed to do specific things. In particular, the CPU is designed to perform
1.21 It is an alternative to machine language. Instead of using binary numbers
operations such as the following:
for instructions, assembly language uses short words that are known as
Reading a piece of data from main memory mnemonics.
Adding two numbers
1.22 A high-level language
Subtracting one number from another number
Multiplying two numbers 1.23 Syntax
Dividing one number by another number
1.24 A compiler
Moving a piece of data from one memory location to another
Determining whether one value is equal to another value 1.25 An interpreter
As you can see from this list, the CPU performs simple operations on pieces of data. The 1.26 A syntax error
CPU does nothing on its own, however. It has to be told what to do, and that’s the purpose
of a program. A program is nothing more than a list of instructions that cause the CPU to
perform operations. Chapter 2
Each instruction in a program is a command that tells the CPU to perform a specific opera- 2.1 Any person, group, or organization that is asking you to write a program
tion. Here’s an example of an instruction that might appear in a program: 2.2 A single function that the program must perform in order to satisfy the
10110000 customer
To you and me, this is only a series of 0s and 1s. To a CPU, however, this is an instruction 2.3 A set of well-defined logical steps that must be taken to perform a task
to perform an operation.1 It is written in 0s and 1s because CPUs only understand instruc- 2.4 An informal language that has no syntax rules and is not meant to be
tions that are written in machine language, and machine language instructions always have compiled or executed. Instead, programmers use pseudocode to create
an underlying binary structure. models, or “mock-ups,” of programs.
A machine language instruction exists for each operation that a CPU is capable of perform- 2.5 A diagram that graphically depicts the steps that take place in a program
ing. For example, there is an instruction for adding numbers, there is an instruction for
subtracting one number from another, and so forth. The entire set of instructions that a 2.6 Ovals are terminal symbols. Parallelograms are either output or input
CPU can execute is known as the CPU’s instruction set. symbols. Rectangles are processing symbols.
2.7 print('Jimmy Smith')
The machine language instruction that was previously shown is an example of only one
instruction. It takes a lot more than one instruction, however, for the computer to do any-
thing meaningful. Because the operations that a CPU knows how to perform are so basic in
nature, a meaningful task can be accomplished only if the CPU performs many operations.
For example, if you want your computer to calculate the amount of interest that you will
APP ENDIX
earn from your savings account this year, the CPU will have to perform a large number of
G
instructions, carried out in the proper sequence. It is not unusual for a program to contain
Answers to Checkpoints thousands or even millions of machine language instructions.
Programs are usually stored on a secondary storage device such as a disk drive. When you
install a program on your computer, the program is typically copied to your computer’s disk
drive from a CD-ROM, or downloaded from a website.
Although a program can be stored on a secondary storage device such as a disk drive,
it has to be copied into main memory, or RAM, each time the CPU executes it. For
example, suppose you have a word processing program on your computer’s disk. To
execute the program, you use the mouse to double-click the program’s icon. This causes
Chapter 1
the program to be copied from the disk into main memory. Then, the computer’s CPU
1.1 A program is a set of instructions that a computer follows to perform a task. executes the copy of the program that is in main memory. This process is illustrated in
1.2 Hardware is all the physical devices, or components, of which a computer is Figure 1-15.
made.
1.3 The central processing unit (CPU), main memory, secondary storage devices, Figure 1-15 A program is copied into main memory and then executed
input devices, and output devices
The program is copied
1.4 The CPU The CPU executes
from secondary storage
the program in
to main memory.
1.5 Main memory main memory.
Main memory
1.6 Secondary storage (RAM)
1.7 Input device
1.8 Output device
1.9 The operating system Disk drive CPU
707
1.4 How a Program Works 37
10100001
Fetch the next instruction
1
in the program.
10100001
10111000 Decode the instruction
10011110 2 to determine which
00011010 operation to perform.
11011100
and so forth... CPU
Execute the instruction
3
(perform the operation).
Main memory
(RAM)
N OTE : There are many different versions of assembly language. It was mentioned
earlier that each brand of CPU has its own machine language instruction set. Each
brand of CPU typically has its own assembly language as well.
Assembly language programs cannot be executed by the CPU, however. The CPU only
understands machine language, so a special program known as an assembler is used to
translate an assembly language program to a machine language program. This process is
shown in Figure 1-17. The machine language program that is created by the assembler can
then be executed by the CPU.
2
The first assembly language was most likely that developed in the 1940s at Cambridge University
for use with a historic computer known as the EDSAC.
38 Chapter 1 Introduction to Computers and Programming
F
mov eax, Z 10100001
add eax, 2
mov Y, eax 10111000
High-Level Languages
Although assembly language makes it unnecessary to write binary machine language instruc-
The Python standard library provides classes and functions that your programs can use to tions, it is not without difficulties. Assembly language is primarily a direct substitute for
perform basic operations, as well as many advanced tasks. There are operations, however, machine language, and like machine language, it requires that you know a lot about the
that the standard library cannot perform. When you need to do something that is beyond CPU. Assembly language also requires that you write a large number of instructions for even
the scope of the standard library, you have two choices: write the code yourself, or use code the simplest program. Because assembly language is so close in nature to machine language,
that someone else has already written. it is referred to as a low-level language.
Fortunately, there are thousands of Python modules, written by independent programmers, In the 1950s, a new generation of programming languages known as high-level languages
that provide capabilities that the standard Python library does not offer. These are known began to appear. A high-level language allows you to create powerful and complex pro-
as third-party modules. A large collection of third-party modules exists at the website pypi. grams without knowing how the CPU works and without writing large numbers of low-level
python.org, which is known as the Python Package Index, or PyPI. instructions. In addition, most high-level languages use words that are easy to understand.
For example, if a programmer were using COBOL (which was one of the early high-level
The modules that are available at PyPI are organized as packages. A package is simply a coll- languages created in the 1950s), he or she would write the following instruction to display
ection of one or more related modules. The easiest way to download and install a package the message Hello world on the computer screen:
is with the pip utility. The pip utility is a program that is part of the standard Python
installation, beginning with Python 3.4. To install a package on a Windows system with DISPLAY "Hello world"
the pip utility, you must open a command prompt window, and type a command following Python is a modern, high-level programming language that we will use in this book. In
this format: Python you would display the message Hello world with the following instruction:
pip install package_name print('Hello world')
package_name is the name of a package that you want to download and install. If you are
Doing the same thing in assembly language would require several instructions and an inti-
running a Mac or a Linux system, you must use the pip3 command instead of the pip com-
mate knowledge of how the CPU interacts with the computer’s output device. As you can see
mand. In addition, you will need superuser privileges to execute the pip3 command on a
from this example, high-level languages allow programmers to concentrate on the tasks they
Mac or Linux system, so you will have to prefix the command with sudo, as shown here: want to perform with their programs, rather than the details of how the CPU will execute
sudo pip3 install package_name those programs.
Once you enter the command, the pip utility will start downloading and installing the Since the 1950s, thousands of high-level languages have been created. Table 1-1 lists several
package. Depending on the size of the package, it may take a few minutes to complete the of the more well-known languages.
installation process. Once the process is finished, you can typically verify that the package
was correctly installed by starting IDLE and entering the command
Key Words, Operators, and Syntax: An Overview
>>> import package_name
Each high-level language has its own set of predefined words that the programmer must
where package_name is the name of the package that you installed. If you do not see an use to write a program. The words that make up a high-level programming language are
error message, you can assume the package was successfully installed. known as key words or reserved words. Each key word has a specific meaning, and cannot
In Chapter 7, you will explore a popular third-party package named matplotlib. You can be used for any other purpose. Table 1-2 shows all of the Python key words.
use the matplotlib package to create charts and graphs.
705
1.4 How a Program Works 39
Using an Alias In addition to key words, programming languages have operators that perform various
operations on data. For example, all programming languages have math operators that
You can use the as keyword to assign an alias to a module when you import it. The follow- perform arithmetic. In Python, as well as most other languages, the + sign is an operator
ing statement shows an example: that adds two numbers. The following adds 12 and 75:
import math as mt 12 + 75
This statement loads the math module into memory, assigning the module the alias mt. There are numerous other operators in the Python language, many of which you will learn
To use any of the items that are in the module, you prefix the item’s name with the alias, about as you progress through this text.
followed by a dot. For example, to call the sqrt function, you would use the name
mt.sqrt. The following interactive session shows an example: In addition to key words and operators, each language also has its own syntax, which is a
set of rules that must be strictly followed when writing a program. The syntax rules dictate
>>> import math as mt how key words, operators, and various punctuation characters must be used in a program.
>>> x = mt.sqrt(25) When you are learning a programming language, you must learn the syntax rules for that
>>> a = mt.radians(180) particular language.
>>> print(x)
5.0 The individual instructions that you use to write a program in a high-level programming
>>> print(a) language are called statements. A programming statement can consist of key words, oper-
3.141592653589793 ators, punctuation, and other allowable programming elements, arranged in the proper
>>> sequence to perform an operation.
You can also assign an alias to a specific function or class when you import it. The follow-
ing statement imports the sqrt function from the math module, and assigns the function Compilers and Interpreters
the alias square_root:
Because the CPU understands only machine language instructions, programs that are writ-
from math import sqrt as square_root ten in a high-level language must be translated into machine language. Depending on the
language in which a program has been written, the programmer will use either a compiler
After using this import statement, you would use the name square_root to call the sqrt
or an interpreter to make the translation.
function. The following interactive session shows an example:
A compiler is a program that translates a high-level language program into a separate
>>> from math import sqrt as square_root
machine language program. The machine language program can then be executed any time
>>> x = square_root(25)
it is needed. This is shown in Figure 1-18. As shown in the figure, compiling and executing
>>> print(x)
are two different processes.
5.0
>>> Figure 1-18 Compiling a high-level program and executing it
In the following interactive session, we import two functions from the math module, giving
High-level language Machine language
each of them an alias. The sqrt function is imported as square_root, and the tan func- program
program
tion is imported as tangent:
The compiler is used 10100001
print ("Hello
>>> from math import sqrt as square_root, tan as tangent 1 to translate the high-level Earthling") 10111000
language program to a Compiler
>>> x = square_root(25) 10011110
machine language program. and so forth... and so forth...
>>> y = tangent(45)
>>> print(x)
5.0
>>> print(y)
1.6197751905438615
Machine language
CPU
program
The machine language 10100001
2 program can be executed 10111000
at any time, without using 10011110
the compiler. and so forth...
1.4 How a Program Works 41 702 Appendix E More About the import Statement
The Python language uses an interpreter, which is a program that both translates and This statement causes only the sqrt function to be imported from the math module. It also
executes the instructions in a high-level language program. As the interpreter reads allows you to call the sqrt function without prefixing the function’s name with the name
each individual instruction in the program, it converts it to machine language instruc- of the module. The following interactive session shows an example:
tions then immediately executes them. This process repeats for every instruction in
>>> from math import sqrt
the program. This process is illustrated in Figure 1-19. Because interpreters combine
>>> x = sqrt(25)
translation and execution, they typically do not create separate machine language
>>> print(x)
programs.
5.0
>>>
Figure 1-19 Executing a high-level program with an interpreter You can specify the names of multiple items, separated with commas, when you use this
form of the import statement. For example, the import statement in the following interac-
High-level language tive session imports only the sqrt function and the radians function from the math
program CPU module:
Machine language
print ("Hello instruction
>>> from math import sqrt, radians
Earthling") Interpreter 10100001
>>> x = sqrt(25)
and so forth... >>> a = radians(180)
>>> print(x)
5.0
The interpreter translates each high-level instruction to
>>> print(a)
its equivalent machine language instructions then 3.141592653589793
immediately executes them. >>>
This process is repeated for each high-level instruction.
Wildcard Imports
The statements that a programmer writes in a high-level language are called source A wildcard import statement loads the entire contents of a module. Here is an example:
code, or simply code. Typically, the programmer types a program’s code into a text
editor then saves the code in a file on the computer’s disk. Next, the programmer uses from math import *
a compiler to translate the code into a machine language program, or an interpreter to The difference between this statement and the import math statement is that the wildcard
translate and execute the code. If the code contains a syntax error, however, it cannot import statement does not require you to use the qualified names of the items in the mod-
be translated. A syntax error is a mistake such as a misspelled key word, a missing ule. For example, here is an interactive session that uses a wildcard import statement:
punctuation character, or the incorrect use of an operator. When this happens, the
compiler or interpreter displays an error message indicating that the program contains >>> from math import*
a syntax error. The programmer corrects the error then attempts once again to translate >>> x = sqrt(25)
the program. >>> a = radians(180)
>>>
And, here is an interactive session that uses the regular import statement:
N OTE : Human languages also have syntax rules. Do you remember when you took >>> import math
your first English class, and you learned all those rules about commas, apostrophes, >>> x = math.sqrt(25)
capitalization, and so forth? You were learning the syntax of the English language. >>> a = math.radians(180)
>>>
Although people commonly violate the syntax rules of their native language when
speaking and writing, other people usually understand what they mean. Unfortunately, Typically, you should avoid using the wildcard import statement because it can lead to
compilers and interpreters do not have this ability. If even a single syntax error appears name clashes when you are importing several modules. A name clash occurs when a
in a program, the program cannot be compiled or executed. When an interpreter program imports two modules that have functions or classes with the same name. Name
encounters a syntax error, it stops executing the program. clashes do not occur when you are using the qualified names of a module’s functions
and/or classes.
42 Chapter 1 Introduction to Computers and Programming
Checkpoint
1.18 A CPU understands instructions that are written only in what language?
1.19 A program has to be copied into what type of memory each time the CPU
executes it?
1.20 When a CPU executes the instructions in a program, it is engaged in what process?
More About the import
APP ENDIX
E
1.21 What is assembly language?
1.22 What type of programming language allows you to create powerful and complex
Statement 1.23
programs without knowing how the CPU works?
Each language has a set of rules that must be strictly followed when writing a
program. What is this set of rules called?
1.24 What do you call a program that translates a high-level language program into a
separate machine language program?
1.25 What do you call a program that both translates and executes the instructions in
A module is a Python source code file that contains functions and/or classes. Many of the a high-level language program?
functions in the Python standard library are stored in modules. For example, the math mod- 1.26 What type of mistake is usually caused by a misspelled key word, a missing
ule contains various mathematical functions, and the random module contains functions for punctuation character, or the incorrect use of an operator?
working with random numbers.
In order to use the functions and/or classes that are stored in a module, you must import the
module. To import a module, you write an import statement at the top of your program.
1.5 Using Python
Here is an import statement that imports the math module:
CONCEPT : The Python interpreter can run Python programs that are saved in files
import math
or interactively execute Python statements that are typed at the keyboard.
This statement causes the Python interpreter to load the contents of the math module into Python comes with a program named IDLE that simplifies the process of
memory, making the functions and/or classes that are stored in the math module available writing, executing, and testing programs.
to the program. To use any item that is in the module, you must use the item’s qualified
name. This means that you must prefix the item’s name with the name of the module, fol-
lowed by a dot. For example, the math module has a function named sqrt that returns the Installing Python
square root of a number. To call the sqrt function, you would use the name math.sqrt. Before you can try any of the programs shown in this book, or write any programs of your
The following interactive session shows an example: own, you need to make sure that Python is installed on your computer and properly con-
>>> import math
figured. If you are working in a computer lab, this has probably been done already. If you
>>> x = math.sqrt(25)
are using your own computer, you can follow the instructions in Appendix A to download
>>> print(x)
and install Python.
5.0
>>> The Python Interpreter
You learned earlier that Python is an interpreted language. When you install the Python
language on your computer, one of the items that is installed is the Python interpreter. The
Importing a Specific Function or Class Python interpreter is a program that can read Python programming statements and execute
The previously shown form of the import statement loads the entire contents of a module them. (Sometimes, we will refer to the Python interpreter simply as the interpreter.)
into memory. Sometimes you want to import only a specific function or class from a mod-
You can use the interpreter in two modes: interactive mode and script mode. In interac-
ule. When this is the case, you can use the from keyword with the import statement, as
tive mode, the interpreter waits for you to type Python statements on the keyboard. Once
shown here:
you type a statement, the interpreter executes it and then waits for you to type another
from math import sqrt statement. In script mode, the interpreter reads the contents of a file that contains Python
statements. Such a file is known as a Python program or a Python script. The interpreter
executes each statement in the Python program as it reads it.
701
1.5 Using Python 43
Interactive Mode
Once Python has been installed and set up on your system, you start the interpreter in
interactive mode by going to the operating system’s command line and typing the follow-
ing command:
python
If you are using Windows, you can alternatively type python in the Windows search box.
In the search results, you will see a program named something like Python 3.5. (The “3.5”
is the version of Python that is installed. At the time this is being written, Python 3.5 is
the latest version.) Clicking this item will start the Python interpreter in interactive mode.
When the Python interpreter starts in interactive mode, you will see something like the fol-
lowing displayed in a console window:
Python 3.5.1 (v3.5.1:37a07cee5969, Dec 6 2015, 01:38:48)
[MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license"
for more information. This page intentionally left blank
>>>
The >>> that you see is a prompt that indicates the interpreter is waiting for you to type
a Python statement. Let’s try it out. One of the simplest things that you can do in Python
is print a message on the screen. For example, the following statement prints the message
Python programming is fun! on the screen:
print('Python programming is fun!')
You can think of this as a command that you are sending to the Python interpreter. If
you type the statement exactly as it is shown, the message Python programming is fun! is
printed on the screen. Here is an example of how you type this statement at the interpreter’s
prompt:
>>> print('Python programming is fun!') Enter
After typing the statement, you press the Enter key, and the Python interpreter executes the
statement, as shown here:
>>> print('Python programming is fun!') Enter
Python programming is fun!
>>>
Appendix D Predefined Named Colors 699 44 Chapter 1 Introduction to Computers and Programming
'gray3' 'gray4' 'gray5' After the message is displayed, the >>> prompt appears again, indicating the interpreter is
'gray6' 'gray7' 'gray8' waiting for you to enter another statement. Let’s look at another example. In the following
sample session, we have entered two statements:
'gray9' 'gray10' 'gray11'
>>> print('To be or not to be') Enter
'gray12' 'gray13' 'gray14'
To be or not to be
'gray15' 'gray16' 'gray17' >>> print('That is the question.') Enter
'gray18' 'gray19' 'gray20' That is the question.
>>>
'gray21' 'gray22' 'gray23'
'gray24' 'gray25' 'gray26' If you incorrectly type a statement in interactive mode, the interpreter will display an error
message. This will make interactive mode useful to you while you learn Python. As you
'gray27' 'gray28' 'gray29'
learn new parts of the Python language, you can try them out in interactive mode and get
'gray30' 'gray31' 'gray32' immediate feedback from the interpreter.
'gray33' 'gray34' 'gray35' To quit the Python interpreter in interactive mode on a Windows computer, press Ctrl-Z
'gray36' 'gray37' 'gray38' (pressing both keys together) followed by Enter. On a Mac, Linux, or UNIX computer,
press Ctrl-D.
'gray39' 'gray40' 'gray42'
'gray43' 'gray44' 'gray45'
'gray46' 'gray47' 'gray48' N O TE : In Chapter 2, we will discuss the details of statements like the ones previously
shown. If you want to try them now in interactive mode, make sure you type them exactly
'gray49' 'gray50' 'gray51'
as shown.
'gray52' 'gray53' 'gray54'
'gray55' 'gray56' 'gray57'
'gray58' 'gray59' 'gray60' Writing Python Programs and Running
'gray61' 'gray62' 'gray63' Them in Script Mode
'gray64' 'gray65' 'gray66' Although interactive mode is useful for testing code, the statements that you enter in interac-
tive mode are not saved as a program. They are simply executed and their results displayed on
'gray67' 'gray68' 'gray69'
the screen. If you want to save a set of Python statements as a program, you save those state-
'gray70' 'gray71' 'gray72' ments in a file. Then, to execute the program, you use the Python interpreter in script mode.
'gray73' 'gray74' 'gray75' For example, suppose you want to write a Python program that displays the following three
'gray76' 'gray77' 'gray78' lines of text:
'gray79' 'gray80' 'gray81' Nudge nudge
'gray82' 'gray83' 'gray84' Wink wink
Know what I mean?
'gray85' 'gray86' 'gray87'
'gray88' 'gray89' 'gray90'
To write the program you would use a simple text editor like Notepad (which is installed
on all Windows computers) to create a file containing the following statements:
'gray91' 'gray92' 'gray93'
print('Nudge nudge')
'gray94' 'gray95' 'gray97'
print('Wink wink')
'gray98' 'gray99' print('Know what I mean?')
N O TE : It is possible to use a word processor to create a Python program, but you must
be sure to save the program as a plain text file. Otherwise, the Python interpreter will
not be able to read its contents.