ebook img

Python for Everyone 3rd Ed PDF

761 Pages·3·12.396 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Python for Everyone 3rd Ed

Python for Everyone 3/e Cay Horstmann Rance Necaise Cay Horstmann San Jose State University Rance Necaise Randolph-Macon College Python for Everyone 3/e VICE PRESIDENT AND EXECUTIVE PUBLISHER Laurie Rosatone EXECUTIVE EDITOR Joanna Dingle PROJECT MANAGER/DEVELOPMENT EDITOR Cindy Johnson EDITORIAL ASSISTANT Crystal Franks LEAD PRODUCT DESIGNER Tom Kulesa MARKETING MANAGER Michael MacDougald PRODUCTION MANAGER Nichole Urban PRODUCTION MANAGER Nicole Repasky PRODUCTION MANAGEMENT SERVICES Cindy Johnson, Publishing Services PHOTO EDITOR Anindita Adiyal COVER DESIGNER Joanna Vieira COVER PHOTOS (castle) © Tom Watson/EyeEm/Getty Images; (chalice) © Paul Fleet/Getty Images, Inc.; (balloon) © Mikhail Mishchenko/123RFLimited; (trumpets) © modella/123RF.com. This book was set in 10.5/12 Stempel Garamond LT Std by Publishing Services, and printed and bound by Quad Graphics/Versailles. The cover was printed by Quad Graphics/Versailles. Founded in 1807, John Wiley & Sons, Inc. has been a valued source of knowledge and understanding for more than 200 years, helping people around the world meet their needs and fulfill their aspirations. Our company is built on a foundation of principles that include responsibility to the communities we serve and where we live and work. In 2008, we launched a Corporate Citizenship Initiative, a global effort to address the environmental, social, eco- nomic, and ethical challenges we face in our business. Among the issues we are addressing are carbon impact, paper specifications and procurement, ethical conduct within our business and among our vendors, and community and charitable support. For more informationo, op lease visit our website: www.wiley.com/go/citizenship. This book is printed on acid-free paper. Copyright © 2019, 2016 John Wiley & Sons, Inc. All rights reserved. No part of this publication may be repro- duced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photo- copying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, Inc., 222 Rosewood Drive, Dan- vers, MA 01923, (978) 750-8400, fax (978) 646-8600, or on the Web at www.copyright.com. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, (201) 748-6011, fax (201) 748-6008. Evaluation copies are provided to qualified academics and professionals for review purposes only, for use in their courses during the next academic year. These copies are licensed and may not be sold or transferred to a third party. Upon completion of the review period, please return the evaluation copy to Wiley. Return instruc- tions and a free of charge return shipping label are available at: www.wiley.com/go/returnlabel. If you have chosen to adopt this textbook for use in your course, please accept this book as your complimentary desk copy. Outside of the United States, please contact your local representative. ePUB ISBN 978-1-119-49853-7 Printed in the United States of America. The inside back cover will contain printing identification and country of origin if omitted from this page. In addition, if the ISBN on the back cover differs from the ISBN on this page, the one on the back cover is correct. 10 9 8 7 6 5 4 3 2 1 PREFACE This book is an introduction to computer programming using Python that focuses on the essentials—and on effective learning. Designed to serve a wide range of student interests and abilities, it is suitable for a first course in programming for computer scientists, engineers, and students in other disciplines. No prior programming expe- rience is required, and only a modest amount of high school algebra is needed. For pedagogical reasons, the book uses Python 3, which is more regular than Python 2. PreHseerne ta rfeu tnhed abmooekn’st kaelsy fefiartsutr.e s: The book takes a traditional route, first stressing control structures, functions, procedural decomposition, and the built-in data structures. Objects are used when appropriate in the early chapters. Students start designing and implementing their Gowunid calanscsees a inn dC hwapotrekre 9d. examples help students succeed. Beginning programmers often ask “How do I start? Now what do I do?” Of course, an activity as complex as programming cannot be reduced to cookbook-style instructions. However, step-by-step guidance is immensely helpful for building con- fidence and providing an outline for the task at hand. “Problem Solving” sections stress the importance of design and planning. “How To” guides help students with common programming tasks. Numerous “Worked Examples” demonstrate how to aPprpolbyl cehmap steorl vcoinncge psttsr atot eingtieerse satirneg mpraodblee mexs.p licit. Practical, step-by-step illustrations of techniques help students devise and evaluate solutions to programming problems. Introduced where they are most relevant, these strategies address barriers to success for many students. Strategies included are: • Algorithm Design (with pseudocode) • Stepwise Refinement • First Do It By Hand (doing sample • Adapting Algorithms calculations by hand) • Discovering Algorithms by • Flowcharts Manipulating Physical Objects • Test Cases • Tracing Objects • Hand-Tracing • Patterns for Object Data • Storyboards • Thinking Recursively • Solve a Simpler Problem First • Estimating the Running Time of Practice makes perfect. an Algorithm • Reusable Functions Of course, programming students need to be able to implement nontrivial programs, but they first need to have the confidence that they can succeed. Each section con- tains numerous exercises that ask students to carry out progressively more complex tasks: trace code and understand its effects, produce program snippets from prepared parts, and complete simple programs. Additional review and programming problems are provided at the end of each chapter. iii iv Preface A visual approach motivates the reader and eases navigation. Photographs present visual analogies that explain the o. ot h nature and behavior of computer concepts. Step-by- p k c step figures illustrate complex program operations. Sto Syntax boxes and example tables present a variety er/i or of typical and special cases in a compact format. It pl x a is easy to get the “lay of the land” by browsing the err Fvioscuualss , obnef othree f oecsusseinngt ioanl sth we theixlteu able minagte rial. © T technically accurate. Visual features help the reader with navigation. An encyclopedic coverage is not helpful for a begin- ning programmer, but neither is the opposite— reducing the material to a list of simplistic bullet points. In this book, the essentials are presented in digestible chunks, with separate notes that go deeper into good prac- tices or language features when the reader is ready for the additional information. New to This Edition Interactive Learning With this edition, interactive content is front and center. Immersive activities integrate with this text and engage students in activities designed to foster in-depth learning. Students don’t just watch animations and code traces, they work on generating them. Live code samples invite the reader to experiment and to learn programming con- structs first hand. The activities provide instant feedback to show students what Ath eFyo dcidu rsi gohnt a Dnda wtah eSrcei tehnecy en eed to study more. The methods of data science are becoming so important that students in many disciplines, and not just computer scientists, are eager to learn the fundamentals of programming. Python is uniquely positioned as the “go to” language for budding data scientists, due to its logical structure, interactive programming libraries that invite exploration, and a wealth of libraries for data manipulation. This book employs a proven pedagogy for teaching programming that is not lim- ited to computer science majors. In this edition, we provide additional examples and eJuxesrtc itshees tRhaigt fhotc uAsm ono vuanrito uosf a Pspyethctos nof data science. When we wrote this book, our goal was to teach good programming and computer science, using Python as the means of instruction and not an end in itself. Following suggestions of users of prior editions, we accelerated the coverage of cMoonvreen Tieoncoel bopoexreatsio ns for working with strings and lists in this edition. A popular enhancement of the previous edition was the introduction of optional “Toolbox” sections that introduce useful packages in the wonderful ecosystem of Python libraries. Students are empowered to perform useful work such as statistical Preface v computations, drawing graphs and charts, sending e-mail, processing spreadsheets, and analyzing web pages. The libraries are placed in the context of computer sci- ence principles, and students learn how those principles apply to solving real-world problems. Each Toolbox is accompanied by many new end-of-chapter review and programming exercises. New to this edition are additional Toolboxes on turtle graphics and game programming. A Tour of the Book Figure 1 shows the dependencies between the chapters and how topics are organized. The core material of the book is Chapters 1–8. Chapters 9 and 10 cover object- oriented programming, and Chapters 11 and 12 support a course that goes more Appendices deeply into algorithm design and analysis. Six appendices provide a handy reference for students on operator pGrreacpedheinccse ,a rnesde rIvmeda wgoer dPsr,o Ucneicsosdien, gth e Python standard library, and more. Writing programs that create drawings or process images can provide students with effective visualizations of complex topics. Chapter 2 introduces the EzGraphics open-source library and how to use it to create basic graphical drawings. The library, Fundamentals 1. Introduction Object-Oriented Programming Data Structures & Algorithms 2. Programming with Numbers and Strings 3. Decisions 4. Loops A gentle 5. Functions introduction to recursion is optional. Sections 6.1 – 6.3 Sections 7.1 and 7.2 6.6 I.t eLriasttiso n (lists) can be covered (text file processing) can be with Chapter 4. covered with Chapter 4. 7. Files and 8. Sets and 9. Objects Exceptions D6i.c tItioernaatriioens and Classes 11. Recursion Figure 1 10. Inheritance 12. Sorting and Searching Chapter Dependencies vi Preface which students find easier to use than Python’s standard Tkinter library, also supports simple image processing. Chapter 5 contains an optional Toolbox on turtle graphics. Graphics Worked Examples and exercises are provided throughout the text, all of wExheicrhc aisree osp tional. End-of-chapter exercises contain a broad mix of review and programming questions, with optional questions from graphics, science, and business. Designed to engage sIntutdeernatcs,t tihvee eexTerecxiste sD ilelussitgrantee dth feo vra lPureo ogf praromgrmaminmgin Sg tiun dapepnlitesd fields. wiley.com vitalsource.com Available online through , , or at your local bookstore, the interactive eText features integrated student coding activities that foster in-depth learning. Designed by Cay Horstmann, these activities provide instant feedback to show students what they did right and where they need to study more. Students do http://wiley. more than just watch animations and code traces; they work on generating them right com/college/sc/horstmann in the eText environment. For a preview of these activities, check out . Customized formats are also available in both print and digital formats and pro- vide your students with curated content based on your unique syllabus. Please contact your Wiley sales rep for more information about any of these oWpetibon Rs.e sources www.wiley. com/go/pfe3 This book is complemented by a complete suite of online resources. Go to to visit the online companion sites, which include • Source code for all example programs, Toolboxes, and Worked Examples in the book. • Lecture presentation slides (for instructors only). • Solutions to all end-of-chapter review and programming exercises (for instructors only). • A test bank that focuses on skills, not just terminology (for instructors only). This extensive set of multiple-choice questions can be used with a word processor or imported into a course management system. ® • CodeCheck , an innovative online service that allows instructors to design their own automatically graded programming exercises. Walkthrough vii A Walkthrough of the Learning Aids The pedagogical elements in this book work together to focus on and reinforce key concepts and fundamental principles of programming, with additional tips and detail organized to support and deepen these fundamentals. In addition to traditional fea- tures, such as chapter objectives and a wealth of exercises, each chapter contains ele- ments geared to today’s visual learner. 1.5 Analyzing Your First Program 11 1.5 Analyzing Your First Program In this section, we will analyze the first Python program in detail. Here again is the manda Rohde/iStockphoto. scoed12ce 0:#p 4r /iMhntye( lf"liHroes.tlp lPyoy, t hWoonr lpdr!o"g)r am. statements Throughout each chapter, © A bAe P #ty rtMahyno sfnlia rptsertod g Parynatdhmo en cx operncoutgatrieanmds. b oyn teh oer P mytohroen li innetse ropf rinetsetrru. Tchtieo nfisr sotr l ine that will margin notes show where A comment provides comment # information to the new concepts are introduced programmer. itsiv ae informati.o Cno tmo mtheen tpsr boeggrianm wmitehr . Caonmdm aeren tnso wt isltla bteem deisnctus.s Tsehde yin p mroovridee d deetsacirl iipn- and provide an outline of key ideas. SecpTtrhiioenn ts (2e"c.H1oe.n5lld. o l,i nWeo rclodn!t"a)in s a statement A function is ian csotrlulecctitoionns of that prints or displaypsr ai nlitn e of text, namely “Hello, World!”. In this statefumnecntito, nw e that perform a call a function named and pass it the information to be displayed. A is particular task. a collection of programming instructions that carry out a particular task. We do not have to implement this function, it is part of the Python language. We simply want Abfuy fn uscpntiecotcniiof nynia nimsg c eta hallene dd the1T f.ou unsceti,o onr tcoa pll,e ar ffournmct iitosn i ninte Pnydtehdo nta, ysko,u n naemeedl yto t osp perciinfyt :a pvrailnute. its arguments. 2. The name of the function you want to usaer g(iunm theinst case, )". Hello, World!" Annotated syntax boxes Any values the function needs to carry out its task (in this case, ). The technical term for such a value is an . Arguments are enclosed in provide a quick, visual overview parentheses; multiple arguments are separated by commas. The number of arguments required depends on the function. of new language constructs. Syntax 1.1 print Statement Syntax print() print(value, value, ..., valuen) 1 2 Annotations explain required Aarlle a grigvuemne, nat bs laarnek o lpintieo nisa lp. rIifn ntoe da.r guments components and point to more print("The answer is", 6 + 7, "!") information on common errors The values to be printed, or best practices associated one after the other, separated by a blank space. with the syntax. Analogies to everyday objects are used to explain the nature and behavior of concepts such as variables, data Like a variable in a computer types, loops, and more. program, a parking space has an identifier and a contents. viii Walkthrough Memorable photos reinforce analogies and help students remember the concepts. pie(fruit) pie(fruit) A recipe for a fruit pie may say to use any kind of fruit. Here, “fruit” is an example of a parameter variable. Apples and cherries are examples of arguments. Problem Solving sections teach techniques for generating ideas and 6.6 Problem Solving: Discovering Algorithms by Manipulating Physical Objects 311 evaluating proposed solutions, often using pencil and paper or other Now how does that help us with our problem, switching the first and the second artifacts. These sections emphasize half of the list? that most of the planning and problem Let’s put the first coin into place, by swapping it with the fifth coin. However, as Python programmers, we will say that we swap the coins in positions 0 and 4: solving that makes students successful happens away from the computer. HOW TO 1.1 Describing an Algorithm with Pseudocode How To guides give step-by-step guidance for common programming This is the first of many “How To” sections in this book that give you step-by-step proce- dures for carrying out important tasks in developing computer programs. tasks, emphasizing planning and Before you are ready to write a program in Python, you need to develop an algorithm—a mPreothboledm fo rS atrartievminge natt a solution for a particular problem. Describe the algorithm in pseudo- testing. They answer the beginner’s code: a sequence of precise steps formulated in English. question, “Now what do I do?” and You have the choice of buying two cars. One is more fuel efficient than the other, but also more expensive. integrate key concepts into a You know the price and fuel efficiency (in miles per gallon, mpg) of both cars. You plan to keep the car for ten years. Assume a problem-solving sequence. price of $4 per gallon of gas and usage of 15,000 miles per year. You will pay cash for the car and not worry about financing costs. © David H. Lewis/Getty Images. Which car is the better deal? Step 1 Determine the inputs and outputs. In opuurr cshaamsep lper ipcreo1b lemf, uweel e hffaivceie tnhceys1e inputs: Worked Examples apply • WORKaEnDd EXAMPLE, the1 p.1ri ce and fuel efficiency (in mpg) of the first car Writing an Algorithm for Tiling a Floor the steps in the How To to a di erent example, showing Problem Statement Make a pla×n for tiling a rectangular bathroom floor with alternating how they can be used to black and white tiles measuring 4 4 inches. The floor dimensions, measured in inches, are plan, implement, and test Step 1 multiples of 4. a solution to another Determine the inputs and outputs. × The inputs are the floor dimensions (length width), programming problem. Step 2 measured in inches. The output is a tiled floor. Break down the problem into smaller tasks. A natural subtask is to lay one row of tiles. If you can solve that, then you can solve the problem by laying © kilukilu/Shutterstock. one row next to the other, starting from a wall, until you reach the opposite wall. How do you lay a row? Start witEh a txile aat onmew widatllh. p/ 4le tables support beginners If it is white, put a black one next to it. If it is black, put a white one next to it. Keep going until Table1 NSutmepb 3e r Lyiotue rreaachls th ien o pPpoystithe woanll. The row willcontwaiinth mutilltes. iple,concrete examples. Describe each subtask in pseudocode. Number Type In tWPhlaehc iplCee s aoteh bmeula fdmlcookoe ctrnio liestd n ineo ,tt hy yeoe ntu fo iwlrltehadw,n retes ptteo cao btr tnehe mer .f oolrloew piTnrge csh isteeep as: bsoeu t texaabctlylweshe repthoe tiinlest ar oe pulatce cd.ommon 6 int Repeat this step width / 4 – 1 times: errors and present another quick –6 int An integer has no fractional part. reference to the section’s topic. 0 int Integers can be negative. 0.5 float Zero is an integer. float 1.0 float A number with a fractional part has type flo. at 1E6 float An integer with a fractional part .0 has type . 6 float 2.96E-2 float AN unmumbebresr i inn e exxppoonneennttiiaall n noottaattiioonn a: 1lw ×a 1y0s hoarv e1 0ty0p0e0 00. . Optional graphics programming 100,000 ENrreogra: tive exponent: 2.96 × 10–2 = 2.96 / 100 = 0.0296 examples demonstrate constructs 3 1/2 Error: Do not use a comma as a decimal separator. with engaging drawings, visually Do not use fractions; use decimal notation: 3.5. reinforcing programming concepts.

See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.