upload/misc/Y9EgLx762wKqWqG7nloH/Books/Programming_Languages/Python/Python Crash Course, 2nd Edition.pdf
Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming 🔍
Matthes, Eric
No Starch Press, Incorporated, Illustrated, 2019
English [en] · PDF · 7.7MB · 2019 · 📘 Book (non-fiction) · 🚀/lgli/upload/zlib · Save
description
Uehara Sakukazu, Hirota Osamu Hen. Includes Bibliographical References. 上原作和, 広田収編.
Alternative filename
lgli/Matthes, Eric - Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming (2019, No Starch Press).pdf
Alternative filename
zlib/Computers/Programming/Matthes, Eric/Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming_18111212.pdf
Alternative title
Изучаем PYTHON. Программирование игр, визуализация данных, ВЕБ-приложения
Alternative author
Эрик Мэтиз; [перевод с английского Е. Матвеева]
Alternative author
Adobe InDesign CS6 (Windows)
Alternative author
Eric Matthes
Alternative author
Мэтиз, Эрик
Alternative publisher
ПИТЕР
Alternative edition
Бестселлер, 3-е изд., Санкт-Петербург [и др.], Russia, 2020
Alternative edition
United States, United States of America
Alternative edition
Segona edició, San Francisco :, 2019
Alternative edition
2nd edition, San Francisco, CA, 2019
Alternative edition
May 03, 2019
metadata comments
producers:
Adobe PDF Library 10.0.1
Adobe PDF Library 10.0.1
metadata comments
Source title: Python Crash Course, 2nd Edition: A Hands-On, Project-Based Introduction to Programming
metadata comments
Пер.: Matthes, Eric Python crash course San Francisco : No Starch Press, cop. 2019 978-1593279288
metadata comments
РГБ
metadata comments
Russian State Library [rgb] MARC:
=001 010381697
=005 20200819094036.0
=008 200812s2020\\\\ru\\\\\\\\\\\\0||\|\rus|d
=017 \\ $a КН-П-20-042039 $b RuMoRKP
=020 \\ $a 978-5-4461-1528-0
=040 \\ $a RuMoRGB $b rus $e rcr
=041 1\ $a rus $h eng
=044 \\ $a ru
=084 \\ $a З973.2-018.19Python,0 $2 rubbk
=100 1\ $a Мэтиз, Эрик
=245 00 $a Изучаем PYTHON. Программирование игр, визуализация данных, ВЕБ-приложения $c Эрик Мэтиз ; [перевод с английского Е. Матвеева]
=250 \\ $a 3-е изд.
=260 \\ $a Санкт-Петербург [и др.] $b ПИТЕР $c 2020
=300 \\ $a 551 с. $b ил. $c 24 см
=336 \\ $a Текст (визуальный)
=337 \\ $a непосредственный
=490 0\ $a Бестселлер
=534 \\ $p Пер.: $a Matthes, Eric $t Python crash course $c San Francisco : No Starch Press, cop. 2019 $z 978-1593279288
=650 \7 $a Техника. Технические науки -- Энергетика. Радиоэлектроника -- Радиоэлектроника -- Вычислительная техника -- Вычислительные машины электронные цифровые -- Программирование -- Языки программирования -- Python $2 rubbk
=852 \\ $a РГБ $b FB $j 3 20-32/76 $x 90
=852 7\ $a РГБ $b CZ2 $h З973.2-018/М97 $x 83
=852 \\ $a РГБ $b ORF $x 82
=852 \\ $a РГБ $b ORF $x 82
=001 010381697
=005 20200819094036.0
=008 200812s2020\\\\ru\\\\\\\\\\\\0||\|\rus|d
=017 \\ $a КН-П-20-042039 $b RuMoRKP
=020 \\ $a 978-5-4461-1528-0
=040 \\ $a RuMoRGB $b rus $e rcr
=041 1\ $a rus $h eng
=044 \\ $a ru
=084 \\ $a З973.2-018.19Python,0 $2 rubbk
=100 1\ $a Мэтиз, Эрик
=245 00 $a Изучаем PYTHON. Программирование игр, визуализация данных, ВЕБ-приложения $c Эрик Мэтиз ; [перевод с английского Е. Матвеева]
=250 \\ $a 3-е изд.
=260 \\ $a Санкт-Петербург [и др.] $b ПИТЕР $c 2020
=300 \\ $a 551 с. $b ил. $c 24 см
=336 \\ $a Текст (визуальный)
=337 \\ $a непосредственный
=490 0\ $a Бестселлер
=534 \\ $p Пер.: $a Matthes, Eric $t Python crash course $c San Francisco : No Starch Press, cop. 2019 $z 978-1593279288
=650 \7 $a Техника. Технические науки -- Энергетика. Радиоэлектроника -- Радиоэлектроника -- Вычислительная техника -- Вычислительные машины электронные цифровые -- Программирование -- Языки программирования -- Python $2 rubbk
=852 \\ $a РГБ $b FB $j 3 20-32/76 $x 90
=852 7\ $a РГБ $b CZ2 $h З973.2-018/М97 $x 83
=852 \\ $a РГБ $b ORF $x 82
=852 \\ $a РГБ $b ORF $x 82
Alternative description
Brief Contents 11
Contents in Detail 13
Preface to
the Second Edition 29
Acknowledgments 33
Introduction 35
Who Is This Book For? 36
What Can You Expect to Learn? 36
Online Resources 37
Why Python? 38
Part I: Basics 39
Chapter 1: Getting Started 41
Setting Up Your Programming Environment 41
Python Versions 42
Running Snippets of Python Code 42
About the Sublime Text Editor 42
Python on Different Operating Systems 43
Python on Windows 43
Python on macOS 45
Python on Linux 46
Running a Hello World Program 47
Configuring Sublime Text to Use the Correct Python Version 47
Running hello_world.py 48
Troubleshooting 49
Running Python Programs from a Terminal 50
On Windows 50
On macOS and Linux 50
Summary 51
Chapter 2: Variables and Simple Data Types 53
What Really Happens When You Run hello_world.py 53
Variables 54
Naming and Using Variables 55
Avoiding Name Errors When Using Variables 55
Variables Are Labels 56
Strings 57
Changing Case in a String with Methods 58
Using Variables in Strings 59
Adding Whitespace to Strings with Tabs or Newlines 60
Stripping Whitespace 60
Avoiding Syntax Errors with Strings 62
Numbers 63
Integers 64
Floats 64
Integers and Floats 65
Underscores in Numbers 66
Multiple Assignment 66
Constants 66
Comments 67
How Do You Write Comments? 67
What Kind of Comments Should You Write? 67
The Zen of Python 68
Summary 70
Chapter 3: Introducing Lists 71
What Is a List? 71
Accessing Elements in a List 72
Index Positions Start at 0, Not 1 73
Using Individual Values from a List 73
Changing, Adding, and Removing Elements 74
Modifying Elements in a List 74
Adding Elements to a List 75
Removing Elements from a List 76
Organizing a List 81
Sorting a List Permanently with the sort() Method 81
Sorting a List Temporarily with the sorted() Function 82
Printing a List in Reverse Order 83
Finding the Length of a List 83
Avoiding Index Errors When Working with Lists 84
Summary 86
Chapter 4: Working with Lists 87
Looping Through an Entire List 87
A Closer Look at Looping 88
Doing More Work Within a for Loop 89
Doing Something After a for Loop 90
Avoiding Indentation Errors 91
Forgetting to Indent 91
Forgetting to Indent Additional Lines 92
Indenting Unnecessarily 93
Indenting Unnecessarily After the Loop 93
Forgetting the Colon 94
Making Numerical Lists 95
Using the range() Function 95
Using range() to Make a List of Numbers 96
Simple Statistics with a List of Numbers 97
List Comprehensions 97
Working with Part of a List 99
Slicing a List 99
Looping Through a Slice 100
Copying a List 101
Tuples 103
Defining a Tuple 104
Looping Through All Values in a Tuple 105
Writing over a Tuple 105
Styling Your Code 106
The Style Guide 106
Indentation 107
Line Length 107
Blank Lines 107
Other Style Guidelines 108
Summary 108
Chapter 5: if Statements 109
A Simple Example 110
Conditional Tests 110
Checking for Equality 110
Ignoring Case When Checking for Equality 111
Checking for Inequality 112
Numerical Comparisons 112
Checking Multiple Conditions 113
Checking Whether a Value Is in a List 114
Checking Whether a Value Is Not in a List 115
Boolean Expressions 115
if Statements 116
Simple if Statements 116
if-else Statements 117
The if-elif-else Chain 118
Using Multiple elif Blocks 120
Omitting the else Block 120
Testing Multiple Conditions 121
Using if Statements with Lists 123
Checking for Special Items 124
Checking That a List Is Not Empty 125
Using Multiple Lists 126
Styling Your if Statements 128
Summary 128
Chapter 6: Dictionaries 129
A Simple Dictionary 130
Working with Dictionaries 130
Accessing Values in a Dictionary 131
Adding New Key-Value Pairs 131
Starting with an Empty Dictionary 132
Modifying Values in a Dictionary 133
Removing Key-Value Pairs 134
A Dictionary of Similar Objects 135
Using get() to Access Values 136
Looping Through a Dictionary 137
Looping Through All Key-Value Pairs 137
Looping Through All the Keys in a Dictionary 139
Looping Through a Dictionary’s Keys in a Particular Order 141
Looping Through All Values in a Dictionary 142
Nesting 144
A List of Dictionaries 144
A List in a Dictionary 146
A Dictionary in a Dictionary 148
Summary 150
Chapter 7: User Input and while Loops 151
How the input() Function Works 152
Writing Clear Prompts 152
Using int() to Accept Numerical Input 153
The Modulo Operator 154
Introducing while Loops 156
The while Loop in Action 156
Letting the User Choose When to Quit 156
Using a Flag 158
Using break to Exit a Loop 159
Using continue in a Loop 160
Avoiding Infinite Loops 160
Using a while Loop with Lists and Dictionaries 162
Moving Items from One List to Another 162
Removing All Instances of Specific Values from a List 163
Filling a Dictionary with User Input 164
Summary 165
Chapter 8: Functions 167
Defining a Function 168
Passing Information to a Function 168
Arguments and Parameters 169
Passing Arguments 169
Positional Arguments 170
Keyword Arguments 171
Default Values 172
Equivalent Function Calls 173
Avoiding Argument Errors 174
Return Values 175
Returning a Simple Value 176
Making an Argument Optional 176
Returning a Dictionary 178
Using a Function with a while Loop 179
Passing a List 181
Modifying a List in a Function 181
Preventing a Function from Modifying a List 183
Passing an Arbitrary Number of Arguments 185
Mixing Positional and Arbitrary Arguments 186
Using Arbitrary Keyword Arguments 186
Storing Your Functions in Modules 188
Importing an Entire Module 188
Importing Specific Functions 190
Using as to Give a Function an Alias 190
Using as to Give a Module an Alias 191
Importing All Functions in a Module 191
Styling Functions 192
Summary 193
Chapter 9: Classes 195
Creating and Using a Class 196
Creating the Dog Class 196
Making an Instance from a Class 198
Working with Classes and Instances 200
The Car Class 200
Setting a Default Value for an Attribute 201
Modifying Attribute Values 202
Inheritance 205
The __init__() Method for a Child Class 205
Defining Attributes and Methods for the Child Class 207
Overriding Methods from the Parent Class 208
Instances as Attributes 208
Modeling Real-World Objects 211
Importing Classes 212
Importing a Single Class 212
Storing Multiple Classes in a Module 213
Importing Multiple Classes from a Module 215
Importing an Entire Module 215
Importing All Classes from a Module 215
Importing a Module into a Module 216
Using Aliases 217
Finding Your Own Workflow 217
The Python Standard Library 218
Styling Classes 219
Summary 220
Chapter 10: Files and Exceptions 221
Reading from a File 222
Reading an Entire File 222
File Paths 223
Reading Line by Line 225
Making a List of Lines from a File 226
Working with a File’s Contents 226
Large Files: One Million Digits 227
Is Your Birthday Contained in Pi? 228
Writing to a File 229
Writing to an Empty File 229
Writing Multiple Lines 230
Appending to a File 231
Exceptions 232
Handling the ZeroDivisionError Exception 232
Using try-except Blocks 232
Using Exceptions to Prevent Crashes 233
The else Block 234
Handling the FileNotFoundError Exception 235
Analyzing Text 236
Working with Multiple Files 237
Failing Silently 238
Deciding Which Errors to Report 239
Storing Data 240
Using json.dump() and json.load() 241
Saving and Reading User-Generated Data 242
Refactoring 244
Summary 246
Chapter 11: Testing Your Code 247
Testing a Function 248
Unit Tests and Test Cases 249
A Passing Test 249
A Failing Test 250
Responding to a Failed Test 251
Adding New Tests 252
Testing a Class 254
A Variety of Assert Methods 254
A Class to Test 255
Testing the AnonymousSurvey Class 256
The setUp() Method 258
Summary 260
Part II: Projects 261
Project 1: Alien Invasion 263
Chapter 12: A Ship that Fires Bullets 265
Planning Your Project 266
Installing Pygame 266
Starting the Game Project 267
Creating a Pygame Window and Responding to User Input 267
Setting the Background Color 268
Creating a Settings Class 269
Adding the Ship Image 270
Creating the Ship Class 271
Drawing the Ship to the Screen 273
Refactoring: The _check_events() and _update_screen() Methods 274
The _check_events() Method 274
The _update_screen() Method 275
Piloting the Ship 276
Responding to a Keypress 276
Allowing Continuous Movement 277
Moving Both Left and Right 278
Adjusting the Ship’s Speed 279
Limiting the Ship’s Range 281
Refactoring _check_events() 281
Pressing Q to Quit 282
Running the Game in Fullscreen Mode 282
A Quick Recap 283
alien_invasion.py 283
settings.py 284
ship.py 284
Shooting Bullets 284
Adding the Bullet Settings 285
Creating the Bullet Class 285
Storing Bullets in a Group 286
Firing Bullets 287
Deleting Old Bullets 288
Limiting the Number of Bullets 289
Creating the _update_bullets() Method 290
Summary 291
Chapter 13: Aliens! 293
Reviewing the Project 294
Creating the First Alien 294
Creating the Alien Class 295
Creating an Instance of the Alien 296
Building the Alien Fleet 297
Determining How Many Aliens Fit in a Row 298
Creating a Row of Aliens 298
Refactoring _create_fleet() 300
Adding Rows 300
Making the Fleet Move 303
Moving the Aliens Right 303
Creating Settings for Fleet Direction 304
Checking Whether an Alien Has Hit the Edge 304
Dropping the Fleet and Changing Direction 305
Shooting Aliens 306
Detecting Bullet Collisions 306
Making Larger Bullets for Testing 308
Repopulating the Fleet 308
Speeding Up the Bullets 309
Refactoring _update_bullets() 309
Ending the Game 310
Detecting Alien and Ship Collisions 310
Responding to Alien and Ship Collisions 311
Aliens that Reach the Bottom of the Screen 314
Game Over! 314
Identifying When Parts of the Game Should Run 315
Summary 316
Chapter 14: Scoring 317
Adding the Play Button 318
Creating a Button Class 318
Drawing the Button to the Screen 319
Starting the Game 321
Resetting the Game 321
Deactivating the Play Button 322
Hiding the Mouse Cursor 322
Leveling Up 323
Modifying the Speed Settings 323
Resetting the Speed 325
Scoring 326
Displaying the Score 326
Making a Scoreboard 327
Updating the Score as Aliens Are Shot Down 329
Resetting the Score 329
Making Sure to Score All Hits 330
Increasing Point Values 330
Rounding the Score 331
High Scores 332
Displaying the Level 334
Displaying the Number of Ships 336
Summary 340
Project 2: Data Visualization 341
Chapter 15: Generating Data 343
Installing Matplotlib 344
Plotting a Simple Line Graph 344
Changing the Label Type and Line Thickness 345
Correcting the Plot 347
Using Built-in Styles 348
Plotting and Styling Individual Points with scatter() 348
Plotting a Series of Points with scatter() 350
Calculating Data Automatically 350
Defining Custom Colors 352
Using a Colormap 352
Saving Your Plots Automatically 353
Random Walks 353
Creating the RandomWalk() Class 354
Choosing Directions 354
Plotting the Random Walk 355
Generating Multiple Random Walks 356
Styling the Walk 357
Rolling Dice with Plotly 361
Installing Plotly 362
Creating the Die Class 362
Rolling the Die 363
Analyzing the Results 363
Making a Histogram 364
Rolling Two Dice 366
Rolling Dice of Different Sizes 367
Summary 369
Chapter 16: Downloading Data 371
The CSV File Format 372
Parsing the CSV File Headers 372
Printing the Headers and Their Positions 373
Extracting and Reading Data 374
Plotting Data in a Temperature Chart 374
The datetime Module 375
Plotting Dates 376
Plotting a Longer Timeframe 378
Plotting a Second Data Series 378
Shading an Area in the Chart 380
Error Checking 381
Downloading Your Own Data 383
Mapping Global Data Sets: JSON Format 385
Downloading Earthquake Data 385
Examining JSON Data 385
Making a List of All Earthquakes 388
Extracting Magnitudes 388
Extracting Location Data 389
Building a World Map 389
A Different Way of Specifying Chart Data 391
Customizing Marker Size 391
Customizing Marker Colors 392
Other Colorscales 394
Adding Hover Text 394
Summary 396
Chapter 17: Working with APIs 397
Using a Web API 397
Git and GitHub 398
Requesting Data Using an API Call 398
Installing Requests 399
Processing an API Response 399
Working with the Response Dictionary 400
Summarizing the Top Repositories 402
Monitoring API Rate Limits 403
Visualizing Repositories Using Plotly 404
Refining Plotly Charts 406
Adding Custom Tooltips 407
Adding Clickable Links to Our Graph 408
More About Plotly and the GitHub API 409
The Hacker News API 410
Summary 413
Project 3: Web Applications 415
Chapter 18: Getting Started with Django 417
Setting Up a Project 418
Writing a Spec 418
Creating a Virtual Environment 418
Activating the Virtual Environment 419
Installing Django 419
Creating a Project in Django 420
Creating the Database 420
Viewing the Project 421
Starting an App 422
Defining Models 423
Activating Models 424
The Django Admin Site 425
Defining the Entry Model 428
Migrating the Entry Model 429
Registering Entry with the Admin Site 429
The Django Shell 430
Making Pages: The Learning Log Home Page 432
Mapping a URL 433
Writing a View 434
Writing a Template 435
Building Additional Pages 436
Template Inheritance 436
The Topics Page 438
Individual Topic Pages 441
Summary 445
Chapter 19: User Accounts 447
Allowing Users to Enter Data 448
Adding New Topics 448
Adding New Entries 452
Editing Entries 456
Setting Up User Accounts 459
The users App 459
The Login Page 460
Logging Out 462
The Registration Page 464
Allowing Users to Own Their Data 466
Restricting Access with @login_required 467
Connecting Data to Certain Users 468
Restricting Topics Access to Appropriate Users 471
Protecting a User’s Topics 472
Protecting the edit_entry Page 472
Associating New Topics with the Current User 473
Summary 474
Chapter 20: Styling and Deploying an App 475
Styling Learning Log 476
The django-bootstrap4 App 476
Using Bootstrap to Style Learning Log 476
Modifying base.html 477
Styling the Home Page Using a Jumbotron 481
Styling the Login Page 482
Styling the Topics Page 483
Styling the Entries on the Topic Page 484
Deploying Learning Log 486
Making a Heroku Account 486
Installing the Heroku CLI 486
Installing Required Packages 486
Creating a requirements.txt File 486
Specifying the Python Runtime 487
Modifying settings.py for Heroku 488
Making a Procfile to Start Processes 488
Using Git to Track the Project’s Files 488
Pushing to Heroku 490
Setting Up the Database on Heroku 492
Refining the Heroku Deployment 492
Securing the Live Project 494
Committing and Pushing Changes 495
Setting Environment Variables on Heroku 496
Creating Custom Error Pages 496
Ongoing Development 499
The SECRET_KEY Setting 499
Deleting a Project on Heroku 499
Summary 501
Afterword 503
Appendix A: Installation and Troubleshooting 505
Python on Windows 505
Finding the Python Interpreter 505
Adding Python to Your Path Variable 506
Reinstalling Python 507
Python on macOS 507
Installing Homebrew 507
Installing Python 508
Python on Linux 508
Python Keywords and Built-in Functions 509
Python Keywords 509
Python Built-in Functions 509
Appendix B: Text Editors and IDEs 511
Customizing Sublime Text Settings 512
Converting Tabs to Spaces 512
Setting the Line Length Indicator 512
Indenting and Unindenting Code Blocks 512
Commenting Out Blocks of Code 513
Saving Your Configuration 513
Further Customizations 513
Other Text Editors and IDEs 513
IDLE 513
Geany 514
Emacs and Vim 514
Atom 514
Visual Studio Code 514
PyCharm 514
Jupyter Notebooks 515
Appendix C: Getting Help 517
First Steps 517
Try It Again 518
Take a Break 518
Refer to This Book’s Resources 518
Searching Online 519
Stack Overflow 519
The Official Python Documentation 519
Official Library Documentation 520
r/learnpython 520
Blog Posts 520
Internet Relay Chat 520
Making an IRC Account 520
Channels to Join 521
IRC Culture 521
Slack 521
Discord 522
Appendix D: Using Git for Version Control 523
Installing Git 524
Installing Git on Windows 524
Installing Git on macOS 524
Installing Git on Linux 524
Configuring Git 524
Making a Project 524
Ignoring Files 525
Initializing a Repository 525
Checking the Status 525
Adding Files to the Repository 526
Making a Commit 526
Checking the Log 527
The Second Commit 527
Reverting a Change 528
Checking Out Previous Commits 529
Deleting the Repository 531
Index 533
Blank Page 547
Contents in Detail 13
Preface to
the Second Edition 29
Acknowledgments 33
Introduction 35
Who Is This Book For? 36
What Can You Expect to Learn? 36
Online Resources 37
Why Python? 38
Part I: Basics 39
Chapter 1: Getting Started 41
Setting Up Your Programming Environment 41
Python Versions 42
Running Snippets of Python Code 42
About the Sublime Text Editor 42
Python on Different Operating Systems 43
Python on Windows 43
Python on macOS 45
Python on Linux 46
Running a Hello World Program 47
Configuring Sublime Text to Use the Correct Python Version 47
Running hello_world.py 48
Troubleshooting 49
Running Python Programs from a Terminal 50
On Windows 50
On macOS and Linux 50
Summary 51
Chapter 2: Variables and Simple Data Types 53
What Really Happens When You Run hello_world.py 53
Variables 54
Naming and Using Variables 55
Avoiding Name Errors When Using Variables 55
Variables Are Labels 56
Strings 57
Changing Case in a String with Methods 58
Using Variables in Strings 59
Adding Whitespace to Strings with Tabs or Newlines 60
Stripping Whitespace 60
Avoiding Syntax Errors with Strings 62
Numbers 63
Integers 64
Floats 64
Integers and Floats 65
Underscores in Numbers 66
Multiple Assignment 66
Constants 66
Comments 67
How Do You Write Comments? 67
What Kind of Comments Should You Write? 67
The Zen of Python 68
Summary 70
Chapter 3: Introducing Lists 71
What Is a List? 71
Accessing Elements in a List 72
Index Positions Start at 0, Not 1 73
Using Individual Values from a List 73
Changing, Adding, and Removing Elements 74
Modifying Elements in a List 74
Adding Elements to a List 75
Removing Elements from a List 76
Organizing a List 81
Sorting a List Permanently with the sort() Method 81
Sorting a List Temporarily with the sorted() Function 82
Printing a List in Reverse Order 83
Finding the Length of a List 83
Avoiding Index Errors When Working with Lists 84
Summary 86
Chapter 4: Working with Lists 87
Looping Through an Entire List 87
A Closer Look at Looping 88
Doing More Work Within a for Loop 89
Doing Something After a for Loop 90
Avoiding Indentation Errors 91
Forgetting to Indent 91
Forgetting to Indent Additional Lines 92
Indenting Unnecessarily 93
Indenting Unnecessarily After the Loop 93
Forgetting the Colon 94
Making Numerical Lists 95
Using the range() Function 95
Using range() to Make a List of Numbers 96
Simple Statistics with a List of Numbers 97
List Comprehensions 97
Working with Part of a List 99
Slicing a List 99
Looping Through a Slice 100
Copying a List 101
Tuples 103
Defining a Tuple 104
Looping Through All Values in a Tuple 105
Writing over a Tuple 105
Styling Your Code 106
The Style Guide 106
Indentation 107
Line Length 107
Blank Lines 107
Other Style Guidelines 108
Summary 108
Chapter 5: if Statements 109
A Simple Example 110
Conditional Tests 110
Checking for Equality 110
Ignoring Case When Checking for Equality 111
Checking for Inequality 112
Numerical Comparisons 112
Checking Multiple Conditions 113
Checking Whether a Value Is in a List 114
Checking Whether a Value Is Not in a List 115
Boolean Expressions 115
if Statements 116
Simple if Statements 116
if-else Statements 117
The if-elif-else Chain 118
Using Multiple elif Blocks 120
Omitting the else Block 120
Testing Multiple Conditions 121
Using if Statements with Lists 123
Checking for Special Items 124
Checking That a List Is Not Empty 125
Using Multiple Lists 126
Styling Your if Statements 128
Summary 128
Chapter 6: Dictionaries 129
A Simple Dictionary 130
Working with Dictionaries 130
Accessing Values in a Dictionary 131
Adding New Key-Value Pairs 131
Starting with an Empty Dictionary 132
Modifying Values in a Dictionary 133
Removing Key-Value Pairs 134
A Dictionary of Similar Objects 135
Using get() to Access Values 136
Looping Through a Dictionary 137
Looping Through All Key-Value Pairs 137
Looping Through All the Keys in a Dictionary 139
Looping Through a Dictionary’s Keys in a Particular Order 141
Looping Through All Values in a Dictionary 142
Nesting 144
A List of Dictionaries 144
A List in a Dictionary 146
A Dictionary in a Dictionary 148
Summary 150
Chapter 7: User Input and while Loops 151
How the input() Function Works 152
Writing Clear Prompts 152
Using int() to Accept Numerical Input 153
The Modulo Operator 154
Introducing while Loops 156
The while Loop in Action 156
Letting the User Choose When to Quit 156
Using a Flag 158
Using break to Exit a Loop 159
Using continue in a Loop 160
Avoiding Infinite Loops 160
Using a while Loop with Lists and Dictionaries 162
Moving Items from One List to Another 162
Removing All Instances of Specific Values from a List 163
Filling a Dictionary with User Input 164
Summary 165
Chapter 8: Functions 167
Defining a Function 168
Passing Information to a Function 168
Arguments and Parameters 169
Passing Arguments 169
Positional Arguments 170
Keyword Arguments 171
Default Values 172
Equivalent Function Calls 173
Avoiding Argument Errors 174
Return Values 175
Returning a Simple Value 176
Making an Argument Optional 176
Returning a Dictionary 178
Using a Function with a while Loop 179
Passing a List 181
Modifying a List in a Function 181
Preventing a Function from Modifying a List 183
Passing an Arbitrary Number of Arguments 185
Mixing Positional and Arbitrary Arguments 186
Using Arbitrary Keyword Arguments 186
Storing Your Functions in Modules 188
Importing an Entire Module 188
Importing Specific Functions 190
Using as to Give a Function an Alias 190
Using as to Give a Module an Alias 191
Importing All Functions in a Module 191
Styling Functions 192
Summary 193
Chapter 9: Classes 195
Creating and Using a Class 196
Creating the Dog Class 196
Making an Instance from a Class 198
Working with Classes and Instances 200
The Car Class 200
Setting a Default Value for an Attribute 201
Modifying Attribute Values 202
Inheritance 205
The __init__() Method for a Child Class 205
Defining Attributes and Methods for the Child Class 207
Overriding Methods from the Parent Class 208
Instances as Attributes 208
Modeling Real-World Objects 211
Importing Classes 212
Importing a Single Class 212
Storing Multiple Classes in a Module 213
Importing Multiple Classes from a Module 215
Importing an Entire Module 215
Importing All Classes from a Module 215
Importing a Module into a Module 216
Using Aliases 217
Finding Your Own Workflow 217
The Python Standard Library 218
Styling Classes 219
Summary 220
Chapter 10: Files and Exceptions 221
Reading from a File 222
Reading an Entire File 222
File Paths 223
Reading Line by Line 225
Making a List of Lines from a File 226
Working with a File’s Contents 226
Large Files: One Million Digits 227
Is Your Birthday Contained in Pi? 228
Writing to a File 229
Writing to an Empty File 229
Writing Multiple Lines 230
Appending to a File 231
Exceptions 232
Handling the ZeroDivisionError Exception 232
Using try-except Blocks 232
Using Exceptions to Prevent Crashes 233
The else Block 234
Handling the FileNotFoundError Exception 235
Analyzing Text 236
Working with Multiple Files 237
Failing Silently 238
Deciding Which Errors to Report 239
Storing Data 240
Using json.dump() and json.load() 241
Saving and Reading User-Generated Data 242
Refactoring 244
Summary 246
Chapter 11: Testing Your Code 247
Testing a Function 248
Unit Tests and Test Cases 249
A Passing Test 249
A Failing Test 250
Responding to a Failed Test 251
Adding New Tests 252
Testing a Class 254
A Variety of Assert Methods 254
A Class to Test 255
Testing the AnonymousSurvey Class 256
The setUp() Method 258
Summary 260
Part II: Projects 261
Project 1: Alien Invasion 263
Chapter 12: A Ship that Fires Bullets 265
Planning Your Project 266
Installing Pygame 266
Starting the Game Project 267
Creating a Pygame Window and Responding to User Input 267
Setting the Background Color 268
Creating a Settings Class 269
Adding the Ship Image 270
Creating the Ship Class 271
Drawing the Ship to the Screen 273
Refactoring: The _check_events() and _update_screen() Methods 274
The _check_events() Method 274
The _update_screen() Method 275
Piloting the Ship 276
Responding to a Keypress 276
Allowing Continuous Movement 277
Moving Both Left and Right 278
Adjusting the Ship’s Speed 279
Limiting the Ship’s Range 281
Refactoring _check_events() 281
Pressing Q to Quit 282
Running the Game in Fullscreen Mode 282
A Quick Recap 283
alien_invasion.py 283
settings.py 284
ship.py 284
Shooting Bullets 284
Adding the Bullet Settings 285
Creating the Bullet Class 285
Storing Bullets in a Group 286
Firing Bullets 287
Deleting Old Bullets 288
Limiting the Number of Bullets 289
Creating the _update_bullets() Method 290
Summary 291
Chapter 13: Aliens! 293
Reviewing the Project 294
Creating the First Alien 294
Creating the Alien Class 295
Creating an Instance of the Alien 296
Building the Alien Fleet 297
Determining How Many Aliens Fit in a Row 298
Creating a Row of Aliens 298
Refactoring _create_fleet() 300
Adding Rows 300
Making the Fleet Move 303
Moving the Aliens Right 303
Creating Settings for Fleet Direction 304
Checking Whether an Alien Has Hit the Edge 304
Dropping the Fleet and Changing Direction 305
Shooting Aliens 306
Detecting Bullet Collisions 306
Making Larger Bullets for Testing 308
Repopulating the Fleet 308
Speeding Up the Bullets 309
Refactoring _update_bullets() 309
Ending the Game 310
Detecting Alien and Ship Collisions 310
Responding to Alien and Ship Collisions 311
Aliens that Reach the Bottom of the Screen 314
Game Over! 314
Identifying When Parts of the Game Should Run 315
Summary 316
Chapter 14: Scoring 317
Adding the Play Button 318
Creating a Button Class 318
Drawing the Button to the Screen 319
Starting the Game 321
Resetting the Game 321
Deactivating the Play Button 322
Hiding the Mouse Cursor 322
Leveling Up 323
Modifying the Speed Settings 323
Resetting the Speed 325
Scoring 326
Displaying the Score 326
Making a Scoreboard 327
Updating the Score as Aliens Are Shot Down 329
Resetting the Score 329
Making Sure to Score All Hits 330
Increasing Point Values 330
Rounding the Score 331
High Scores 332
Displaying the Level 334
Displaying the Number of Ships 336
Summary 340
Project 2: Data Visualization 341
Chapter 15: Generating Data 343
Installing Matplotlib 344
Plotting a Simple Line Graph 344
Changing the Label Type and Line Thickness 345
Correcting the Plot 347
Using Built-in Styles 348
Plotting and Styling Individual Points with scatter() 348
Plotting a Series of Points with scatter() 350
Calculating Data Automatically 350
Defining Custom Colors 352
Using a Colormap 352
Saving Your Plots Automatically 353
Random Walks 353
Creating the RandomWalk() Class 354
Choosing Directions 354
Plotting the Random Walk 355
Generating Multiple Random Walks 356
Styling the Walk 357
Rolling Dice with Plotly 361
Installing Plotly 362
Creating the Die Class 362
Rolling the Die 363
Analyzing the Results 363
Making a Histogram 364
Rolling Two Dice 366
Rolling Dice of Different Sizes 367
Summary 369
Chapter 16: Downloading Data 371
The CSV File Format 372
Parsing the CSV File Headers 372
Printing the Headers and Their Positions 373
Extracting and Reading Data 374
Plotting Data in a Temperature Chart 374
The datetime Module 375
Plotting Dates 376
Plotting a Longer Timeframe 378
Plotting a Second Data Series 378
Shading an Area in the Chart 380
Error Checking 381
Downloading Your Own Data 383
Mapping Global Data Sets: JSON Format 385
Downloading Earthquake Data 385
Examining JSON Data 385
Making a List of All Earthquakes 388
Extracting Magnitudes 388
Extracting Location Data 389
Building a World Map 389
A Different Way of Specifying Chart Data 391
Customizing Marker Size 391
Customizing Marker Colors 392
Other Colorscales 394
Adding Hover Text 394
Summary 396
Chapter 17: Working with APIs 397
Using a Web API 397
Git and GitHub 398
Requesting Data Using an API Call 398
Installing Requests 399
Processing an API Response 399
Working with the Response Dictionary 400
Summarizing the Top Repositories 402
Monitoring API Rate Limits 403
Visualizing Repositories Using Plotly 404
Refining Plotly Charts 406
Adding Custom Tooltips 407
Adding Clickable Links to Our Graph 408
More About Plotly and the GitHub API 409
The Hacker News API 410
Summary 413
Project 3: Web Applications 415
Chapter 18: Getting Started with Django 417
Setting Up a Project 418
Writing a Spec 418
Creating a Virtual Environment 418
Activating the Virtual Environment 419
Installing Django 419
Creating a Project in Django 420
Creating the Database 420
Viewing the Project 421
Starting an App 422
Defining Models 423
Activating Models 424
The Django Admin Site 425
Defining the Entry Model 428
Migrating the Entry Model 429
Registering Entry with the Admin Site 429
The Django Shell 430
Making Pages: The Learning Log Home Page 432
Mapping a URL 433
Writing a View 434
Writing a Template 435
Building Additional Pages 436
Template Inheritance 436
The Topics Page 438
Individual Topic Pages 441
Summary 445
Chapter 19: User Accounts 447
Allowing Users to Enter Data 448
Adding New Topics 448
Adding New Entries 452
Editing Entries 456
Setting Up User Accounts 459
The users App 459
The Login Page 460
Logging Out 462
The Registration Page 464
Allowing Users to Own Their Data 466
Restricting Access with @login_required 467
Connecting Data to Certain Users 468
Restricting Topics Access to Appropriate Users 471
Protecting a User’s Topics 472
Protecting the edit_entry Page 472
Associating New Topics with the Current User 473
Summary 474
Chapter 20: Styling and Deploying an App 475
Styling Learning Log 476
The django-bootstrap4 App 476
Using Bootstrap to Style Learning Log 476
Modifying base.html 477
Styling the Home Page Using a Jumbotron 481
Styling the Login Page 482
Styling the Topics Page 483
Styling the Entries on the Topic Page 484
Deploying Learning Log 486
Making a Heroku Account 486
Installing the Heroku CLI 486
Installing Required Packages 486
Creating a requirements.txt File 486
Specifying the Python Runtime 487
Modifying settings.py for Heroku 488
Making a Procfile to Start Processes 488
Using Git to Track the Project’s Files 488
Pushing to Heroku 490
Setting Up the Database on Heroku 492
Refining the Heroku Deployment 492
Securing the Live Project 494
Committing and Pushing Changes 495
Setting Environment Variables on Heroku 496
Creating Custom Error Pages 496
Ongoing Development 499
The SECRET_KEY Setting 499
Deleting a Project on Heroku 499
Summary 501
Afterword 503
Appendix A: Installation and Troubleshooting 505
Python on Windows 505
Finding the Python Interpreter 505
Adding Python to Your Path Variable 506
Reinstalling Python 507
Python on macOS 507
Installing Homebrew 507
Installing Python 508
Python on Linux 508
Python Keywords and Built-in Functions 509
Python Keywords 509
Python Built-in Functions 509
Appendix B: Text Editors and IDEs 511
Customizing Sublime Text Settings 512
Converting Tabs to Spaces 512
Setting the Line Length Indicator 512
Indenting and Unindenting Code Blocks 512
Commenting Out Blocks of Code 513
Saving Your Configuration 513
Further Customizations 513
Other Text Editors and IDEs 513
IDLE 513
Geany 514
Emacs and Vim 514
Atom 514
Visual Studio Code 514
PyCharm 514
Jupyter Notebooks 515
Appendix C: Getting Help 517
First Steps 517
Try It Again 518
Take a Break 518
Refer to This Book’s Resources 518
Searching Online 519
Stack Overflow 519
The Official Python Documentation 519
Official Library Documentation 520
r/learnpython 520
Blog Posts 520
Internet Relay Chat 520
Making an IRC Account 520
Channels to Join 521
IRC Culture 521
Slack 521
Discord 522
Appendix D: Using Git for Version Control 523
Installing Git 524
Installing Git on Windows 524
Installing Git on macOS 524
Installing Git on Linux 524
Configuring Git 524
Making a Project 524
Ignoring Files 525
Initializing a Repository 525
Checking the Status 525
Adding Files to the Repository 526
Making a Commit 526
Checking the Log 527
The Second Commit 527
Reverting a Change 528
Checking Out Previous Commits 529
Deleting the Repository 531
Index 533
Blank Page 547
Alternative description
Second edition of the best selling Python book in the world. A fast-paced, no-nonsense guide to programming in Python. This book teaches beginners the basics of programming in Python with a focus on real projects. This is the second edition of the best selling Python book in the world. Python Crash Course, 2nd Edition is a straightforward introduction to the core of Python programming. Author Eric Matthes dispenses with the sort of tedious, unnecessary information that can get in the way of learning how to program, choosing instead to provide a foundation in general programming concepts, Python fundamentals, and problem solving. Three real world projects in the second part of the book allow readers to apply their knowledge in useful ways. Readers will learn how to create a simple video game, use data visualization techniques to make graphs and charts, and build and deploy an interactive web application. Python Crash Course, 2nd Edition teaches beginners the essentials of Python quickly so that they can build practical programs and develop powerful programming techniques
Alternative description
This is the second edition of the best selling Python book in the world. Python Crash Course, 2nd Edition is a straightforward introduction to the core of Python programming. Author Eric Matthes dispenses with the sort of tedious, unnecessary information that can get in the way of learning how to program, choosing instead to provide a foundation in general programming concepts, Python fundamentals, and problem solving. Three real world projects in the second part of the book allow readers to apply their knowledge in useful ways. Readers will learn how to create a simple video game, use data visualization techniques to make graphs and charts, and build and deploy an interactive web application. Python Crash Course, 2nd Edition teaches beginners the essentials of Python quickly so that they can build practical programs and develop powerful programming techniques. - Amazon.com
date open sourced
2021-11-11
🚀 Fast downloads
Become a member to support the long-term preservation of books, papers, and more. To show our gratitude for your support, you get fast downloads. ❤️
- Fast Partner Server #1 (recommended)
- Fast Partner Server #2 (recommended)
- Fast Partner Server #3 (recommended)
- Fast Partner Server #4 (recommended)
- Fast Partner Server #5 (recommended)
- Fast Partner Server #6 (recommended)
- Fast Partner Server #7
- Fast Partner Server #8
- Fast Partner Server #9
- Fast Partner Server #10
- Fast Partner Server #11
🐢 Slow downloads
From trusted partners. More information in the FAQ. (might require browser verification — unlimited downloads!)
- Slow Partner Server #1 (slightly faster but with waitlist)
- Slow Partner Server #2 (slightly faster but with waitlist)
- Slow Partner Server #3 (slightly faster but with waitlist)
- Slow Partner Server #4 (slightly faster but with waitlist)
- Slow Partner Server #5 (no waitlist, but can be very slow)
- Slow Partner Server #6 (no waitlist, but can be very slow)
- Slow Partner Server #7 (no waitlist, but can be very slow)
- Slow Partner Server #8 (no waitlist, but can be very slow)
- After downloading: Open in our viewer
All download options have the same file, and should be safe to use. That said, always be cautious when downloading files from the internet, especially from sites external to Anna’s Archive. For example, be sure to keep your devices updated.
External downloads
-
For large files, we recommend using a download manager to prevent interruptions.
Recommended download managers: Motrix -
You will need an ebook or PDF reader to open the file, depending on the file format.
Recommended ebook readers: Anna’s Archive online viewer, ReadEra, and Calibre -
Use online tools to convert between formats.
Recommended conversion tools: CloudConvert and PrintFriendly -
You can send both PDF and EPUB files to your Kindle or Kobo eReader.
Recommended tools: Amazon‘s “Send to Kindle” and djazz‘s “Send to Kobo/Kindle” -
Support authors and libraries
✍️ If you like this and can afford it, consider buying the original, or supporting the authors directly.
📚 If this is available at your local library, consider borrowing it for free there.
Total downloads:
A “file MD5” is a hash that gets computed from the file contents, and is reasonably unique based on that content. All shadow libraries that we have indexed on here primarily use MD5s to identify files.
A file might appear in multiple shadow libraries. For information about the various datasets that we have compiled, see the Datasets page.
For information about this particular file, check out its JSON file. Live/debug JSON version. Live/debug page.