Starting Out with Python, 5th Edition (Global Edition) PDF

Document Details

Uploaded by Deleted User

Haywood Community College

2021

Tony Gaddis

Tags

python programming computer programming programming language introduction to programming

Summary

This is a textbook on Python programming by Tony Gaddis, specifically tailored to a global audience. The fifth edition expands on content, discussing database programming, GUI programming, and function topics in greater detail. It's suitable for introductory programming courses or courses focusing on programming logic and design.

Full Transcript

This is a special edition of an established title widely used by colleges and GLOBAL universities throughout the world. Pearson published this exclusive edition for the benefit of students outsid...

This is a special edition of an established title widely used by colleges and GLOBAL universities throughout the world. Pearson published this exclusive edition for the benefit of students outside the United States and Canada. If you GLOBAL EDITION purchased this book within the United States or Canada, you should be aware EDITION EDITION GLOB AL that it has been imported without the approval of the Publisher or Author. Ideal for an introductory programming course or a programming logic and design course, Starting Out with Python® Starting Out with Python by Tony Gaddis helps students understand concepts and acquire problem-solving skills, without assuming any previous programming experience. The fifth edition retains the clear, friendly, and easy-to-understand writing that is the hallmark of the Starting Out With series. “In the Spotlight” case studies in each chapter provide detailed analysis of problems and show students how to solve these problems step by step. The book also presents example programs and programming exercises that are concise, practical, and designed to solidify students’ know-how. Highlights of the Fifth Edition New! A chapter on database programming introduces students to Structured Query Language (SQL) and Python database programming with SQLite. New! Relevant chapters have been updated with list, dictionary, and set comprehensions. Many new GUI programming topics have been introduced in Chapter 13, including internal and external padding, Listbox widgets, and scrollbars. Chapter 5 examines several function topics in greater detail. For instance, a discussion on the pass keyword has been added, and an expanded discussion on the value None has been presented. This edition also adopts the standard practice of conditionally executing the main function. String topics such as f-strings, string tokens, and string concatenation have been added and elaborated on. Starting Out with Python® EDITION FIFTH Available separately for purchase is MyLab Programming for Starting Out with Python, the teaching and learning platform that empowers instructors to personalize learning for every student. When combined with Pearson’s trusted educational content, this optional suite helps deliver the desired learning outcomes. FIFTH EDITION Gaddis Tony Gaddis CVR_GADD8637_05_GE_CVR_Vivar.indd 1 07/05/21 12:26 PM Digital Resources for Students Your new textbook provides 12-month access to digital resources that may include VideoNotes (step-by-step video tutorials on programming concepts), source code, and more. Refer to the preface in the textbook for a detailed list of resources. Follow the instructions below to register for the Companion Website for Tony Gaddis’s Starting Out with Python, Fifth Edition, Global Edition. 1. Go to www.pearsonglobaleditions.com. 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. ISSPYT-EMAIL-ALARY-CADET-SOTUN-DENSE 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 Pearson MyLab Programming, which is available at www.myprogramminglab.com for purchase. This access code can only be used once. This subscription is valid for 12 months upon activation and is not transferable. For technical support, go to https://support.pearson.com/getsupport. CVR_GADD8637_05_GE_CVR_IFC_IBC_uPDF.indd 1 07/05/21 12:29 PM STARTING OUT WITH Python ® A01_GADD8637_05_GE_FM.indd 1 05/05/2021 12:51 This page is intentionally left blank A01_GADD8637_05_GE_FM.indd 2 05/05/2021 12:51 STARTING OUT WITH Python ® FIFTH EDITION GLOBAL EDITION Tony Gaddis Haywood Community College A01_GADD8637_05_GE_FM.indd 3 05/05/2021 12:51 Please contact https://support.pearson.com/getsupport/s/ with any queries on this content. Microsoft and/or its respective suppliers make no representations about the suitability of the information contained in the documents and related graphics published as part of the services for any purpose. All such documents and related graphics are provided “as is” without warranty of any kind. Microsoft and/or its respective suppliers hereby disclaim all warranties and conditions with regard to this information, including all warranties and conditions of merchantability, 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 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 with the use or performance of information available from the services. The documents and related graphics contained herein could include technical inaccuracies or typographical errors. Changes are periodically added to the information herein. Microsoft and/or its respective suppliers may make improvements and/or changes in the product(s) and/or the program(s) described herein at any time. Partial screen shots may be viewed in full within the software version specified. Microsoft®, Windows®, and Excel® are registered trademarks of the Microsoft Corporation in the U.S.A. and other countries. This book is not sponsored or endorsed by or affiliated with the Microsoft Corporation. Acknowledgments of third-party content appear on the relevant page, which constitutes an extension of this copyright page. PEARSON, ALWAYS LEARNING, and MYLAB are exclusive trademarks owned by Pearson Education, Inc. or its affiliates in the U.S. and/or other countries. Pearson Education Limited KAO Two KAO Park Hockham Way Harlow CM17 9SR United Kingdom and Associated Companies throughout the world Visit us on the World Wide Web at: www.pearsonglobaleditions.com © Pearson Education Limited 2022 The rights of Tony Gaddis to be identified as the author of this work have been asserted by him in accordance with the Copyright, Designs and Patents Act 1988. Authorized adaptation from the United States edition, entitled Starting Out with Python, 5th Edition, ISBN 978-0-13- 592903-2 by Tony Gaddis published by Pearson Education © 2021. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, without either the prior written permission of the publisher or a license permitting restricted copying in the United Kingdom issued by the Copyright Licensing Agency Ltd, Saffron House, 6–10 Kirby Street, London EC1N 8TS. All trademarks used herein are the property of their respective owners. The use of any trademark in this text does not vest in the author or publisher any trademark ownership rights in such trademarks, nor does the use of such trademarks imply any affiliation with or endorsement of this book by such owners. For information regarding permissions, request forms, and the appropriate contacts within the Pearson Education Global Rights and Permissions department, please visit www.pearsoned.com/permissions. This eBook may be available as a standalone product or integrated with other Pearson digital products like MyLab and Mastering. This eBook may or may not include all assets that were part of the print version. The publisher reserves the right to remove any material in this eBook at any time. ISBN 10: 1-292-40863-4 ISBN 13: 978-1-292-40863-7 eBook ISBN 13: 978-1-292-40860-6 British Library Cataloguing-in-Publication Data A catalogue record for this book is available from the British Library 1 21 eBook formatted by B2R Technologies Pvt. Ltd. Contents at a Glance Preface   13 Chapter 1 Introduction to Computers and Programming 23 Chapter 2 Input, Processing, and Output 53 Chapter 3 Decision Structures and Boolean Logic 141 Chapter 4 Repetition Structures 191 Chapter 5 Functions 241 Chapter 6 Files and Exceptions 325 Chapter 7 Lists and Tuples 383 Chapter 8 More About Strings 453 Chapter 9 Dictionaries and Sets 489 Chapter 10 Classes and Object-Oriented Programming 543 Chapter 11 Inheritance 605 Chapter 12 Recursion 631 Chapter 13 GUI Programming 651 Chapter 14 Database Programming 739 Appendix A Installing Python 821 Appendix B Introduction to IDLE 825 Appendix C The ASCII Character Set 833 Appendix D Predefined Named Colors 835 Appendix E More About the import Statement 841 Appendix F Formatting Numeric Output with the format() Function 845 Appendix G Installing Modules with the pip Utility 851 Appendix H Answers to Checkpoints 853 Index 875 Credits 891 5 A01_GADD8637_05_GE_FM.indd 5 05/05/2021 12:51 This page is intentionally left blank A01_GADD8637_05_GE_FM.indd 6 05/05/2021 12:51 Contents Preface    13 Chapter 1 Introduction to Computers and Programming 23 1.1 Introduction 23 1.2 Hardware and Software 24 1.3 How Computers Store Data 29 1.4 How a Program Works 34 1.5 Using Python 42 Review Questions 46 Chapter 2 Input, Processing, and Output 53 2.1 Designing a Program 53 2.2 Input, Processing, and Output 57 2.3 Displaying Output with the print Function 58 2.4 Comments 61 2.5 Variables 62 2.6 Reading Input from the Keyboard 71 2.7 Performing Calculations 75 2.8 String Concatenation 87 2.9 More About the print Function 89 2.10 Displaying Formatted Output with F-strings 92 2.11 Named Constants 102 2.12 Introduction to Turtle Graphics 103 Review Questions 131 Programming Exercises 136 Chapter 3 Decision Structures and Boolean Logic 141 3.1 The if Statement 141 3.2 The if-else Statement 150 3.3 Comparing Strings 153 3.4 Nested Decision Structures and the if-elif-else Statement 157 3.5 Logical Operators 165 3.6 Boolean Variables 171 3.7 Turtle Graphics: Determining the State of the Turtle 172 Review Questions 180 Programming Exercises 183 7 A01_GADD8637_05_GE_FM.indd 7 05/05/2021 12:51 8 Contents Chapter 4 Repetition Structures 191 4.1 Introduction to Repetition Structures 191 4.2 The while Loop: A Condition-Controlled Loop 192 4.3 The for Loop: A Count-Controlled Loop 200 4.4 Calculating a Running Total 211 4.5 Sentinels 214 4.6 Input Validation Loops 217 4.7 Nested Loops 222 4.8 Turtle Graphics: Using Loops to Draw Designs 229 Review Questions 233 Programming Exercises 235 Chapter 5 Functions 241 5.1 Introduction to Functions 241 5.2 Defining and Calling a Void Function 244 5.3 Designing a Program to Use Functions 249 5.4 Local Variables 255 5.5 Passing Arguments to Functions 258 5.6 Global Variables and Global Constants 268 5.7 Introduction to Value-Returning Functions: Generating Random Numbers 272 5.8 Writing Your Own Value-Returning Functions 283 5.9 The math Module 296 5.10 Storing Functions in Modules 299 5.11 Turtle Graphics: Modularizing Code with Functions 305 Review Questions 311 Programming Exercises 316 Chapter 6 Files and Exceptions 325 6.1 Introduction to File Input and Output 325 6.2 Using Loops to Process Files 343 6.3 Processing Records 350 6.4 Exceptions 363 Review Questions 376 Programming Exercises 380 Chapter 7 Lists and Tuples 383 7.1 Sequences 383 7.2 Introduction to Lists 383 7.3 List Slicing 392 7.4 Finding Items in Lists with the in Operator 395 7.5 List Methods and Useful Built-in Functions 397 7.6 Copying Lists 404 7.7 Processing Lists 405 7.8 List Comprehensions 419 7.9 Two-Dimensional Lists 421 7.10 Tuples 426 7.11 Plotting List Data with the matplotlib Package 428 Review Questions 445 Programming Exercises 448 A01_GADD8637_05_GE_FM.indd 8 05/05/2021 12:51 Contents 9 Chapter 8 More About Strings 453 8.1 Basic String Operations 453 8.2 String Slicing 461 8.3 Testing, Searching, and Manipulating Strings 465 Review Questions 481 Programming Exercises 484 Chapter 9 Dictionaries and Sets 489 9.1 Dictionaries 489 9.2 Sets 515 9.3 Serializing Objects 528 Review Questions 534 Programming Exercises 539 Chapter 10 Classes and Object-Oriented Programming 543 10.1 Procedural and Object-Oriented Programming 543 10.2 Classes 547 10.3 Working with Instances 564 10.4 Techniques for Designing Classes 586 Review Questions 597 Programming Exercises 600 Chapter 11 Inheritance 605 11.1 Introduction to Inheritance 605 11.2 Polymorphism 620 Review Questions 626 Programming Exercises 628 Chapter 12 Recursion 631 12.1 Introduction to Recursion 631 12.2 Problem Solving with Recursion 634 12.3 Examples of Recursive Algorithms 638 Review Questions 646 Programming Exercises 648 Chapter 13 GUI Programming 651 13.1 Graphical User Interfaces 651 13.2 Using the tkinter Module 653 13.3 Displaying Text with Label Widgets 657 13.4 Organizing Widgets with Frames 667 13.5 Button Widgets and Info Dialog Boxes 669 13.6 Getting Input with the Entry Widget 673 13.7 Using Labels as Output Fields 676 13.8 Radio Buttons and Check Buttons 683 13.9 Listbox Widgets 690 13.10 Drawing Shapes with the Canvas Widget 709 Review Questions 732 Programming Exercises 735 A01_GADD8637_05_GE_FM.indd 9 05/05/2021 12:51 10 Contents Chapter 14 Database Programming 739 14.1 Database Management Systems 739 14.2 Tables, Rows, and Columns 741 14.3 Opening and Closing a Database Connection with SQLite 745 14.4 Creating and Deleting Tables 748 14.5 Adding Data to a Table 753 14.6 Querying Data with the SQL SELECT Statement 760 14.7 Updating and Deleting Existing Rows 775 14.8 More About Primary Keys 782 14.9 Handling Database Exceptions 785 14.10 CRUD Operations 788 14.11 Relational Data 796 Review Questions 812 Programming Exercises 818 Appendix A Installing Python 821 Appendix B Introduction to IDLE 825 Appendix C The ASCII Character Set 833 Appendix D Predefined Named Colors 835 Appendix E More About the import Statement 841 Appendix F Formatting Numeric Output with the format() Function 845 Appendix G Installing Modules with the pip Utility 851 Appendix H Answers to Checkpoints 853 Index 875 Credits 891 A01_GADD8637_05_GE_FM.indd 10 05/05/2021 12:51 LOCATION OF VIDEONOTES IN THE TEXT Chapter 1 Using Interactive Mode in IDLE, p. 45 Performing Exercise 2, p. 50 Chapter 2 The print Function, p. 58 Reading Input from the Keyboard, p. 71 Introduction to Turtle Graphics, p. 103 The Sales Prediction Problem, p. 136 Chapter 3 The if Statement, p. 141 The if-else Statement, p. 150 The Areas of Rectangles Problem, p. 183 Chapter 4 The while Loop, p. 192 The for Loop, p. 200 The Bug Collector Problem, p. 235 Chapter 5 Defining and Calling a Function, p. 244 Passing Arguments to a Function, p. 258 Writing a Value-Returning Function, p. 283 The Kilometer Converter Problem, p. 316 The Feet to Inches Problem, p. 318 Chapter 6 Using Loops to Process Files, p. 343 File Display, p. 380 Chapter 7 List Slicing, p. 392 The Lottery Number Generator Problem, p. 448 Chapter 8 The Vowels and Consonants problem, p. 485 Chapter 9 Introduction to Dictionaries, p. 489 Introduction to Sets, p. 515 The Capital Quiz Problem, p. 540 Chapter 10 Classes and Objects, p. 547 The Pet class, p. 600 Chapter 11 The Person and Customer Classes, p. 629 Chapter 12 The Recursive Multiplication Problem, p. 648 Chapter 13 Creating a Simple GUI application, p. 657 Responding to Button Clicks, p. 669 The Name and Address Problem, p. 735 Chapter 14 Opening and Closing a Database Connection, p. 745 Creating a Table, p. 748 Adding Data to a Table, p. 753 The SELECT Statement, p. 761 Updating Rows, p. 775 Getting Started with the Population Database Problem, p. 818 Appendix B Introduction to IDLE, p. 825 A01_GADD8637_05_GE_FM.indd 11 05/05/2021 12:51 This page is intentionally left blank A01_GADD8637_05_GE_FM.indd 12 05/05/2021 12:51 Preface Welcome to Starting Out with Python, Fifth Edition. This book uses the Python language to teach programming concepts and problem-solving skills, without assuming any previous programming experience. With easy-to-understand examples, pseudocode, flowcharts, and other tools, the student learns how to design the logic of programs then implement those programs using Python. This book is ideal for an introductory programming course or a programming logic and design course using Python as the language. As with all the books in the Starting Out With series, the hallmark of this text is its clear, friendly, and easy-to-understand writing. In addition, it is rich in example programs that are concise and practical. The programs in this book include short examples that highlight specific programming topics, as well as more involved examples that focus on problem solv- ing. Each chapter provides one or more case studies that provide step-by-step analysis of a specific problem and shows the student how to solve it. Control Structures First, Then Classes Python is a fully object-oriented programming language, but students do not have to under- stand object-oriented concepts to start programming in Python. This text first introduces the student to the fundamentals of data storage, input and output, control structures, functions, sequences and lists, file I/O, and objects that are created from standard library classes. Then the student learns to write classes, explores the topics of inheritance and polymorphism, and learns to write recursive functions. Finally, the student learns to develop simple event-driven GUI applications. Changes in the Fifth Edition This book’s clear writing style remains the same as in the previous edition. However, many additions and improvements have been made, which are summarized here: Database Programming – This edition adds a new chapter on database programming. Chapter 14 introduces the student to SQL and Python database programming with SQLite. Comprehension Expressions – This edition introduces and explains list comprehen- sions, dictionary comprehensions, and set comprehensions. 13 A01_GADD8637_05_GE_FM.indd 13 05/05/2021 12:51 14 Preface Updated String Topics – Several new string topics have been added. For example: o Throughout the text, this edition uses f-strings, which were introduced in Python 3.6, to display formatted output. F-strings use a concise and intuitive syntax and are easier to learn than the format function. The previous material on the format function has been moved to Appendix F. o A new discussion of string tokens has been added to Chapter 8. o A new example of reading and parsing CSV files has been added to Chapter 8. o The discussion of string concatenation in Chapter 2 has been expanded to include implicit concatenation of adjacent strings. GUI Programming – Several new GUI programming topics have been added to Chapter 13, including: o adding borders to widgets o internal and external padding o listbox widgets and scrollbars Turtle Graphics – Two commands for reading user input with dialog boxes have been introduced: o turtle.numinput o turtle.textinput Random List Element Selection – The random.choice() function is introduced in Chapter 7 as a way to randomly select list elements. New Function Topics – Several new topics have been added to Chapter 5. For example: o The pass keyword is introduced. o Expanded discussion of the value None, and why a function might return None. o This edition adopts the standard practice of conditionally executing the main function. Brief Overview of Each Chapter Chapter 1: Introduction to Computers and Programming This chapter begins by giving a very concrete and easy-to-understand explanation of how computers work, how data is stored and manipulated, and why we write programs in high- level languages. An introduction to Python, interactive mode, script mode, and the IDLE environment are also given. Chapter 2: Input, Processing, and Output This chapter introduces the program development cycle, variables, data types, and simple programs that are written as sequence structures. The student learns to write simple programs that read input from the keyboard, perform mathematical operations, and produce formatted screen output. Pseudocode and flowcharts are also introduced as tools for designing programs. The chapter also includes an optional introduction to the turtle graphics library. Chapter 3: Decision Structures and Boolean Logic In this chapter, the student learns about relational operators and Boolean expressions and is shown how to control the flow of a program with decision structures. The if, if-else, and A01_GADD8637_05_GE_FM.indd 14 05/05/2021 12:51 Preface 15 if-elif-else statements are covered. Nested decision structures and logical operators are discussed as well. The chapter also includes an optional turtle graphics section, with a discus- sion of how to use decision structures to test the state of the turtle. Chapter 4: Repetition Structures 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 techniques for writing input validation loops. The chapter also includes an optional section on using loops to draw designs with the turtle graphics library. Chapter 5: Functions In this chapter, the student first learns how to write and call void functions. The chapter shows the benefits of using functions to modularize programs and discusses the top-down design approach. Then, the student learns to pass arguments to functions. Common library functions, such as those for generating random numbers, are discussed. After learning how to call library functions and use their return value, the student learns to define and call his or her own functions. Then the student learns how to use modules to organize functions. An optional section includes a discussion of modularizing turtle graphics code with functions. Chapter 6: Files and Exceptions This chapter introduces sequential file input and output. The student learns to read and write large sets of data and store data as fields and records. The chapter concludes by discussing exceptions and shows the student how to write exception-handling code. Chapter 7: Lists and Tuples This chapter introduces the student to the concept of a sequence in Python and explores the use of two common Python sequences: lists and tuples. The student learns to use lists for arraylike operations, such as storing objects in a list, iterating over a list, searching for items in a list, and calculating the sum and average of items in a list. The chapter discusses list comprehension expressions, slicing, and many of the list methods. One- and two- dimensional lists are covered. The chapter also includes a discussion of the matplotlib package, and how to use it to plot charts and graphs from lists. Chapter 8: More About Strings In this chapter, the student learns to process strings at a detailed level. String slicing and ­algorithms that step through the individual characters in a string are discussed, and several built-in functions and string methods for character and text processing are introduced. This chapter also includes examples of string tokenizing and parsing CSV files. Chapter 9: Dictionaries and Sets This chapter introduces the dictionary and set data structures. The student learns to store data as key-value pairs in dictionaries, search for values, change existing values, add new A01_GADD8637_05_GE_FM.indd 15 05/05/2021 12:51 16 Preface key-value pairs, delete key-value pairs, and write dictionary comprehensions. The student learns to store values as unique elements in sets and perform common set operations such as union, intersection, difference, and symmetric difference. Set comprehensions are also introduced. The chapter concludes with a discussion of object serialization and introduces the student to the Python pickle module. Chapter 10: Classes and Object-Oriented Programming This chapter compares procedural and object-oriented programming practices. It covers the fundamental concepts of classes and objects. Attributes, methods, encapsulation and data hiding, _ _init_ _ functions (which are similar to constructors), accessors, and mutators are discussed. The student learns how to model classes with UML and how to find the classes in a particular problem. Chapter 11: Inheritance The study of classes continues in this chapter with the subjects of inheritance and polymor- phism. The topics covered include superclasses, subclasses, how _ _init_ _ functions work in inheritance, method overriding, and polymorphism. Chapter 12: Recursion This chapter discusses recursion and its use in problem solving. A visual trace of recursive calls is provided, and recursive applications are discussed. Recursive algorithms for many tasks are presented, such as finding factorials, finding a greatest common denominator (GCD), and sum- ming a range of values in a list, and the classic Towers of Hanoi example are presented. Chapter 13: GUI Programming This chapter discusses the basic aspects of designing a GUI application using the tkinter module in Python. Fundamental widgets, such as labels, buttons, entry fields, radio buttons, check buttons, list boxes, and dialog boxes, are covered. The student also learns how events work in a GUI application and how to write callback functions to handle events. The c­ hapter includes a discussion of the Canvas widget, and how to use it to draw lines, ­rectangles, ovals, arcs, polygons, and text. Chapter 14: Database Programming This chapter introduces the student to database programming. The chapter first introduces the basic concepts of databases, such as tables, rows, and primary keys. Then the student learns to use SQLite to connect to a database in Python. SQL is introduced and the student learns to execute queries and statements that search for rows, add new rows, update existing rows, and delete rows. CRUD applications are demonstrated, and the chapter concludes with a discussion of relational data. Appendix A: Installing Python This appendix explains how to download and install the latest Python distribution. A01_GADD8637_05_GE_FM.indd 16 05/05/2021 12:51 Preface 17 Appendix B: Introduction to IDLE This appendix gives an overview of the IDLE integrated development environment that comes with Python. Appendix C: The ASCII Character Set As a reference, this appendix lists the ASCII character set. Appendix D: Predefined Named Colors This appendix lists the predefined color names that can be used with the turtle graphics library, matplotlib and tkinter. Appendix E: More About the import Statement This appendix discusses various ways to use the import statement. For example, you can use the import statement to import a module, a class, a function, or to assign an alias to a module. Appendix F: Formatting Numeric Output with the format() Function This appendix discusses the format() function and shows how to use its format specifiers to control the way that numeric values are displayed. Appendix G: Installing Modules with the pip Utility This appendix discusses how to use the pip utility to install third-party modules from the Python Package Index, or PyPI. Appendix H: Answers to Checkpoints This appendix gives the answers to the Checkpoint questions that appear throughout the text. Organization of the Text The text teaches programming in a step-by-step manner. Each chapter covers a major set of topics and builds knowledge as students progress through the book. Although the chapters can be easily taught in their existing sequence, you do have some flexibility in the order that you wish to cover them. Figure P-1 shows chapter dependencies. Each box represents a chapter or a group of chapters. An arrow points from a chapter to the chapter that must be covered before it. A01_GADD8637_05_GE_FM.indd 17 05/05/2021 12:51 18 Preface Figure P-1 Chapter dependencies Chapters 1-5 (Cover in Order) Chapter 6 Chapter 8 Chapter 12 Files and Exceptions More About Strings Recursion Chapter 7 Lists and Tuples Chapter 9 Chapter 14 Dictionaries and Sets Database Programming Chapter 10 Classes and Object- Chapter 14 includes Oriented Programming one example that uses a GUI interface. Chapter 11 Chapter 13 Inheritance GUI Programming Features of the Text Concept Each major section of the text starts with a concept statement. Statements This statement concisely summarizes the main point of the section. Example Programs Each chapter has an abundant number of complete and partial example programs, each designed to highlight the current topic. In the Spotlight Each chapter has one or more In the Spotlight case studies that Case Studies provide detailed, step-by-step analysis of problems and show the student how to solve them. VideoNotes Online videos developed specifically for this book are avail- able for viewing at www.pearsonglobaleditions.com. Icons appear throughout the text alerting the student to videos about specific topics. A01_GADD8637_05_GE_FM.indd 18 05/05/2021 12:51 Preface 19 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. Tips Tips advise the student on the best techniques for approaching different 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 quickly after learning a new topic. Review Questions Each chapter presents a thorough and diverse set of review questions and exercises. They include Multiple Choice, True/ False, Algorithm Workbench, and Short Answer. Programming Each chapter offers a pool of programming exercises designed Exercises to solidify the student’s knowledge of the topics currently ­being studied. Supplements Student Online Resources Many student resources are available for this book from the publisher. The follow- ing items can be found on the Premium Companion Website of the book available at www.pearsonglobaleditions.com. The source code for each example program in the book Access to the book’s companion VideoNotes Instructor Resources The following supplements are available to qualified instructors only: Answers to all of the Review Questions Solutions for the Programming Exercises PowerPoint presentation slides for each chapter Test bank Visit the Pearson Education Instructor Resource Center (www.pearsonglobaleditions.com) or contact your local Pearson Education campus representative for information on how to access them. Acknowledgments I would like to thank the following faculty reviewers for their insight, expertise, and thought- ful recommendations: Paul Amer John Cavazos University of Delaware University of Delaware James Atlas Desmond K. H. Chun University of Delaware Chabot Community College James Carrier Sonya Dennis Guilford Technical Community College Morehouse College A01_GADD8637_05_GE_FM.indd 19 05/05/2021 12:51 20 Preface Barbara Goldner Janet Renwick North Seattle Community College University of Arkansas–Fort Smith Paul Gruhn Haris Ribic Manchester Community College SUNY at Binghamton Bob Husson Ken Robol Craven Community College Beaufort Community College Diane Innes Eric Shaffer Sandhills Community College University of Illinois at Urbana- Daniel Jinguji Champaign North Seattle Community College Tom Stokke John Kinuthia University of North Dakota Nazareth College of Rochester Anita Sutton Frank Liu Germanna Community College Sam Houston State University Ann Ford Tyson Gary Marrer Florida State University Glendale Community College Karen Ughetta Keith Mehl Virginia Western Community College Chabot College Christopher Urban Shyamal Mitra SUNY Institute of Technology University of Texas at Austin Nanette Veilleux Vince Offenback Simmons College North Seattle Community College Brent Wilson Smiljana Petrovic George Fox University Iona College Linda F. Wilson Raymond Pettit Texas Lutheran University Abilene Christian University I would like to thank the faculty, staff, and administration at Haywood Community College for the opportunity to build a career teaching the subjects that I love. I would also like to thank my family and friends for their support in all of my projects. It is a great honor to be published by Pearson, and I am extremely fortunate to have Tracy Johnson as my Editor and Content Manager. She and her colleagues Holly Stark, Erin Sullivan, ­Alicia Wilson, Scott Disanno, Carole Snyder, Bob Engelhardt, and Aishwarya Panday have worked tirelessly to produce and promote this book. Thanks to you all! Acknowledgments for the Global Edition Pearson would like to acknowledge and thank the following for the Global Edition: Contributors Reviewers Gregory Baatard Ayça Tüzmen Yıldırım Edith Cowan University Koç University Kenneth Eustace Charles Sturt University A01_GADD8637_05_GE_FM.indd 20 05/05/2021 12:51 Preface 21 About the Author Tony Gaddis is the principal author of the Starting Out With series of textbooks. Tony has nearly two decades of experience teaching computer science courses at Haywood Commu- nity 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 Excel- lence award from the National Institute for Staff and Organizational Development. The Starting Out with series includes introductory books covering C++, Java™, Visual C#®, Python®, and App Inventor, all published by Pearson. More information about all these books can be found at www.pearsonglobaleditions.com. A01_GADD8637_05_GE_FM.indd 21 05/05/2021 12:51 A01_GADD8637_05_GE_FM.indd 22 05/05/2021 12:51 Introduction to Computers CHAPTER 1 and Programming TOPICS 1.1 Introduction 1.4 How a Program Works 1.2 Hardware and Software 1.5 Using Python 1.3 How Computers Store Data 1.1 Introduction Think about some of the different ways that people use computers. In school, students use computers for tasks such as writing papers, searching for articles, sending email, and participating in online classes. At work, people use computers to analyze data, make pre- sentations, conduct business transactions, communicate with customers and coworkers, control machines in manufacturing facilities, and do many other things. At home, people use computers for tasks such as paying bills, shopping online, communicating with friends and family, and playing games. And don’t forget that cell phones, tablets, smart phones, car navigation systems, and many other devices are computers too. The uses of computers are almost limitless in our everyday lives. Computers can perform such a wide variety of tasks because they can be programmed. This means that computers are not designed to do just one job, but to do any job that their pro- grams tell them to do. A program is a set of instructions that a computer follows to perform a task. For example, Figure 1-1 shows screens using Microsoft Word and PowerPoint, two commonly used programs. Programs are commonly referred to as software. Software is essential to a computer because it controls everything the computer does. All of the software that we use to make our com- puters useful is created by individuals working as programmers or software developers. A 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 rewarding career. Today, you will find programmers’ work used in business, medicine, gov- ernment, law enforcement, agriculture, academics, entertainment, and many other fields. This book introduces you to the fundamental concepts of computer programming using the Python language. The Python language is a good choice for beginners because it is easy to learn 23 M01_GADD8637_05_GE_C01.indd 23 24/04/2021 11:48 24 Chapter 1   Introduction to Computers and Programming Figure 1-1 A word processing program and a presentation program 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, NASA, YouTube, various game companies, the New York Stock Exchange, and many others. Before we begin exploring the concepts of programming, you need to understand a few 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, we will discuss the physical components of which computers are commonly made. Next, we will look at how computers store data and execute programs. Finally, you will get a quick introduction to the software that you will use to write Python programs. 1.2 Hardware and Software 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 to as software. Hardware 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­ ther. Like the different instruments in a symphony orchestra, each device in a computer plays its own part. If you have ever shopped for a computer, you’ve probably seen sales literature listing compo- nents such as microprocessors, memory, disk drives, video displays, graphics cards, and so on. 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 typical computer system consists of the following major components: The central processing unit (CPU) Main memory M01_GADD8637_05_GE_C01.indd 24 24/04/2021 11:48 1.2 Hardware and Software 25 Figure 1-2 Typical components of a computer system Nikita Rogul/ Shutterstock Central Processing Shutterstock Art gallery/ Unit Iko/Shutterstock Shutterstock Feng Yu/Shutterstock Output Aquila/ Devices Chiyacat/ Shutterstock Shutterstock Peter Guess/ Input Devices Jocic/Shutterstock Elkostas/Shutterstock Main Memory (RAM) Tkemot/Shutterstock Secondary StockPhotosArt/Shutterstock Storage Devices Kastianz/Shutterstock Andre Nitsievsky/Shutterstock. Secondary storage devices Input devices Output devices Let’s take a closer look at each of these components. The CPU When a computer is performing the tasks that a program tells it to do, we say that the computer is running or executing the program. The central processing unit, or CPU, is the part of a computer that actually runs programs. The CPU is the most important component in a computer because without it, the computer could not run software. In the earliest computers, CPUs were huge devices made of electrical and mechanical com- ponents such as vacuum tubes and switches. Figure 1-3 shows such a device. The two women in the photo are working with the historic ENIAC computer. The ENIAC, which 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 primarily one big CPU, was 8 feet tall, 100 feet long, and weighed 30 tons. Today, CPUs are small chips known as microprocessors. Figure 1-4 shows a photo of a lab 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. M01_GADD8637_05_GE_C01.indd 25 24/04/2021 11:48 26 Chapter 1   Introduction to Computers and Programming Figure 1-3 The ENIAC computer courtesy of U.S. Army Historic Computer Images Figure 1-4 A lab technician holds a modern microprocessor Creativa Images/Shutterstock M01_GADD8637_05_GE_C01.indd 26 24/04/2021 11:48 1.2 Hardware and Software 27 Main Memory 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 working with. For example, suppose you are using a word processing program to write an essay for one of your classes. While you do this, both the word processing program and the essay are stored in main memory. Main memory is commonly known as random-access memory, or RAM. It is called this because the CPU is able to quickly access data stored at any random location in RAM. RAM is usually a volatile type of memory that is used only for temporary storage while 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. Figure 1-5 Memory chips Garsya/Shutterstock Secondary Storage Devices Secondary storage is a type of memory that can hold data for long periods of time, even 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 documents, payroll data, and inventory records, is saved to secondary storage as well. The most common type of secondary storage device is the disk drive. A traditional disk drive stores data by magnetically encoding it onto a spinning circular disk. Solid-state 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 computers have some sort of secondary storage device, either a traditional disk drive or a solid-state drive, mounted inside their case. External storage devices, which connect to one of the computer’s communication ports, are also available. External storage devices can be used to create backup copies of important data or to move data to another computer. In addition to external storage devices, many types of devices have been created for copy- ing data and for moving it to other computers. For example, USB drives are small devices 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 special type of memory known as flash memory. USB drives, which are also known as memory sticks and flash drives, are inexpensive, reliable, and small enough to be carried in your pocket. M01_GADD8637_05_GE_C01.indd 27 24/04/2021 11:48 28 Chapter 1   Introduction to Computers and Programming Input Devices Input is any data the computer collects from people and from other devices. The com- ponent that collects the data and sends it to the computer is called an input device. Common input devices are the keyboard, mouse, touchscreen, scanner, microphone, and digital camera. Disk drives and optical drives can also be considered input devices, because programs and data are retrieved from them and loaded into the computer’s memory. Output Devices Output is any data the computer produces for people or for other devices. It might be a sales report, a list of names, or a graphic image. The data is sent to an output device, which formats and presents it. Common output devices are video displays and printers. Disk drives can also be considered output devices because the system sends data to them in order to be saved. Software If a computer is to function, software is not optional. Everything computer does, from the time you turn the power switch on until you shut the system down, is under the control of software. There are two general categories of software: system software and application software. Most computer programs clearly fit into one of these two categories. Let’s take a closer look at each. System Software The programs that control and manage the basic operations of a computer are generally referred to as system software. System software typically includes the following types of programs: Operating Systems An operating system is the most fundamental set of programs on a computer. The operating system controls the internal operations of the computer’s hardware, manages all of the devices connected to the computer, allows data to be saved to and retrieved from storage devices, and allows other programs to run on the computer. Popular operating systems for laptop and desktop computers include Windows, macOS, and Linux. Popular operating systems for mobile devices include Android and iOS. Utility Programs A utility program performs a specialized task that enhances the com- puter’s operation or safeguards data. Examples of utility programs are virus scanners, file compression programs, and data backup programs. Software Development Tools Software development tools are the programs that pro- grammers use to create, modify, and test software. Assemblers, compilers, and interpret- ers are examples of programs that fall into this category. M01_GADD8637_05_GE_C01.indd 28 24/04/2021 11:48 1.3 How Computers Store Data 29 Application Software 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 their computers. Figure 1-1, at the beginning of this chapter, shows screens from two com- monly used applications: Microsoft Word, a word processing program, and PowerPoint, a presentation program. Some other examples of application software are spreadsheet pro- grams, email programs, web browsers, and game programs. Checkpoint 1.1 What is a program? 1.2 What is hardware? 1.3 List the five major components of a computer system. 1.4 What part of the computer actually runs programs? 1.5 What part of the computer serves as a work area to store a program and its data while the program is running? 1.6 What part of the computer holds data for long periods of time, even when there is no power to the computer? 1.7 What part of the computer collects data from people and from other devices? 1.8 What part of the computer formats and presents data for people or other devices? 1.9 What fundamental set of programs control the internal operations of the computer’s hardware? 1.10 What do you call a program that performs a specialized task, such as a virus scanner, a file compression program, or a data backup program? 1.11 Word processing programs, spreadsheet programs, email programs, web browsers, and game programs belong to what category of software? 1.3 How Computers Store Data CONCEPT: All data that is stored in a computer is converted to sequences of 0s and 1s. A computer’s memory is divided into tiny storage locations known as bytes. One byte is only enough memory to store a letter of the alphabet or a small number. In order to do anything meaningful, a computer has to have lots of bytes. Most computers today have millions, or even billions, of bytes of memory. Each byte is divided into eight smaller storage locations known as bits. The term bit stands for binary digit. Computer scientists usually think of bits as tiny switches that can be either on or off. Bits aren’t actual “switches,” however, at least not in the conventional M01_GADD8637_05_GE_C01.indd 29 24/04/2021 11:48 30 Chapter 1   Introduction to Computers and Programming sense. In most computer systems, bits are tiny electrical components that can hold either a positive or a negative charge. Computer scientists think of a positive charge as a switch in the on position, and a negative charge as a switch in the off position. Figure 1-6 shows the way that a computer scientist might think of a byte of memory: as a collection of switches that are each flipped to either the on or off position. Figure 1-6 Think of a byte as eight switches ON ON ON ON OFF OFF OFF OFF When a piece of data is stored in a byte, the computer sets the eight bits to an on/ off pattern that represents the data. For example, the pattern on the left in Figure 1-7 shows how the number 77 would be stored in a byte, and the pattern on the right shows how the letter A would be stored in a byte. We explain below how these patterns are determined. Figure 1-7 Bit patterns for the number 77 and the letter A ON ON ON ON ON ON OFF OFF OFF OFF OFF OFF OFF OFF OFF OFF The number 77 stored in a byte. The letter A stored in a byte. Storing Numbers A bit can be used in a very limited way to represent numbers. Depending on whether the bit is turned on or off, it can represent one of two different values. In computer systems, a bit that is turned off represents the number 0, and a bit that is turned on represents the num- ber 1. This corresponds perfectly to the binary numbering system. In the binary numbering system (or binary, as it is usually called), all numeric values are written as sequences of 0s and 1s. Here is an example of a number that is written in binary: 10011101 M01_GADD8637_05_GE_C01.indd 30 24/04/2021 11:48 1.3 How Computers Store Data 31 The position of each digit in a binary number has a value assigned to it. Starting with the rightmost digit and moving left, the position values are 20, 21, 22, 23, and so forth, as shown in Figure 1-8. Figure 1-9 shows the same diagram with the position values calcu- lated. Starting with the rightmost digit and moving left, the position values are 1, 2, 4, 8, and so forth. Figure 1-8 The values of binary digits as powers of 2 10011101 20 21 22 23 24 25 26 27 Figure 1-9 The values of binary digits 10011101 1 2 4 8 16 32 64 128 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, 16, and 128. This is shown in Figure 1-10. The sum of all of these position values is 157. So, the value of the binary number 10011101 is 157. Figure 1-10 Determining the value of 10011101 10011101 1 4 8 16 128 1 + 4 + 8 + 16 + 128 = 157 M01_GADD8637_05_GE_C01.indd 31 24/04/2021 11:48 32 Chapter 1   Introduction to Computers and Programming Figure 1-11 shows how you can picture the number 157 stored in a byte of memory. Each 1 is represented by a bit in the on position, and each 0 is represented by a bit in the off position. Figure 1-11 The bit pattern for 157 1 1 1 1 1 0 0 0 Position values 128 64 32 16 8 4 2 1 128 + 16 + 8 + 4 + 1 = 157 When all of the bits in a byte are set to 0 (turned off), then the value of the byte is 0. When all of the bits in a byte are set to 1 (turned on), then the byte holds the largest value that can be stored in it. The largest value that can be stored in a byte is 1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = 255. This limit exists because there are only eight bits in a byte. What if you need to store a number larger than 255? The answer is simple: use more than one byte. For example, suppose we put two bytes together. That gives us 16 bits. The posi- tion values of those 16 bits would be 20, 21, 22, 23, and so forth, up through 215. As shown in Figure 1-12, the maximum value that can be stored in two bytes is 65,535. If you need to store a number larger than this, then more bytes are necessary. Figure 1-12 Two bytes used for a large number 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 Position values 32768 16384 8192 4096 2048 1024 512 256 128 64 32 16 8 4 2 1 32768 + 16384 + 8192 + 4096 + 2048 + 1024 + 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 65535 TIP: In case you’re feeling overwhelmed by all this, relax! You will not have to actu- ally convert numbers to binary while programming. Knowing that this process is taking place inside the computer will help you as you learn, and in the long term this knowl- edge will make you a better programmer. M01_GADD8637_05_GE_C01.indd 32 24/04/2021 11:48 1.3 How Computers Store Data 33 Storing Characters Any piece of data that is stored in a computer’s memory must be stored as a binary num- ber. That includes characters, such as letters and punctuation marks. When a character is stored in memory, it is first converted to a numeric code. The numeric code is then stored in memory as a binary number. Over the years, different coding schemes have been developed to represent characters in computer memory. Historically, the most important of these coding schemes is ASCII, 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 other characters. For example, the ASCII code for the uppercase letter A is 65. When you type an uppercase A on your computer keyboard, the number 65 is stored in memory (as a binary number, of course). This is shown in Figure 1-13. Figure 1-13 The letter A is stored in memory as the number 65 1 1 A 65 0 0 0 0 0 0 TIP: The acronym ASCII is pronounced “askee.” In case you are curious, the ASCII code for uppercase B is 66, for uppercase C is 67, and so forth. Appendix C shows all of the ASCII codes and the characters they represent. The ASCII character set was developed in the early 1960s and was eventually adopted by almost all computer manufacturers. ASCII is limited, however, because it defines codes for only 128 characters. To remedy this, the Unicode character set was developed in the early 1990s. Unicode is an extensive encoding scheme that is compatible with ASCII, but can 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. Advanced Number Storage Earlier, you read about numbers and how they are stored in memory. While reading that 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.14159) cannot be represented using the simple binary numbering technique we discussed. Computers are able to store negative numbers and real numbers in memory, but to do so 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. M01_GADD8637_05_GE_C01.indd 33 24/04/2021 11:48 34 Chapter 1   Introduction to Computers and Programming Other Types of Data Computers are often referred to as digital devices. The term digital can be used to describe anything that uses binary numbers. Digital data is data that is stored in binary format, and a digital device is any device that works with binary data. In this section, we have discussed how numbers and characters are stored in binary, but computers also work with many other types of digital data. For example, consider the pictures that you take with your digital camera. These images are composed of tiny dots of color known as pixels. (The term pixel stands for picture element.) As show

Use Quizgecko on...
Browser
Browser