Python Crash Course

Python Crash Course
اسم المؤلف
Eric Matthe
التاريخ
التصنيف
المشاهدات
765
التقييم
(لا توجد تقييمات)
Loading...
التحميل

Python Crash Course
2nd edition
ahands-on, Project-Based introduction to Programming
by Eric Matthe
B r i e f C o n t e n t s
Preface to the Second Edition xxvii
Acknowledgments xxxi
Introduction xxxiii
Part I: BasIcs 1
Chapter 1: Getting Started 3
Chapter 2: Variables and Simple Data Types 15
Chapter 3: Introducing Lists 33
Chapter 4: Working with Lists 49
Chapter 5: if Statements 71
Chapter 6: Dictionaries 91
Chapter 7: User Input and while Loops 113
Chapter 8: Functions 129
Chapter 9: Classes 157
Chapter 10: Files and Exceptions 183
Chapter 11: Testing Your Code 209
Part II: Projects 223
Project 1: Alien Invasion
Chapter 12: A Ship that Fires Bullets 227
Chapter 13: Aliens! 255
Chapter 14: Scoring 279x Brief Contents
Project 2: Data Visualization
Chapter 15: Generating Data 305
Chapter 16: Downloading Data 333
Chapter 17: Working with APIs 359
Project 3: Web Applications
Chapter 18: Getting Started with Django 379
Chapter 19: User Accounts 409
Chapter 20: Styling and Deploying an App 437
Afterword 465
Appendix A: Installation and Troubleshooting 467
Appendix B: Text Editors and IDEs 473
Appendix C: Getting Help 479
Appendix D: Using Git for Version Control 485
Index
C o n t e n t s i n D e t a i l
Preface to the Second edition xxvii
acknowledgmentS xxxi
introduction xxxiii
Who Is This Book For? xxxiv
What Can You Expect to Learn? xxxiv
Online Resources xxxv
Why Python? xxxvi
Part i: BaSicS 1
1g
etting Started 3
Setting Up Your Programming Environment 3
Python Versions 4
Running Snippets of Python Code 4
About the Sublime Text Editor 4
Python on Different Operating Systems 5
Python on Windows 5
Python on macOS 7
Python on Linux 8
Running a Hello World Program 9
Configuring Sublime Text to Use the Correct Python Version 9
Running hello_world py 10
Troubleshooting 11
Running Python Programs from a Terminal 12
On Windows 12
On macOS and Linux 12
Exercise 1-1: python.org 13
Exercise 1-2: Hello World Typos . 13
Exercise 1-3: Infinite Skills . 13
Summary 13
2
VariaBleS and SimPle data tyPeS 15
What Really Happens When You Run hello_world py 15
Variables 16
Naming and Using Variables 17
Avoiding Name Errors When Using Variables 17
Variables Are Labels 18
Exercise 2-1: Simple Message 19
Exercise 2-2: Simple Messages 19xii Contents in Detail
Strings 19
Changing Case in a String with Methods 20
Using Variables in Strings 21
Adding Whitespace to Strings with Tabs or Newlines 22
Stripping Whitespace 22
Avoiding Syntax Errors with Strings 24
Exercise 2-3: Personal Message . 25
Exercise 2-4: Name Cases . 25
Exercise 2-5: Famous Quote 25
Exercise 2-6: Famous Quote 2 25
Exercise 2-7: Stripping Names 25
Numbers 25
Integers 26
Floats 26
Integers and Floats 27
Underscores in Numbers 28
Multiple Assignment 28
Constants 28
Exercise 2-8: Number Eight 29
Exercise 2-9: Favorite Number 29
Comments 29
How Do You Write Comments? 29
What Kind of Comments Should You Write? 29
Exercise 2-10: Adding Comments 30
The Zen of Python 30
Exercise 2-11: Zen of Python . 31
Summary 32
3i
ntroducing liStS 33
What Is a List? 33
Accessing Elements in a List 34
Index Positions Start at 0, Not 1 35
Using Individual Values from a List 35
Exercise 3-1: Names . 36
Exercise 3-2: Greetings . 36
Exercise 3-3: Your Own List 36
Changing, Adding, and Removing Elements 36
Modifying Elements in a List 36
Adding Elements to a List 37
Removing Elements from a List 38
Exercise 3-4: Guest List . 42
Exercise 3-5: Changing Guest List 42
Exercise 3-6: More Guests . 42
Exercise 3-7: Shrinking Guest List 43
Organizing a List 43
Sorting a List Permanently with the sort() Method 43
Sorting a List Temporarily with the sorted() Function 44
Printing a List in Reverse Order 45
Finding the Length of a List 45
Exercise 3-8: Seeing the World 46
Exercise 3-9: Dinner Guests 46
Exercise 3-10: Every Function . 46Contents in Detail xiii
Avoiding Index Errors When Working with Lists 46
Exercise 3-11: Intentional Error 48
Summary 48
4w
orking with liStS 49
Looping Through an Entire List 49
A Closer Look at Looping 50
Doing More Work Within a for Loop 51
Doing Something After a for Loop 52
Avoiding Indentation Errors 53
Forgetting to Indent 53
Forgetting to Indent Additional Lines 54
Indenting Unnecessarily 55
Indenting Unnecessarily After the Loop 55
Forgetting the Colon 56
Exercise 4-1: Pizzas . 56
Exercise 4-2: Animals 56
Making Numerical Lists 57
Using the range() Function 57
Using range() to Make a List of Numbers 58
Simple Statistics with a List of Numbers 59
List Comprehensions 59
Exercise 4-3: Counting to Twenty 60
Exercise 4-4: One Million 60
Exercise 4-5: Summing a Million . 60
Exercise 4-6: Odd Numbers 60
Exercise 4-7: Threes . 60
Exercise 4-8: Cubes 60
Exercise 4-9: Cube Comprehension . 60
Working with Part of a List 61
Slicing a List 61
Looping Through a Slice 62
Copying a List 63
Exercise 4-10: Slices . 65
Exercise 4-11: My Pizzas, Your Pizzas . 65
Exercise 4-12: More Loops . 65
Tuples 65
Defining a Tuple 66
Looping Through All Values in a Tuple 67
Writing over a Tuple 67
Exercise 4-13: Buffet . 68
Styling Your Code 68
The Style Guide 68
Indentation 69
Line Length 69
Blank Lines 69
Other Style Guidelines 70
Exercise 4-14: PEP 8 70
Exercise 4-15: Code Review 70
Summary 70xiv Contents in Detail
5
if StatementS 71
A Simple Example 72
Conditional Tests 72
Checking for Equality 72
Ignoring Case When Checking for Equality 73
Checking for Inequality 74
Numerical Comparisons 74
Checking Multiple Conditions 75
Checking Whether a Value Is in a List 76
Checking Whether a Value Is Not in a List 77
Boolean Expressions 77
Exercise 5-1: Conditional Tests 78
Exercise 5-2: More Conditional Tests 78
if Statements 78
Simple if Statements 78
if-else Statements 79
The if-elif-else Chain 80
Using Multiple elif Blocks 82
Omitting the else Block 82
Testing Multiple Conditions 83
Exercise 5-3: Alien Colors #1 . 84
Exercise 5-4: Alien Colors #2 . 84
Exercise 5-5: Alien Colors #3 . 85
Exercise 5-6: Stages of Life . 85
Exercise 5-7: Favorite Fruit . 85
Using if Statements with Lists 85
Checking for Special Items 86
Checking That a List Is Not Empty 87
Using Multiple Lists 88
Exercise 5-8: Hello Admin . 89
Exercise 5-9: No Users . 89
Exercise 5-10: Checking Usernames 89
Exercise 5-11: Ordinal Numbers . 89
Styling Your if Statements 90
Exercise 5-12: Styling if statements . 90
Exercise 5-13: Your Ideas 90
Summary 90
6d
ictionarieS 91
A Simple Dictionary 92
Working with Dictionaries 92
Accessing Values in a Dictionary 93
Adding New Key-Value Pairs 93
Starting with an Empty Dictionary 94
Modifying Values in a Dictionary 95
Removing Key-Value Pairs 96
A Dictionary of Similar Objects 97
Using get() to Access Values 98Contents in Detail xv
Exercise 6-1: Person . 99
Exercise 6-2: Favorite Numbers . 99
Exercise 6-3: Glossary 99
Looping Through a Dictionary 99
Looping Through All Key-Value Pairs 99
Looping Through All the Keys in a Dictionary 101
Looping Through a Dictionary’s Keys in a Particular Order 103
Looping Through All Values in a Dictionary 104
Exercise 6-4: Glossary 2 . 105
Exercise 6-5: Rivers . 105
Exercise 6-6: Polling 105
Nesting 106
A List of Dictionaries 106
A List in a Dictionary 108
A Dictionary in a Dictionary 110
Exercise 6-7: People 112
Exercise 6-8: Pets 112
Exercise 6-9: Favorite Places 112
Exercise 6-10: Favorite Numbers . 112
Exercise 6-11: Cities 112
Exercise 6-12: Extensions . 112
Summary 112
7
uSer inPut and while looPS 113
How the input() Function Works 114
Writing Clear Prompts 114
Using int() to Accept Numerical Input 115
The Modulo Operator 116
Exercise 7-1: Rental Car 117
Exercise 7-2: Restaurant Seating 117
Exercise 7-3: Multiples of Ten 117
Introducing while Loops 118
The while Loop in Action 118
Letting the User Choose When to Quit 118
Using a Flag 120
Using break to Exit a Loop 121
Using continue in a Loop 122
Avoiding Infinite Loops 122
Exercise 7-4: Pizza Toppings 123
Exercise 7-5: Movie Tickets 123
Exercise 7-6: Three Exits . 124
Exercise 7-7: Infinity 124
Using a while Loop with Lists and Dictionaries 124
Moving Items from One List to Another 124
Removing All Instances of Specific Values from a List 125
Filling a Dictionary with User Input 126
Exercise 7-8: Deli 127
Exercise 7-9: No Pastrami 127
Exercise 7-10: Dream Vacation . 127
Summary 127xvi Contents in Detail
8f
unctionS 129
Defining a Function 130
Passing Information to a Function 130
Arguments and Parameters 131
Exercise 8-1: Message . 131
Exercise 8-2: Favorite Book . 131
Passing Arguments 131
Positional Arguments 132
Keyword Arguments 133
Default Values 134
Equivalent Function Calls 135
Avoiding Argument Errors 136
Exercise 8-3: T-Shirt . 137
Exercise 8-4: Large Shirts . 137
Exercise 8-5: Cities . 137
Return Values 137
Returning a Simple Value 138
Making an Argument Optional 138
Returning a Dictionary 140
Using a Function with a while Loop 141
Exercise 8-6: City Names . 142
Exercise 8-7: Album . 142
Exercise 8-8: User Albums 142
Passing a List 143
Modifying a List in a Function 143
Preventing a Function from Modifying a List 145
Exercise 8-9: Messages 146
Exercise 8-10: Sending Messages . 146
Exercise 8-11: Archived Messages 146
Passing an Arbitrary Number of Arguments 147
Mixing Positional and Arbitrary Arguments 148
Using Arbitrary Keyword Arguments 148
Exercise 8-12: Sandwiches 150
Exercise 8-13: User Profile 150
Exercise 8-14: Cars . 150
Storing Your Functions in Modules 150
Importing an Entire Module 150
Importing Specific Functions 152
Using as to Give a Function an Alias 152
Using as to Give a Module an Alias 153
Importing All Functions in a Module 153
Styling Functions 154
Exercise 8-15: Printing Models . 155
Exercise 8-16: Imports . 155
Exercise 8-17: Styling Functions 155
Summary 155Contents in Detail xvii
9c
laSSeS 157
Creating and Using a Class 158
Creating the Dog Class 158
Making an Instance from a Class 160
Exercise 9-1: Restaurant 162
Exercise 9-2: Three Restaurants . 162
Exercise 9-3: Users . 162
Working with Classes and Instances 162
The Car Class 162
Setting a Default Value for an Attribute 163
Modifying Attribute Values 164
Exercise 9-4: Number Served 167
Exercise 9-5: Login Attempts . 167
Inheritance 167
The __init__() Method for a Child Class 167
Defining Attributes and Methods for the Child Class 169
Overriding Methods from the Parent Class 170
Instances as Attributes 170
Modeling Real-World Objects 173
Exercise 9-6: Ice Cream Stand . 173
Exercise 9-7: Admin 173
Exercise 9-8: Privileges 173
Exercise 9-9: Battery Upgrade . 174
Importing Classes 174
Importing a Single Class 174
Storing Multiple Classes in a Module 175
Importing Multiple Classes from a Module 177
Importing an Entire Module 177
Importing All Classes from a Module 177
Importing a Module into a Module 178
Using Aliases 179
Finding Your Own Workflow 179
Exercise 9-10: Imported Restaurant 180
Exercise 9-11: Imported Admin . 180
Exercise 9-12: Multiple Modules 180
The Python Standard Library 180
Exercise 9-13: Dice . 181
Exercise 9-14: Lottery . 181
Exercise 9-15: Lottery Analysis . 181
Exercise 9-16: Python Module of the Week 181
Styling Classes 181
Summary 182
10
fileS and excePtionS 183
Reading from a File 184
Reading an Entire File 184
File Paths 185
Reading Line by Line 187
Making a List of Lines from a File 188
Working with a File’s Contents 188xviii Contents in Detail
Large Files: One Million Digits 189
Is Your Birthday Contained in Pi? 190
Exercise 10-1: Learning Python . 191
Exercise 10-2: Learning C 191
Writing to a File 191
Writing to an Empty File 191
Writing Multiple Lines 192
Appending to a File 193
Exercise 10-3: Guest 193
Exercise 10-4: Guest Book 193
Exercise 10-5: Programming Poll 193
Exceptions 194
Handling the ZeroDivisionError Exception 194
Using try-except Blocks 194
Using Exceptions to Prevent Crashes 195
The else Block 196
Handling the FileNotFoundError Exception 197
Analyzing Text 198
Working with Multiple Files 199
Failing Silently 200
Deciding Which Errors to Report 201
Exercise 10-6: Addition 201
Exercise 10-7: Addition Calculator 202
Exercise 10-8: Cats and Dogs . 202
Exercise 10-9: Silent Cats and Dogs . 202
Exercise 10-10: Common Words . 202
Storing Data 202
Using json dump() and json load() 203
Saving and Reading User-Generated Data 204
Refactoring 206
Exercise 10-11: Favorite Number . 208
Exercise 10-12: Favorite Number Remembered . 208
Exercise 10-13: Verify User . 208
Summary 208
11
teSting your code 209
Testing a Function 210
Unit Tests and Test Cases 211
A Passing Test 211
A Failing Test 212
Responding to a Failed Test 213
Adding New Tests 214
Exercise 11-1: City, Country . 215
Exercise 11-2: Population . 216
Testing a Class 216
A Variety of Assert Methods 216
A Class to Test 217
Testing the AnonymousSurvey Class 218
The setUp() Method 220
Exercise 11-3: Employee . 221
Summary 222Contents in Detail xix
Part ii: ProjectS 223
Project 1: alien inVaSion
12
a ShiP that fireS BulletS 227
Planning Your Project 228
Installing Pygame 228
Starting the Game Project 229
Creating a Pygame Window and Responding to User Input 229
Setting the Background Color 230
Creating a Settings Class 231
Adding the Ship Image 232
Creating the Ship Class 233
Drawing the Ship to the Screen 235
Refactoring: The _check_events() and _update_screen() Methods 236
The _check_events() Method 236
The _update_screen() Method 237
Exercise 12-1: Blue Sky 238
Exercise 12-2: Game Character 238
Piloting the Ship 238
Responding to a Keypress 238
Allowing Continuous Movement 239
Moving Both Left and Right 240
Adjusting the Ship’s Speed 241
Limiting the Ship’s Range 243
Refactoring _check_events() 243
Pressing Q to Quit 244
Running the Game in Fullscreen Mode 244
A Quick Recap 245
alien_invasion py 245
settings py 246
ship py 246
Exercise 12-3: Pygame Documentation . 246
Exercise 12-4: Rocket . 246
Exercise 12-5: Keys . 246
Shooting Bullets 246
Adding the Bullet Settings 247
Creating the Bullet Class 247
Storing Bullets in a Group 248
Firing Bullets 249
Deleting Old Bullets 250
Limiting the Number of Bullets 251
Creating the _update_bullets() Method 252
Exercise 12-6: Sideways Shooter . 253
Summary 253xx Contents in Detail
13
Aliens! 255
Reviewing the Project 256
Creating the First Alien 256
Creating the Alien Class 257
Creating an Instance of the Alien 258
Building the Alien Fleet 259
Determining How Many Aliens Fit in a Row 260
Creating a Row of Aliens 260
Refactoring _create_fleet() 262
Adding Rows 262
Exercise 13-1: Stars 264
Exercise 13-2: Better Stars 264
Making the Fleet Move 265
Moving the Aliens Right 265
Creating Settings for Fleet Direction 266
Checking Whether an Alien Has Hit the Edge 266
Dropping the Fleet and Changing Direction 267
Exercise 13-3: Raindrops 268
Exercise 13-4: Steady Rain 268
Shooting Aliens 268
Detecting Bullet Collisions 268
Making Larger Bullets for Testing 270
Repopulating the Fleet 270
Speeding Up the Bullets 271
Refactoring _update_bullets() 271
Exercise 13-5: Sideways Shooter Part 2 272
Ending the Game 272
Detecting Alien and Ship Collisions 272
Responding to Alien and Ship Collisions 273
Aliens that Reach the Bottom of the Screen 276
Game Over! 276
Identifying When Parts of the Game Should Run 277
Exercise 13-6: Game Over 278
Summary 278
14
scoring 279
Adding the Play Button 280
Creating a Button Class 280
Drawing the Button to the Screen 281
Starting the Game 283
Resetting the Game 283
Deactivating the Play Button 284
Hiding the Mouse Cursor 284
Exercise 14-1: Press P to Play 285
Exercise 14-2: Target Practice 285
Leveling Up 285
Modifying the Speed Settings 285
Resetting the Speed 287Contents in Detail xxi
Exercise 14-3: Challenging Target Practice . 288
Exercise 14-4: Difficulty Levels . 288
Scoring 288
Displaying the Score 288
Making a Scoreboard 289
Updating the Score as Aliens Are Shot Down 291
Resetting the Score 291
Making Sure to Score All Hits 292
Increasing Point Values 292
Rounding the Score 293
High Scores 294
Displaying the Level 296
Displaying the Number of Ships 298
Exercise 14-5: All-Time High Score 301
Exercise 14-6: Refactoring 301
Exercise 14-7: Expanding the Game . 302
Exercise 14-8: Sideways Shooter, Final Version . 302
Summary 302
Project 2: data ViSualization
15
generating data 305
Installing Matplotlib 306
Plotting a Simple Line Graph 306
Changing the Label Type and Line Thickness 307
Correcting the Plot 309
Using Built-in Styles 310
Plotting and Styling Individual Points with scatter() 310
Plotting a Series of Points with scatter() 312
Calculating Data Automatically 312
Defining Custom Colors 314
Using a Colormap 314
Saving Your Plots Automatically 315
Exercise 15-1: Cubes 315
Exercise 15-2: Colored Cubes . 315
Random Walks 315
Creating the RandomWalk() Class 316
Choosing Directions 316
Plotting the Random Walk 317
Generating Multiple Random Walks 318
Styling the Walk 319
Exercise 15-3: Molecular Motion . 323
Exercise 15-4: Modified Random Walks 323
Exercise 15-5: Refactoring 323
Rolling Dice with Plotly 323
Installing Plotly 324
Creating the Die Class 324
Rolling the Die 325xxii Contents in Detail
Analyzing the Results 325
Making a Histogram 326
Rolling Two Dice 328
Rolling Dice of Different Sizes 329
Exercise 15-6: Two D8s 331
Exercise 15-7: Three Dice 331
Exercise 15-8: Multiplication 331
Exercise 15-9: Die Comprehensions . 331
Exercise 15-10: Practicing with Both Libraries . 331
Summary 331
16
downloading data 333
The CSV File Format 334
Parsing the CSV File Headers 334
Printing the Headers and Their Positions 335
Extracting and Reading Data 336
Plotting Data in a Temperature Chart 336
The datetime Module 337
Plotting Dates 338
Plotting a Longer Timeframe 340
Plotting a Second Data Series 340
Shading an Area in the Chart 342
Error Checking 343
Downloading Your Own Data 345
Exercise 16-1: Sitka Rainfall . 346
Exercise 16-2: Sitka–Death Valley Comparison 346
Exercise 16-3: San Francisco 346
Exercise 16-4: Automatic Indexes . 347
Exercise 16-5: Explore . 347
Mapping Global Data Sets: JSON Format 347
Downloading Earthquake Data 347
Examining JSON Data 347
Making a List of All Earthquakes 350
Extracting Magnitudes 350
Extracting Location Data 351
Building a World Map 351
A Different Way of Specifying Chart Data 353
Customizing Marker Size 353
Customizing Marker Colors 354
Other Colorscales 356
Adding Hover Text 356
Exercise 16-6: Refactoring 357
Exercise 16-7: Automated Title . 357
Exercise 16-8: Recent Earthquakes 358
Exercise 16-9: World Fires 358
Summary 358Contents in Detail xxiii
17
working with aPiS 359
Using a Web API 359
Git and GitHub 360
Requesting Data Using an API Call 360
Installing Requests 361
Processing an API Response 361
Working with the Response Dictionary 362
Summarizing the Top Repositories 364
Monitoring API Rate Limits 365
Visualizing Repositories Using Plotly 366
Refining Plotly Charts 368
Adding Custom Tooltips 369
Adding Clickable Links to Our Graph 370
More About Plotly and the GitHub API 371
The Hacker News API 372
Exercise 17-1: Other Languages 375
Exercise 17-2: Active Discussions . 375
Exercise 17-3: Testing python_repos.py . 375
Exercise 17-4: Further Exploration . 375
Summary 375
Project 3: weB aPPlicationS
18
getting Started with django 379
Setting Up a Project 380
Writing a Spec 380
Creating a Virtual Environment 380
Activating the Virtual Environment 381
Installing Django 381
Creating a Project in Django 382
Creating the Database 382
Viewing the Project 383
Exercise 18-1: New Projects . 384
Starting an App 384
Defining Models 385
Activating Models 386
The Django Admin Site 387
Defining the Entry Model 390
Migrating the Entry Model 391
Registering Entry with the Admin Site 391
The Django Shell 392
Exercise 18-2: Short Entries . 394
Exercise 18-3: The Django API . 394
Exercise 18-4: Pizzeria 394
Making Pages: The Learning Log Home Page 394
Mapping a URL 395
Writing a View 396xxiv Contents in Detail
Writing a Template 397
Exercise 18-5: Meal Planner . 398
Exercise 18-6: Pizzeria Home Page 398
Building Additional Pages 398
Template Inheritance 398
The Topics Page 400
Individual Topic Pages 403
Exercise 18-7: Template Documentation . 406
Exercise 18-8: Pizzeria Pages 406
Summary 407
19
uSer accountS 409
Allowing Users to Enter Data 410
Adding New Topics 410
Adding New Entries 414
Editing Entries 418
Exercise 19-1: Blog . 421
Setting Up User Accounts 421
The users App 421
The Login Page 422
Logging Out 424
The Registration Page 426
Exercise 19-2: Blog Accounts 428
Allowing Users to Own Their Data 428
Restricting Access with @login_required 429
Connecting Data to Certain Users 430
Restricting Topics Access to Appropriate Users 433
Protecting a User’s Topics 434
Protecting the edit_entry Page 434
Associating New Topics with the Current User 435
Exercise 19-3: Refactoring 436
Exercise 19-4: Protecting new_entry . 436
Exercise 19-5: Protected Blog 436
Summary 436
20
Styling and dePloying an aPP 437
Styling Learning Log 438
The django-bootstrap4 App 438
Using Bootstrap to Style Learning Log 438
Modifying base html 439
Styling the Home Page Using a Jumbotron 443
Styling the Login Page 444
Styling the Topics Page 445
Styling the Entries on the Topic Page 446
Exercise 20-1: Other Forms . 447
Exercise 20-2: Stylish Blog 447
Deploying Learning Log 448
Making a Heroku Account 448
Installing the Heroku CLI 448Contents in Detail xxv
Installing Required Packages 448
Creating a requirements txt File 448
Specifying the Python Runtime 449
Modifying settings py for Heroku 450
Making a Procfile to Start Processes 450
Using Git to Track the Project’s Files 450
Pushing to Heroku 452
Setting Up the Database on Heroku 454
Refining the Heroku Deployment 454
Securing the Live Project 456
Committing and Pushing Changes 457
Setting Environment Variables on Heroku 458
Creating Custom Error Pages 458
Ongoing Development 461
The SECRET_KEY Setting 461
Deleting a Project on Heroku 461
Exercise 20-3: Live Blog 462
Exercise 20-4: More 404s 462
Exercise 20-5: Extended Learning Log 462
Summary 463
afterword 465
ain
Stallation and trouBleShooting 467
Python on Windows 467
Finding the Python Interpreter 467
Adding Python to Your Path Variable 468
Reinstalling Python 469
Python on macOS 469
Installing Homebrew 469
Installing Python 470
Python on Linux 470
Python Keywords and Built-in Functions 471
Python Keywords 471
Python Built-in Functions 471
Bt
ext editorS and ideS 473
Customizing Sublime Text Settings 474
Converting Tabs to Spaces 474
Setting the Line Length Indicator 474
Indenting and Unindenting Code Blocks 474
Commenting Out Blocks of Code 475
Saving Your Configuration 475
Further Customizations 475
Other Text Editors and IDEs 475
IDLE 475
Geany 476
Emacs and Vim 476xxvi Contents in Detail
Atom 476
Visual Studio Code 476
PyCharm 476
Jupyter Notebooks 477
cg
etting helP 479
First Steps 479
Try It Again 480
Take a Break 480
Refer to This Book’s Resources 480
Searching Online 481
Stack Overflow 481
The Official Python Documentation 481
Official Library Documentation 482
r/learnpython 482
Blog Posts 482
Internet Relay Chat 482
Making an IRC Account 482
Channels to Join 483
IRC Culture 483
Slack 483
Discord 484
d
uSing git for VerSion control 485
Installing Git 486
Installing Git on Windows 486
Installing Git on macOS 486
Installing Git on Linux 486
Configuring Git 486
Making a Project 486
Ignoring Files 487
Initializing a Repository 487
Checking the Status 487
Adding Files to the Repository 488
Making a Commit 488
Checking the Log 489
The Second Commit 489
Reverting a Change 490
Checking Out Previous Commits 491
Deleting the Repository 493
index
Index496 Index
Alien Invasion project, continued
Play button
adding, 280–285
deactivating, 284
drawing, 281
hiding the mouse
cursor, 284
resetting the game, 283
starting the game, 283
scoring, 288–300
all hits, 292
high score, 294
increasing point values, 292
level, 296–298
number of ships, 298–300
resetting, 291
rounding and
formatting, 293–294
score attribute, 288
updating, 291
settings, storing, 231
ship
adjusting speed, 241–243
continuous movement,
239–241
finding an image, 232
limiting range, 243
amusement_park.py, 80–83
and keyword, 75
API (application programming
interface), 359
calls, 359
for GitHub, 371
for Hacker News, 372–375
processing responses, 361–365
rate limits, 365
requesting data, 360
visualizing results, 366–371
apostrophe.py, 24
append() method, 37
application programming interface.
See API (application
programming interface)
arguments, 131–137. See also
functions: arguments
arithmetic, 26
as keyword, 152
assert methods, 212, 216
asterisk (*) operator, 147
attributes, 159. See also classes:
attributes
B
banned_users.py, 77
bicycles.py, 34–36
.bmp (bitmap) image files, 232
body
of a function, 130
of an HTML file, 440
Boolean values, 77, 456
Bootstrap, 438–447
braces ({}), 92, 105
built-in functions, 471
C
CamelCase, 181
car.py, 162–179
cars.py, 43–45, 72
cities.py, 121
classes
attributes, 159
accessing, 160
default values, 163
modifying, 164–166
creating, 158–162
importing, 174–179
all classes from a
module, 177
multiple classes, 175–177
single class, 174–175
inheritance, 167–173
attributes and methods, 169
child classes, 167
__init__() method, 167–169
instances as attributes,
170–172
overriding methods, 170
parent classes, 167
subclasses, 168
super() function, 168
superclasses, 168
instances, 157
methods, 159
calling, 160
__init__() method, 159Index 497
modeling real-world objects, 173
multiple instances, 161
naming conventions, 159
objects, 157
styling guidelines, 181
comma-separated value files. See
CSV (comma-separated
value) files
comment.py, 29
comments, 29–30
conditional tests, 72–77. See also
if statements
confirmed_users.py, 124
constants, 28
counting.py, 118, 122
CSV (comma-separated value) files,
334–346
error-checking, 343–345
parsing headers, 334–335
reading data, 336
D
data analysis, 305
databases. See Django: databases
data visualization, 305. See also
Matplotlib; Plotly
datetime module, 337–339
death_valley_highs_lows.py, 343–345
decorators, 429
default values, 134
class attributes, 163
function parameters, 134
def keyword, 130
del statement, 39
dice_visual.py, 328–330
dictionaries
defining, 92
empty, 94
formatting larger, 97
get() method, 98
KeyError, 98
key-value pairs, 92–99
adding, 93
removing, 96
looping through, 99–105
keys, 101
keys in order, 103
key-value pairs, 99
values, 104
ordering in, 94
sorting a list of, 374
values
accessing, 93
modifying, 95
die.py, 324
die_visual.py, 325–327
dimensions.py, 66–67
Discord, 48
div (HTML), 441
division (/), 26
division_calculator.py, 194–197
Django, 379. See also Heroku;
Learning Log project
admin site, 387–392
registering models, 388, 391
associating data with users, 435
Bootstrap, 438–447
card, 446
collapsible navigation, 440
container element, 443
django-bootstrap4 app, 438
HTML headers, 439–440
jumbotron, 443
navigation bar, 440–442
styling forms, 444–445
commands
createsuperuser, 388
flush, 433
makemigrations, 387, 391, 432
migrate, 383
shell, 392
startapp, 385, 421
startproject, 382
creating a project, 381
databases
cascading delete, 390
creating, 382
foreign keys, 390
many-to-one
relationships, 390
migrating, 383, 391
queries, 404, 433
querysets, 392–393, 401
required (non-nullable)
fields, 432498 Index
Django, continued
databases, continued
resetting, 433
SQLite, 383
decorators, 429
deployment. See Heroku
development server, 383, 389
documentation
Django, 379
models, 386
queries, 394
templates, 406
forms, 410–420
action argument, 413
cross-site request
forgery, 413
displaying, 413
GET and POST requests, 412
ModelForm, 410, 414
pre-filling with data, 419
processing, 412, 416
validation, 410
widgets, 414
get_object_or_404() method, 460
hashes (for passwords), 388
HTML
div element, 441
main element, 442
margin, 443
padding, 443
span element, 442
HTTP 404 error, 434
INSTALLED_APPS, 386, 421, 438
installing, 381
localhost, 383
logging out, 424
login page, 422
@login_required, 429
login template, 422
mapping URLs, 395–396
migrating the database,
383, 391
models, 385–393, 431
privileges, 387
projects (vs. apps), 384
redirect() function, 411
registration page, 426–428
release cycle, 381
restricting access to data,
433–435
restricting access to pages,
428–435
settings.py
INSTALLED APPS, 386, 421, 438
LOGIN_URL, 429
SECRET_KEY, 461
shell, 392, 431
starting an app, 385
starting a new project, 382
static files, 448
styling. See Django: Bootstrap
superuser, 387
templates, 397
anchor tags, 399
block tags, 399
context dictionary, 401
filters, 405
for loop, 402
indentation in, 399
inheritance, 398
linebreaks filter, 405
template tags, 399
third-party apps, 438
URLs
capturing values, 404
namespaces, 399
URL patterns, 395–396
url template tag, 399
user ID values, 431
users
default login view, 422
displaying message to
logged-in user, 424
logging in a user, 427
UserCreationForm, 427
versions, 381
views, 396
retrieving objects, 401, 404
docstrings, 130
dog.py, 158–162
dot notation, 151, 160
double asterisk (**) operator, 149Index 499
E
earthquakes. See mapping
earthquakes
electric_car.py, 168–173
electric_car.py module, 178
enumerate() function, 335
environment variables, 456
epoch time, 366
eq_explore_data.py, 348–351
equality operator (==), 72–73
eq_world_map.py, 351–357
even_numbers.py, 58
even_or_odd.py, 117
exceptions, 183, 194–202
deciding which errors to
report, 201
else blocks, 196
failing silently, 200
FileNotFoundError, 197
handling, 194
try-except blocks, 194
using to prevent crashes, 195
ZeroDivisionError, 194
exponents (**), 26
F
favorite_languages.py, 97–98
FileNotFoundError, 197
file_reader.py, 184–188
files
closing, 185
file paths, 185
absolute, 186
relative, 186
opening, 184
append mode, 192
read mode, 192
write mode, 192
reading from, 184–190
entire files, 184–185
line by line, 187
making a list of lines, 188
working with contents, 188
working with large
files, 189
writing to
by appending, 193
empty files, 191
multiple lines, 192
first_numbers.py, 57
flags, 120
floats, 26
foods.py, 63–65
for loops, 49. See also dictionaries;
lists
formatted_name.py, 138–140
full_name.py, 21–22
functions, 129
alias (as), 152
arguments, 131–137
arbitrary keyword, 148
arbitrary number of, 147
avoiding errors, 136
keyword, 133
lists as, 143–146
mixing positional and
arbitrary, 148
optional, 138
order of, 133
positional, 132–133
built-in, 471
calling, 130–137
equivalent calls, 135–136
multiple times, 132
defining, 130
dictionaries, returning, 140
lists in
modifying, 143–145
protecting, 145
modules, 150–155
alias (as), 153
importing all
functions (*), 153
importing entire
modules, 150
importing specific
functions, 152
parameters, default
values for, 134
passing information to. See
functions: arguments
return values, 137–142
styling, 154500 Index
G
games. See Alien Invasion project;
Pygame
Geany, 476
GET requests, 412
getting help
Discord, 484
IRC (Internet Relay Chat),
482–483
official Python documentation,
481
online resources, 480
r/learnpython, 482
rubber duck debugging, 480
Slack, 483
Stack Overflow, 481
three main questions, 479
Git, 360, 450
branches, 452, 488
commits, 360, 450
checking out, 491–493
making, 452, 457, 460, 488,
490, 493
configuring, 451, 486
detached HEAD, 492
files
adding, 452, 460, 488, 493
ignoring, 451, 487
HEAD, 492
installing, 450, 486
log, checking, 489
repositories, 360
deleting, 493
initializing, 452, 487, 493
reverting changes, 490
status, checking, 452, 457,
487–493
GitHub, 360
greater than (>), 75
greater than or equal to (>=), 75
greeter.py, 114, 130–131
greet_users.py, 143
gunicorn package, 448
H
Hacker News, 372
hash mark (#), for comments, 29
head, of an HTML file, 440
HEAD (Git), 492
Hello World, 9
hello_git.py, 486–491
hello_world.py, 10, 15–19
Heroku, 437. See also Django; Git;
Learning Log project
Bash shell, 454
CLI, installing, 448
commands
config, 458
destroy, 462
login, 453
open, 453
ps, 453
rename, 455
run, 454
set, 458
databases, setting up, 454
django-heroku package, 448
documentation, 453
environment variables, setting,
456–458
error pages, custom, 458–460
free plan, limitations of,
448, 456
making an account, 448
Procfile, 450
projects
deleting, 461
pushing to Heroku,
452–453, 457
viewing live, 453
Python runtime, specifying, 449
requirements.txt, 448–449
securing, 456
settings.py, modifying for, 450,
456, 459
superuser, creating, 454–455
URLs, user-friendly, 455
hidden files, 451Index 501
hn_article.py, 372
hn_submissions.py, 373
Homebrew, 469
I
IDE (integrated development
environment), 473
IDLE, 475
if statements
and keyword, 75
Boolean expressions, 77
checking for
equality (==), 72
equality, ignoring case, 73
empty lists, 87
inequality (!=), 74
items in a list, 76
items not in a list, 77
conditional tests, 72–77
elif statement, 80–84
else statement, 79
lists and, 85–88
numerical comparisons, 74–76
or keyword, 76
simple, 78
styling guidelines, 90
testing multiple conditions,
83–84
immutable, 65
import *, 153
import this, 30
indentation errors, 53–56
index errors, 47
inequality operator (!=), 74
infinite loops, 122
inheritance, 167. See also classes:
inheritance
input() function, 114–117
numerical input, 115–116
prompts, 114
insert() method, 38
IRC (Internet Relay Chat), 482–483
itemgetter() function, 374
items() method, 100
J
JSON files
examining data, 347
geoJSON file format, 349
json.dump() function, 348
json.load() function, 204
jumbotron, 443
K
keys() method, 101
key-value pairs, 92–99. See also
dictionaries
keyword arguments, 132, 133. See
also functions
keywords, 471
L
language_survey.py, 217
Learning Log project, 379. See also
Django; Heroku
deployment. See Git, Heroku
files
404.html, 458
500.html, 459
admin.py, 388
base.html, 399, 403, 423, 425,
428, 439–443
edit_entry.html, 419
forms.py, 410, 414
.gitignore, 451
index.html, 397, 443
learning_logs/urls.py, 395,
401, 404, 411, 415, 418
learning_log/urls.py, 395, 422
logged_out.html, 425
login.html, 422–423, 444
models.py, 385, 390, 431
new_entry.html, 416
new_topic.html, 412
Procfile, 450
register.html, 427
requirements.txt, 448
runtime.txt, 449
settings.py, 386, 421, 429, 450,
456, 459502 Index
Learning Log project, continued
files, continued
topic.html, 404–405, 417, 420
topics.html, 402, 405, 413, 445
users/urls.py, 422, 426
users/views.py, 426
views.py, 396, 401, 404,
411, 415, 418, 429, 430,
433, 460
pages
edit entry, 418–420
home, 394–398
login, 422–424
logout, 424
new entry, 414–417
new topic, 410–413
register, 426
topic, 403
topics, 400–403
users app, 421–428
virtual environment, 380–381
writing a specification
(spec), 380
len() function, 45
less than (<), 75
less than or equal to (<=), 75
Linux
Hello World, running, 10
Python
checking installed version, 8
installing, 470
troubleshooting
installation, 11
Sublime Text, installing, 9
terminal
running programs from, 12
starting Python session, 9
lists, 33
as arguments, 143–146
copying, 63–65
elements
accessing, 34
accessing last, 35
adding with append(), 37
adding with insert(), 38
identifying unique, 104
modifying, 36
removing with del, 39
removing with pop(), 39–41
removing with remove(), 41
empty, 38
enumerate() function, 335
for loops, 49–56
nested, 109, 263
if statements and, 85–88
indentation errors, 53–56
indexes, 35
errors, 46–47
negative, 35
len() function, 45
list comprehensions, 59
naming, 34
numerical lists, 57–60
range() function, 58–59
removing all occurrences of a
value, 125
slices, 61–63
sorting, 43–46
reverse() method, 45
sorted() function, 44
sort() method, 43
logical errors, 54
M
macOS
Hello World, running, 10
Python
checking installed version, 7
installing, with Homebrew,
469–470
installing, official
version, 7–8
troubleshooting
installation, 11
Sublime Text, installing, 8
terminal
running programs from, 12
starting a Python session, 8
magicians.py, 50–53
magic_number.py, 75
making_pizzas.py, 151–153
mapping earthquakes, 347–357
building a world map, 351
colorscales, 354Index 503
data
downloading, 347, 358
examining JSON data, 347
extracting locations, 351
extracting magnitudes, 350
geoJSON file format, 349
hover text, 356
latitude-longitude ordering, 349
magnitudes, representing, 353
Scattergeo chart type, 352
Matplotlib, 306–323, 336–347
axes
axis() method, 313
ax variable, 307
removing, 321
fig variable, 307
formatting plots
alpha argument, 342
built-in styles, 310
colormaps, 314
custom colors, 314
labels, 307–308
line thickness, 307
shading, 342
size, 322
gallery, 306
installing, 306
line graphs, 306
plot() method, 307, 309
pyplot module, 307
saving plots, 315
scatter plots, 310–313
subplots() function, 307
methods, 20, 236–237. See also
classes
modules, 150. See also classes:
modules; functions:
modules
modulo operator (%), 116–117, 122
motorcycles.py, 37–42
mountain_poll.py, 126
mpl_squares.py, 306–310
multiplication (*), 26
my_car.py, 175
my_cars.py, 177–179
my_electric_car.py, 176
N
name errors, 17
name_function.py, 210–215
name.py, 20
names.py, 210
nesting, 106–112
depth, 110
dictionaries in dictionaries,
110–111
dictionaries in lists, 106–108
lists in dictionaries, 108–110
newline (\n), 22
None, 99
not (!), 74
number_reader.py, 203
numbers, 25–28
arithmetic, 26
comparisons, 74–76
exponents, 26
floats, 26
floor division (//), 260
integers, 26
mixing integers and floats, 27
order of operations, 26
round() function, 294
underscores in, 28
number_writer.py, 203
O
object-oriented programming, 157.
See also classes
open() function, 184
or keyword, 76
P
parameters, 131
parent classes, 167. See also classes:
inheritance
parrot.py, 114, 118–121
pass statement, 200
PEP 8, 68–70, 90, 154
person.py, 140–142
pets.py, 125, 132–136504 Index
pip, 228
installing Django, 381
installing Matplotlib, 306
installing Plotly, 324
installing Pygame, 228
installing Requests, 361
pi_string.py, 188–190
pizza.py, 147–148
players.py, 61–63
Plotly, 306
Bar() class, 327
data, long format, 353
formatting plots
bars, 368
colorscales, 354
hover text, 356, 369–370
marker color, 368
marker size, 353
Layout() class, 327
layout, long format, 367
x-axis, 368
y-axis, 368
gallery, 324
histogram, 326
installing, 324
offline.plot() function, 327
Python figure reference, 371
Scattergeo chart type, 352
user guide, 371
positional arguments. See functions:
arguments
POST requests, 412
printing_models.py, 143–146
Project Gutenberg, 198
.py file extension, 16
Pygame. See also Alien Invasion
project
background colors, 230–231
collisions, 268–269, 272–275,
291–292
colors, 231
creating empty windows, 229
cursor, hiding, 285
displaying text, 280
ending games, 276
event loops, 230
fullscreen mode, 244
groups, 248
drawing all elements in, 259
emptying, 271
looping through, 250
removing elements from, 251
storing elements in, 248
updating all elements in, 249
images, drawing to screen, 235
images, loading, 234
installing, 228
print() calls in, 251
quitting, 244
rect objects
creating from scratch, 247
positioning, 234, 247–248,
257–258, 260–261,
263–264
responding to input, 230
keypresses, 238
mouse clicks, 283
screen coordinates, 234
surfaces, 230
testing games, 270
pyplot module, 307
Python
>>> prompt, 4
built-in functions, 471
documentation, 481
installing
on Linux, 470
on macOS, official, 7–8
on macOS, using Homebrew,
469–470
on Windows, 5–6, 467–469
interpreter, 16
keywords, 471
PEP 8, 68–70, 90, 154
standard library, 180–181
terminal sessions, 4
versions, 4
Zen of, 30–31
Python Enhancement Proposal
(PEP), 68
python_repos.py, 361–365
python_repos_visual.py, 366–371Index 505
Q
quit values, 118–120
R
random_walk.py, 316–317
random walks, 315–323
choice() function, 317
coloring points, 319
fill_walk() method, 316
multiple walks, generating, 318
plotting, 317
RandomWalk class, 316
starting and ending points, 320
range() function, 57–59
readlines() method, 188
read() method, 185
refactoring, 206–208, 236
remember_me.py, 204–208
Requests package, 361
return values, 137
r/learnpython, 482
rollercoaster.py, 116
rolling dice, 323–330
analyzing results, 325
Die class, 324
different sizes, 329
randint() function, 324
two dice, 328
rubber duck debugging, 480
rw_visual.py, 317–323
S
scatter_squares.py, 311–315
sets, 104
sitka_highs_lows.py, 340–342
sitka_highs.py, 334–340
Slack, 483
sleep() function, 274
slice, 61
split() method, 198
square brackets ([]), 34
squares.py, 58, 60
Stack Overflow, 481
storing data, 202–205. See also JSON
strings, 19–25
changing case, 20
format() method, 22
f-strings, 21
newlines in, 22
single and double quotes, 19, 24
tabs in, 22
using variables in, 21
whitespace in, 22–24
strptime() method, 338
style guidelines, 68–70
blank lines, 69
CamelCase, 181
classes, 181
functions, 154
if statements, 90
indentation, 69
line length, 69
PEP 8, 68
Sublime Text, 4–10, 474–475
commenting out code, 475
configuring, 9
customizing, 474
indenting and unindenting
code blocks, 474
installing, 7–9
line length indicator, 474
running Python programs, 9–10
saving your configuration, 475
tabs and spaces, 474
subtraction (-), 26
superclasses, 168. See also classes:
inheritance
survey.py, 217
syntax errors, 24
syntax highlighting, 16
T
tab (\t), 22
testing code, 209–222
adding tests, 214
assert methods, 216
coverage, 211
failing tests, 212–214
passing tests, 211–212
setUp() method, 220
test case, 211
testing classes, 216–221
testing functions, 210–215
unittest module, 209
unit tests, 211506 Index
test_name_function.py, 211–215
test_survey.py, 218–221
text editors and IDEs
Atom, 476
Emacs and Vim, 476
Geany, 476
IDLE, 475
Jupyter Notebooks, 477
PyCharm, 476
Sublime Text, 4–10, 474–475
Visual Studio Code, 476
toppings.py, 74, 83–88
traceback, 18
try-except blocks, 194–202. See also
exceptions
tuples, 65–67
type errors, 66
U
unittest module, 209
unit tests, 211
Unix time, 366
user_profile.py, 148
V
values() method, 104
variables, 16–19, 28
constants, 28
as labels, 18
multiple assignment, 28
naming conventions, 17
values, 16
version control system, 485.
See also Git
virtual environment (venv), 380
voting.py, 79–80
W
weather data, 334–347
web framework, 379
while loops, 118–127
active flag, 120–121
break statement, 121
infinite, 122
moving items between lists, 124
quit values, 118–120
whitespace, 22–24
Windows
Hello World, running, 10
Python
checking installed version, 5
installing, 5–6, 467–469
troubleshooting installation,
11, 467–469
Sublime Text, installing, 7
terminal
running programs from, 12
starting a Python session, 6
with statement, 185
word_count.py, 199–201
write_message.py, 191–193
write() method, 192
Z
Zen of Python, 30–31
ZeroDivisionError, 194
كلمة سر فك الضغط : books-world.net

The Unzip Password : books-world.net

تحميل

يجب عليك التسجيل في الموقع لكي تتمكن من التحميل

تسجيل | تسجيل الدخول