ebook img

The Python Workbook: A Brief Introduction with Exercises and Solutions PDF

218 Pages·5.928 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 The Python Workbook: A Brief Introduction with Exercises and Solutions

Texts in Computer Science Ben Stephenson The Python Workbook A Brief Introduction with Exercises and Solutions Second Edition Texts in Computer Science Series Editors David Gries, Department of Computer Science, Cornell University, Ithaca, NY, USA Orit Hazzan, Faculty of Education in Technology and Science, Technion—Israel Institute of Technology, Haifa, Israel More information about this series at http://www.springer.com/series/3191 Ben Stephenson The Python Workbook A Brief Introduction with Exercises and Solutions Second Edition 123 BenStephenson Department ofComputer Science University of Calgary Calgary, AB,Canada ISSN 1868-0941 ISSN 1868-095X (electronic) Textsin Computer Science ISBN978-3-030-18872-6 ISBN978-3-030-18873-3 (eBook) https://doi.org/10.1007/978-3-030-18873-3 1stedition:©SpringerInternationalPublishingSwitzerland2014 2ndedition:©SpringerNatureSwitzerlandAG2019 Thisworkissubjecttocopyright.AllrightsarereservedbythePublisher,whetherthewholeorpart of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission orinformationstorageandretrieval,electronicadaptation,computersoftware,orbysimilarordissimilar methodologynowknownorhereafterdeveloped. The use of general descriptive names, registered names, trademarks, service marks, etc. in this publicationdoesnotimply,evenintheabsenceofaspecificstatement,thatsuchnamesareexemptfrom therelevantprotectivelawsandregulationsandthereforefreeforgeneraluse. The publisher, the authors and the editors are safe to assume that the advice and information in this book are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or the editors give a warranty, expressed or implied, with respect to the material contained hereinorforanyerrorsoromissionsthatmayhavebeenmade.Thepublisherremainsneutralwithregard tojurisdictionalclaimsinpublishedmapsandinstitutionalaffiliations. ThisSpringerimprintispublishedbytheregisteredcompanySpringerNatureSwitzerlandAG Theregisteredcompanyaddressis:Gewerbestrasse11,6330Cham,Switzerland To my wife, Flora, for 16 fantastic years of marriage, and many more to come. To my sons, Jonathan and Andrew, who were both in a hurry to enter the world. I love you all. Preface Ibelievethatcomputerprogrammingisaskillthatisbestlearnedthroughhands-on experience. While it is valuable for you to read about programming in textbooks and watch teachers create programs at the front of classrooms, it is even more important for you to spend time-solving problems that allow you to put program- ming concepts into practice. With this in mind, the majority of the pages in this bookarededicatedtoexercisesandtheirsolutionswhileonlyafewpagesareused to briefly introduce the concepts needed to complete them. Thisbookcontains186exercisesthatspanavarietyofacademicdisciplinesand everyday situations. They can be solved using only the material covered in most introductory Python programming courses. Each exercise that you complete will strengthen your understanding of the Python programming language and enhance your ability to tackle subsequent programming challenges. I also hope that the connections that these exercises make to other academic disciplines and everyday life will maintain your interest as you complete them. Solutions to approximately half of the exercisesare provided in thesecond half of this book. Most of the solutions include brief annotations that explain the techniqueusedtosolvetheproblemorhighlightaspecificpointofPythonsyntax. Youwillfindtheseannotationsinshadedboxes,makingiteasytodistinguishthem from the solution itself. Ihopethat youwill take thetime tocompareeachofyoursolutionswithmine, even when you arrive at your solution without encountering any problems. Per- forming this comparison may reveal a flaw in your program, or help you become morefamiliarwithatechniquethatyoucouldhaveusedtosolvetheproblemmore easily.Insomecases,itcouldalsorevealthatyouhavediscoveredafasteroreasier waytosolvetheproblemthanIhave.Ifyoubecomestuckonanexercise,aquick peek at my solution may help you work through your problem and continue to make progress without requiring assistance from someone else. Finally, the solu- tions that I have provided demonstrate good programming style, including appro- priate comments, meaningful variable names, and minimal use of magic numbers. I encourage you to use good programming style when creating your solutions so thattheycomputethecorrectresultwhilealsobeingclear,easytounderstand,and amenable to being updated in the future. vii viii Preface Exercises that include a solution are clearly marked with (Solved) next to the exercisename.Thelengthofthesamplesolutionisalsostatedforeveryexercisein this book. While you shouldn’t expect your solution length to match the sample solutionlengthexactly,Ihopethatprovidingthisinformationwillpreventyoufrom going too far astray before seeking assistance. This book can be used in a variety of ways. Its concise introductions to major Pythonprogrammingconcepts,whicharenewinthisedition,allowittobeusedas the lone textbook for an introductory programming course. It can also be used to supplement anothertextbook that has a limited selection of exercises. Amotivated individual could teach themselves to program in Python using only this book, though there are, perhaps, easier ways to learn the language because the concise introductions to each topic cover only their most important aspects, without examining every special case or unusual circumstance. No matter what other resources you use with this book, if any, reading the chapters, completing the exercises, and studying the provided solutions will enhance your programming ability. Acknowledgements I would like to thank Dr. Tom Jenkyns for reviewing this book as it was being created. His helpful comments and suggestions resulted in numerous refinements and corrections that improved the quality of this work. Calgary, Canada Ben Stephenson March 2019 Contents Part I Exercises 1 Introduction to Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 1.1 Storing and Manipulating Values. . . . . . . . . . . . . . . . . . . . . . . . 4 1.2 Calling Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5 1.3 Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.4 Formatting Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 1.5 Working with Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 1.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 2 Decision Making . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 2.1 If Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 2.2 If-Else Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 2.3 If-Elif-Else Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 2.4 If-Elif Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 2.5 Nested If Statements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 2.6 Boolean Logic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 2.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29 3 Repetition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 3.1 While Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 3.2 For Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44 3.3 Nested Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46 3.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 4 Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 4.1 Functions with Parameters. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60 4.2 Variables in Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 4.3 Return Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 4.4 Importing Functions into Other Programs. . . . . . . . . . . . . . . . . . 65 4.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65 5 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 5.1 Accessing Individual Elements . . . . . . . . . . . . . . . . . . . . . . . . . 75 5.2 Loops and Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76 ix x Contents 5.3 Additional List Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 5.4 Lists as Return Values and Arguments. . . . . . . . . . . . . . . . . . . . 82 5.5 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 6 Dictionaries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97 6.1 Accessing, Modifying and Adding Values . . . . . . . . . . . . . . . . . 98 6.2 Removing a Key-Value Pair . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 6.3 Additional Dictionary Operations. . . . . . . . . . . . . . . . . . . . . . . . 99 6.4 Loops and Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100 6.5 Dictionaries as Arguments and Return Values . . . . . . . . . . . . . . 101 6.6 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102 7 Files and Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 7.1 Opening a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 7.2 Reading Input from a File. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110 7.3 End of Line Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 7.4 Writing Output to a File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 7.5 Command Line Arguments . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 7.6 Exceptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115 7.7 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 8 Recursion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 8.1 Summing Integers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127 8.2 Fibonacci Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 8.3 Counting Characters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131 8.4 Exercises . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132 Part II Solutions 9 Solutions to the Introduction to Programming Exercises . . . . . . . . 143 10 Solutions to the Decision Making Exercises . . . . . . . . . . . . . . . . . . 151 11 Solutions to the Repetition Exercises. . . . . . . . . . . . . . . . . . . . . . . . 161 12 Solutions to the Function Exercises. . . . . . . . . . . . . . . . . . . . . . . . . 169 13 Solutions to the List Exercises. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183 14 Solutions to the Dictionary Exercises . . . . . . . . . . . . . . . . . . . . . . . 193 15 Solutions to the File and Exception Exercises . . . . . . . . . . . . . . . . . 199 16 Solutions to the Recursion Exercises. . . . . . . . . . . . . . . . . . . . . . . . 209 Index .... .... .... .... .... ..... .... .... .... .... .... ..... .... 215

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.