S e E c dio tin d o n Introducing Python Modern Computing in Simple Packages Bill Lubanovic SECOND EDITION Introducing Python Modern Computing in Simple Packages Bill Lubanovic BBeeiijjiinngg BBoossttoonn FFaarrnnhhaamm SSeebbaassttooppooll TTookkyyoo Introducing Python by Bill Lubanovic Copyright © 2020 Bill Lubanovic. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (http://oreilly.com). For more information, contact our corporate/institutional sales department: 800-998-9938 or [email protected]. Acquisitions Editor: Tyler Ortman Indexer: WordCo Indexing Services, Inc. Development Editor: Corbin Collins Interior Designer: David Futato Production Editor: Christopher Faucher Cover Designer: Karen Montgomery Copyeditor: Jasmine Kwityn Illustrator: Rebecca Demarest Proofreader: Octal Publishing, LLC November 2019: Second Edition Revision History for the Second Edition 2019-11-06: First Release See http://oreilly.com/catalog/errata.csp?isbn=9781492051367 for release details. The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. Introducing Python, the cover image, and related trade dress are trademarks of O’Reilly Media, Inc. The views expressed in this work are those of the author, and do not represent the publisher’s views. While the publisher and the author have used good faith efforts to ensure that the information and instructions contained in this work are accurate, the publisher and the author disclaim all responsibility for errors or omissions, including without limitation responsibility for damages resulting from the use of or reliance on this work. Use of the information and instructions contained in this work is at your own risk. If any code samples or other technology this work contains or describes is subject to open source licenses or the intellectual property rights of others, it is your responsibility to ensure that your use thereof complies with such licenses and/or rights. 978-1-492-05136-7 [LSI] With love to Mary, Tom & Roxie, and Karin & Erik Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi Part I. Python Basics 1. A Taste of Py. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3 Mysteries 3 Little Programs 5 A Bigger Program 7 Python in the Real World 11 Python Versus the Language from Planet X 12 Why Python? 14 Why Not Python? 16 Python 2 Versus Python 3 17 Installing Python 18 Running Python 18 Using the Interactive Interpreter 18 Using Python Files 19 What’s Next? 20 Your Moment of Zen 20 Coming Up 21 Things to Do 21 2. Data: Types, Values, Variables, and Names. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Python Data Are Objects 23 Types 25 Mutability 25 Literal Values 26 v Variables 26 Assignment 28 Variables Are Names, Not Places 29 Assigning to Multiple Names 33 Reassigning a Name 33 Copying 33 Choose Good Variable Names 34 Coming Up 35 Things to Do 35 3. Numbers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37 Booleans 38 Integers 38 Literal Integers 38 Integer Operations 40 Integers and Variables 41 Precedence 43 Bases 44 Type Conversions 47 How Big Is an int? 49 Floats 49 Math Functions 51 Coming Up 51 Things to Do 51 4. Choose with if. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 Comment with # 53 Continue Lines with \ 54 Compare with if, elif, and else 55 What Is True? 58 Do Multiple Comparisons with in 59 New: I Am the Walrus 60 Coming Up 61 Things to Do 61 5. Text Strings. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 Create with Quotes 64 Create with str() 66 Escape with \ 66 Combine by Using + 68 Duplicate with * 68 Get a Character with [] 69 vi | Table of Contents Get a Substring with a Slice 70 Get Length with len() 72 Split with split() 72 Combine by Using join() 73 Substitute by Using replace() 73 Strip with strip() 74 Search and Select 75 Case 76 Alignment 77 Formatting 77 Old style: % 78 New style: {} and format() 80 Newest Style: f-strings 82 More String Things 83 Coming Up 84 Things to Do 84 6. Loop with while and for. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87 Repeat with while 87 Cancel with break 88 Skip Ahead with continue 88 Check break Use with else 89 Iterate with for and in 89 Cancel with break 90 Skip with continue 90 Check break Use with else 90 Generate Number Sequences with range() 91 Other Iterators 92 Coming Up 92 Things to Do 92 7. Tuples and Lists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 Tuples 93 Create with Commas and () 94 Create with tuple() 95 Combine Tuples by Using + 95 Duplicate Items with * 96 Compare Tuples 96 Iterate with for and in 96 Modify a Tuple 96 Lists 97 Create with [] 97 Table of Contents | vii Create or Convert with list() 97 Create from a String with split() 98 Get an Item by [ offset ] 98 Get Items with a Slice 99 Add an Item to the End with append() 100 Add an Item by Offset with insert() 100 Duplicate All Items with * 100 Combine Lists by Using extend() or + 101 Change an Item by [ offset ] 101 Change Items with a Slice 102 Delete an Item by Offset with del 102 Delete an Item by Value with remove() 103 Get an Item by Offset and Delete It with pop() 103 Delete All Items with clear() 104 Find an Item’s Offset by Value with index() 104 Test for a Value with in 104 Count Occurrences of a Value with count() 104 Convert a List to a String with join() 105 Reorder Items with sort() or sorted() 105 Get Length with len() 106 Assign with = 106 Copy with copy(), list(), or a Slice 107 Copy Everything with deepcopy() 108 Compare Lists 109 Iterate with for and in 109 Iterate Multiple Sequences with zip() 110 Create a List with a Comprehension 111 Lists of Lists 114 Tuples Versus Lists 114 There Are No Tuple Comprehensions 115 Coming Up 115 Things to Do 115 8. Dictionaries and Sets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Dictionaries 117 Create with {} 117 Create with dict() 118 Convert with dict() 119 Add or Change an Item by [ key ] 119 Get an Item by [key] or with get() 121 Get All Keys with keys() 121 Get All Values with values() 122 viii | Table of Contents