ebook img

Python for Everyone PDF

724 Pages·2013·95.239 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

HORSTMANN + NECAISE = N H c Ay H O R S T M A N N A WHOLE NEW WAY TO LEARN PROGRAMMING WITH PYTHON! e O c R A S i T RANce D. NecAiSe This exciting new text by Cay Horstmann and Rance Necaise provides an introduction to programming S M e using Python that focuses on the essentials and on the problem-solving skills all good programmers A need to be successful. Suitable for a first course in programming for students in computer science, N engineering, scientific, or liberal arts disciplines, it requires no prior programming experience. N KEY FEATURES • A visual approach motivates the reader and eases navigation. Abundant illustrations and photographs make concepts memorable. Syntax boxes annotate code examples to present a visual summary of key points. • G uidance and worked examples help students succeed. Step-by-step “how-to” boxes guide p students through the implementation of core concepts. Worked examples apply these steps to new y problems. “Tips” and “Common Errors” boxes guide students to good practice. Python T • Practice makes perfect. Abundant practice tools build student confidence and skills. Self checks H in each section test understanding and point students to exercises they can do to practice what they O learned. N • Teaches computer science principles, not just Python. The core of the book builds students’ skills in control flow, loops, functions, lists, file I/O, sets, and dictionaries before addressing classes F and inheritance. O R F O R E V E R Y O N E • A focus on problem solving. Problem-solving sections provide techniques for planning and E evaluating solutions—before starting to code. These include the use of psuedocode for algorithm V design, hand-tracing code segments, storyboards and more. E R Y O N CAY S. HORSTMANN is a Professor of Computer Science in the Department of Computer Science at San E Jose State University. He is an experienced professional programmer, having worked as Vice President and Chief Technology Officer for an internet startup and as a consultant for major corporations, univer- sities, and organizations. Horstmann is the author of many successful professional and academic books, including Big Java, Big Java: Late Objects, Big C++, and C++ for Everyone —all with Wiley. RANCE D. NECAISE is a member of the faculty in the Department of Computer Science at The College of William and Mary. He has over 22 years of teaching experience across a broad range of the computer science discipline. Necaise is also the author of Data Structures and Algorithms Using Python published by Wiley and has authored numerous professional and pedagogical online tutorials and references. Cover design: Madelyn Lesure Cover image credits: castle: Anik Messier/Getty Images, cow: © Eric Isselee/Shutterstock, hotair balloon: © Mikhail Mishchenko/123RF.com, trumpets: © modella/123RF.com, ISBN 978-1-118-62613-9 trebuchet: © Stephen Coburn/123RF.com, parrot: © Eric Isselée/iStockphoto, binoculars: © Tom Horyn/iStockphoto 90000 www.wiley.com/college/horstmann 9 781118 626139 pyt_cover2.pdf 1 1/11/13 11:44 AM Variable and Constant Definitions Selected Operators and Their Precedence (See Appendix B for the complete list.) Name Initial value [] Sequence element access cansPerPack = 6 Use uppercase for constants ** Raising to a power CAN_VOLUME = 0.335 * / // % Multiplication, division, floor division, remainder + - Addition, subtraction Mathematical Functions < <= > >= != in Comparisons and membership abs(x) Absolute value |x| not round(x) Rounds to nearest integer or Boolean operators max(x1, x2, ...) Largest of the arguments and min(x1, x2, ...) Smallest of the arguments From math module: Strings sqrt(x) Square root x trunc(x) Truncates to an integer s = "Hello" sin(x), cos(x), tan(x) Sine, cosine, tangent of x len(s) The length of the string: 5 degrees(x), radians(x) Converts to degrees or radians s[1] The character with index 1: "e" log(x), log(x, base) Natural log, log (x) s + "!" Concatenation: Hello! base s * 2 Replication: "HelloHello" s.upper() Yields "HELLO" Imports s.replace("e", "3") Yields "H3llo" Module Imported items from math import sqrt, log Lists An empty list friends = [] Conditional Statement values = [16, 3, 2, 13] Condition for i in range(len(values)) if floor >= 13 : Executed when condition is true values[i] = i * i actualFloor = floor - 1 Second condition (optional) elif floor >= 0 : friends.append("Bob") actualFloor = floor friends.insert(0, "Amy") else : Executed when if "Amy" in friends : print("Floor negative") all conditions are n = friends.index("Amy") friends.pop(n) false (optional) Removes nth else : friends.pop( ) Removes last Loop Statements friends.remove("Bob") Condition Concatenation guests = friends + ["Lee", "Zoe"] scores = [0] * 1 2 Replication while balance < TARGET : year = year + 1 Executed while bestFriends = f r i e n d s [ 0 : 3 ] Slice balance = balance * (1 + rate / 100) condition is true Included Excluded A container (list, str, range, dict, set) total = sum(val u e s ) List must contain numbers for value in values : largest = max(v a l u e s ) sum = sum + value values.sort() Use min to get the smallest Function Definition Tables table = [[16, 3, 2, 13], Function name Parameter name [5, 10, 11, 8], [9, 6, 7, 12], def cubeVolume(sideLength) : Number of rows [4, 15, 14, 1]] volume = sideLength ** 3 Number of columns return volume for row in range(len(table)) : Exits method and for column in range(len(table[row])) : returns result sum = sum + table[row][column] P y t h o n f o r E v E r y o n E © Anik Messier/Getty Images. Cay Horstmann San Jose State University Rance D. Necaise College of William and Mary pyt_fm.indd 1 1/31/13 6:40 PM VP AND EXECUTIVE PUBLISHER Don Fowley EXECUTIVE EDITOR Beth Lang Golub EDITORIAL ASSISTANT Katherine Willis EXECUTIVE MARKETING MANAGER Christopher Ruel PRODUCTION MANAGEMENT SERVICES Cindy Johnson CREATIVE DIRECTOR Harry Nolan SENIOR DESIGNER Madelyn Lesure PHOTO MANAGER Hilary Newman SENIOR PHOTO EDITOR Lisa Gee COVER CREDIT Based on Monty Python and the Holy Grail. Reproduced with permission of Python (Monty) Pictures, Ltd. COVER PHOTOS (balloon) © Mikhail Mishchenko/123RF.com; (binoculars) © Tom Horyn/iStockphoto; (castle) © Anik Messier/Getty Images; (cow) © Eric Isselée/Shutterstock; (parrot) © Eric Isselée/iStockphoto; (trebuchet) © Stephen Coburn/123RF.com; (trumpets) © modella/123RF.com. This book was set in Stempel Garamond by Publishing Services, and printed and bound by Quad/Graphics. The cover was printed by Quad/Graphics. This book is printed on acid-free paper. ∞ 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, economic, 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 information, please visit our website: www.wiley.com/go/ citizenship. Copyright © 2014 John Wiley & Sons, Inc. 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, 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, Danvers, MA 01923, website 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, website www.wiley.com/go/permissions. 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. Outside of the United States, please contact your local representative. ISBN 978-1-118-62613-9 ISBN 978-1-118-64520-8 (BRV) Printed in the United States of America 10 9 8 7 6 5 4 3 2 1 pyt_fm.indd 2 1/31/13 6:40 PM For Clora, maybe—C.H. To my parents Willard and Ella—R.N. pyt_fm.indd 3 1/31/13 9:43 AM pyt_fm.indd 4 1/31/13 9:43 AM 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. Here are the book’s key features: Present fundamentals first. The book takes a traditional route, first stressing control structures, functions, proce- dural decomposition, and the built-in data structures. Objects are used when appro- priate in the early chapters. Students start designing and implementing their own classes in Chapter 9. Guidance and worked examples help students succeed. Beginning programmers often ask “How do I start? Now what do I do?” Of course, an activity as complex as programming cannot be reduced to cookbook-style instruc- tions. However, step-by-step guidance is immensely helpful for building confidence and providing an outline for the task at hand. “Problem Solving” sections stress the importance of design and planning. “How To” guides help students with common programming tasks. Numerous worked examples demonstrate how to apply chapter concepts to interesting problems. Practice makes perfect. Of course, programming students need to be able to implement nontrivial programs, but they first need to have the confidence that they can succeed. This book contains a substantial number of self-check questions at the end of each section. “Practice It” pointers suggest exercises to try after each section. A bank of quiz and test questions covering computer science concepts and programming skills is available to instructors. A visual approach motivates the reader and eases navigation. Photographs present visual analogies that explain the nature and behavior of computer concepts. Step-by- step figures illustrate complex program operations. Syntax boxes and example tables present a variety of typical and special cases in a compact format. It is easy to get the “lay of the land” by browsing the visuals, before focusing on the textual material. Focus on the essentials while being technically accurate. Visual features help the reader An encyclopedic coverage is not helpful for a begin- with navigation. ning programmer, but neither is the opposite— reducing the material to a list of simplistic bullet points. In this book, the essentials are presented in digestible chunks, with separate notes that go deeper into good prac- tices or language features when the reader is ready for the additional information. © Terraxplorer/iStockphoto. v pyt_fm.indd 5 1/31/13 6:38 PM vi Preface a tour of the Book Figure 1 shows the dependencies between the chapters and how topics are organized. The core material of the book is: chapter 1. Introduction chapter 2. Programming with Numbers and Strings chapter 3. Decisions chapter 4. Loops chapter 5. Functions chapter 6. Lists chapter 7. Files and Exceptions chapter 8. Sets and Dictionaries Two chapters cover object-oriented programming: chapter 9. Objects and Classes chapter 10. Inheritance Two chapters support a course that goes more deeply into algorithm design and analysis: chapter 11. Recursion chapter 12. Sorting and Searching Any chapters can be incorporated into a custom print version of this text; ask your Wiley sales representative for details. Appendices  Five appendices provide a handy reference for students: appendix a. The Basic Latin and Latin-1 Subsets of Unicode appendix B. Python Operator Summary appendix c. Python Reserved Word Summary appendix D. The Python Library appendix E. Binary Numbers and Bit Operations Problem Solving Strategies Throughout the book, students will find practical, step-by-step guidance to help them 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) • Adapting Algorithms • First Do It By Hand (doing sample • Discovering Algorithms by calculations by hand) Manipulating Physical Objects • Flowcharts • Tracing Objects (identifying state • Test Cases and behavior) • Hand-Tracing • Patterns for Object Data • Storyboards • Thinking Recursively • Reusable Functions • Estimating the Running Time of • Stepwise Refinement an Algorithm pyt_fm.indd 6 1/31/13 9:43 AM Preface  vii An Optional Graphics Library Writing programs that create drawings can provide students with effective visualiza- tions of complex topics. We provide a very simple graphics library that we introduce in Chapter 2. Subsequent chapters contain worked examples and exercises that use the library. This material is completely optional. Exercises End-of-chapter exercises contain a broad mix of review and programming ques- tions, with optional questions from the domains of graphics, science, and business. Designed to engage students, the exercises illustrate the value of programming in applied fields. Web Resources This book is complemented by a complete suite of online resources. Go to www.wiley. com/college/horstmann to visit the online companion sites, which include • Source code for all examples in the book. • Lecture presentation slides (in PowerPoint format). • Solutions to all review and programming exercises (for instructors only). • A test bank that focuses on skills, not just terminology (for instructors only). Fundamentals 1. Introduction Object-Oriented Programming Data Structures & Algorithms 2. Programming with Numbers and Strings 3. Decisions 4. Loops A gentle introduction to recursion 5. Functions is optional. Sections 7.1 and 7.2 (text file processing) can be 6.6 I.t eLriasttison covered with Chapter 4. 7. Files and 8. Sets and 9. Objects Exceptions D6i.c Ittieornaatrioiens and Classes 11. Recursion Figure 1   Chapter   10. Inheritance 12. Sorting and Searching Dependencies pyt_fm.indd 7 1/31/13 7:19 PM viii Walkthrough 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 code: ch01/hello.py 1 # My first Python program. 2 print("Hello, World!") A Python program contains one or more lines of instructions or statements that will be translated and executed by the Python interpreter. The first line Throughout each chapter, # My first Python program. margin notes show where Ain fcoormmmateionnt ptoro vides tisiv ae c ionmfomrmenatti.o Cno tmo mtheen ptsr obgergainm wmiethr. #C aonmd mareen ntos tw stiallt ebme ednistcs.u Tssheedy ipnr movoidree ddeetsacirli pin- new concepts are introduced the programmer. Section 2.1.5. The second line contains a statement and provide an outline of key ideas. print("Hello, World!") that prints or displays a line of text, namely “Hello, World!”. In this statement, we Aa cfuonllectcitoionn i so f call a function named print and pass it the information to be displayed. A function is instructions a collection of programming instructions that carry out a particular task. We do not that perform a have to implement this function, it is part of the Python language. We simply want particular task. the function to perform its intended task, namely to print a value. To use, or call, a function in Python, you need to specify A function is called bfuyn scptieocnif nyianmge t haen d 1. The name of the function you want to use (in this case, print). its arguments. 2. Any values the function needs to carry out its task (in this case, "Hello, World!"). The technical term for such a value is an argument. Arguments are enclosed in Annotated syntax boxes parentheses with multiple arguments separated by commas. The number of provide a quick, visual overview arguments required depends on the function. of new language constructs. Syntax 1.1 print Statement Syntax print() print(value1, value2, ..., valuen) All arguments are optional. If no arguments Annotations explain required are given, a blank line is printed. 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. pyt_fm.indd 8 1/31/13 9:43 AM

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.