Index

Symbols creating the fleet, 258–264 dropping the fleet, 267 + (addition), 26 reaching bottom of * (asterisk) operator, 147 screen, 276 {} (braces), 92, 105 rebuilding the fleet, 270 / (division), 26 bullets, 246–252 ** (double asterisk) operator, 149 collisions, with aliens, == (equality operator), 72–73 268–269, 291–292 ** (exponent), 26 deleting old, 250 // (floor division), 260 firing, 249 > (greater than), 75 limiting number of, 251 >= (greater than or equal to), 75 making larger, 270 # (hash mark), for comments, 29 settings, 247 != (inequality operator), 74 speeding up, 271 < (less than), 75 classes <= (less than or equal to), 75 Alien, 256–258 % (modulo operator), 116–117, 122 Bullet, 247–248 * (multiplication), 26 Button, 280–281 \n (newline), 22 GameStats, 273 ! (not), 74 Scoreboard, 288–289 += operator, 115 Settings, 231 [] (square brackets), 34 Ship, 233–235 - (subtraction), 26 ending the game, 276 \t (tab), 22 files alien_invasion.py, 229 A bullet.py, 247 addition (+), 26 button.py, 280 aliases, 152 game_stats.py, 273 alice.py, 197–199 scoreboard.py, 288 Alien Invasion project. See also settings.py, 231 Pygame ship.bmp, 233 aliens initializing dynamic checking edges, 266 settings, 286 collisions, with bullets, levels 268–269, 291–292 adding, 285–287 collisions, with ship, 272–275 modifying speed controlling fleet settings, 285 direction, 266 resetting the speed, 287 creating an alien, 256 planning, 228 Alien Invasion project, continued asterisk (*) operator, 147 Play button attributes, 159. See also classes: adding, 280–285 attributes deactivating, 284 drawing, 281 B hiding the mouse cursor, 284 banned_users.py, 77 resetting the game, 283 bicycles.py, 34–36 starting the game, 283 .bmp (bitmap) image files, 232 scoring, 288–300 body all hits, 292 of a function, 130 high score, 294 of an HTML file, 440 increasing point values, 292 Boolean values, 77, 456 level, 296–298 Bootstrap, 438–447 number of ships, 298–300 braces ({}), 92, 105 resetting, 291 built-in functions, 471 rounding and formatting, 293–294 C score attribute, 288 CamelCase, 181 updating, 291 car.py, 162–179 settings, storing, 231 cars.py, 43–45, 72 ship cities.py, 121 adjusting speed, 241–243 classes continuous movement, attributes, 159 239–241 accessing, 160 finding an image, 232 default values, 163 limiting range, 243 modifying, 164–166 amusement_park.py, 80–83 creating, 158–162 and keyword, 75 importing, 174 –179 API (application programming all classes from a interface), 359 module, 177 calls, 359 multiple classes, 175–177 for GitHub, 371 single class, 174 –175 for Hacker News, 372–375 inheritance, 167–173 processing responses, 361–365 attributes and methods, 169 rate limits, 365 child classes, 167 requesting data, 360 __init__() method, 167–169 visualizing results, 366–371 instances as attributes, apostrophe.py, 24 170 –172 append() method, 37 overriding methods, 170 application programming interface. parent classes, 167 See API (application subclasses, 168 programming interface) super() function, 168 arguments, 131–137. See also superclasses, 168 functions: arguments instances, 157 arithmetic, 26 methods, 159 as keyword, 152 calling, 160 assert methods, 212, 216 __init__() method, 159

496 Index modeling real-world objects, 173 key-value pairs, 99 multiple instances, 161 values, 104 naming conventions, 159 ordering in, 94 objects, 157 sorting a list of, 374 styling guidelines, 181 values comma-separated value files. See accessing, 93 CSV (comma-separated modifying, 95 value) files die.py, 324 comment.py, 29 die_visual.py, 325–327 comments, 29–30 dimensions.py, 66–67 conditional tests, 72–77. See also Discord, 48 if statements div (HTML), 441 confirmed_users.py, 124 division (/), 26 constants, 28 division_calculator.py, 194–197 counting.py, 118, 122 Django, 379. See also Heroku; CSV (comma-separated value) files, Learning Log project 334–346 admin site, 387–392 error-checking, 343–345 registering models, 388, 391 parsing headers, 334–335 associating data with users, 435 reading data, 336 Bootstrap, 438–447 card, 446 D collapsible navigation, 440 container element, 443 data analysis, 305 django-bootstrap4 app, 438 databases. See Django: databases HTML headers, 439–440 data visualization, 305. See also jumbotron, 443 Matplotlib; Plotly navigation bar, 440–442 datetime module, 337–339 styling forms, 444–445 death_valley_highs_lows.py, 343–345 commands decorators, 429 createsuperuser, 388 default values, 134 flush, 433 class attributes, 163 makemigrations, 387, 391, 432 function parameters, 134 migrate, 383 def keyword, 130 shell, 392 del statement, 39 startapp, 385, 421 dice_visual.py, 328–330 startproject, 382 dictionaries creating a project, 381 defining, 92 databases empty, 94 cascading delete, 390 formatting larger, 97 creating, 382 get() method, 98 foreign keys, 390 KeyError, 98 many-to-one key-value pairs, 92–99 relationships, 390 adding, 93 migrating, 383, 391 removing, 96 queries, 404, 433 looping through, 99–105 querysets, 392–393, 401 keys, 101 required (non-nullable) keys in order, 103 fields, 432

Index 497 Django, continued registration page, 426–428 databases, continued release cycle, 381 resetting, 433 restricting access to data, SQLite, 383 433–435 decorators, 429 restricting access to , deployment. See Heroku 428–435 development server, 383, 389 settings.py documentation INSTALLED APPS, 386, 421, 438 Django, 379 LOGIN_URL, 429 models, 386 SECRET_KEY, 461 queries, 394 shell, 392, 431 templates, 406 starting an app, 385 forms, 410–420 starting a new project, 382 action argument, 413 static files, 448 cross-site request styling. See Django: Bootstrap forgery, 413 superuser, 387 displaying, 413 templates, 397 GET and POST requests, 412 anchor tags, 399 ModelForm, 410, 414 block tags, 399 pre-filling with data, 419 context dictionary, 401 processing, 412, 416 filters, 405 validation, 410 for loop, 402 widgets, 414 indentation in, 399 get_object_or_404() method, 460 inheritance, 398 hashes (for passwords), 388 linebreaks filter, 405 HTML template tags, 399 div element, 441 third-party apps, 438 main element, 442 URLs margin, 443 capturing values, 404 padding, 443 namespaces, 399 span element, 442 URL patterns, 395–396 HTTP 404 error, 434 url template tag, 399 INSTALLED_APPS, 386, 421, 438 user ID values, 431 installing, 381 users localhost, 383 default login view, 422 logging out, 424 displaying message to login page, 422 logged-in user, 424 @login_required, 429 logging in a user, 427 login template, 422 UserCreationForm, 427 mapping URLs, 395–396 versions, 381 migrating the database, views, 396 383, 391 retrieving objects, 401, 404 models, 385–393, 431 docstrings, 130 privileges, 387 dog.py, 158–162 projects (vs. apps), 384 dot notation, 151, 160 redirect() function, 411 double asterisk (**) operator, 149

498 Index E writing to by appending, 193 earthquakes. See mapping empty files, 191 earthquakes multiple lines, 192 electric_car.py, 168 –173 first_numbers.py, 57 electric_car.py module, 178 flags, 120 enumerate() function, 335 floats, 26 environment variables, 456 foods.py, 63–65 epoch time, 366 for loops, 49. See also dictionaries; eq_explore_data.py, 348–351 lists equality operator (==), 72–73 formatted_name.py, 138–140 eq_world_map.py, 351–357 full_name.py, 21–22 even_numbers.py, 58 functions, 129 even_or_odd.py, 117 alias (as), 152 exceptions, 183, 194–202 arguments, 131–137 deciding which errors to arbitrary keyword, 148 report, 201 arbitrary number of, 147 else blocks, 196 avoiding errors, 136 failing silently, 200 keyword, 133 FileNotFoundError, 197 lists as, 143 –146 handling, 194 mixing positional and try-except blocks, 194 arbitrary, 148 using to prevent crashes, 195 optional, 138 ZeroDivisionError, 194 order of, 133 exponents (**), 26 positional, 132–133 built-in, 471 F calling, 130–137 favorite_languages.py, 97–98 equivalent calls, 135–136 FileNotFoundError, 197 multiple times, 132 file_reader.py, 184–188 defining, 130 files dictionaries, returning, 140 closing, 185 lists in file paths, 185 modifying, 143 –145 absolute, 186 protecting, 145 relative, 186 modules, 150–155 opening, 184 alias (as), 153 append mode, 192 importing all read mode, 192 functions (*), 153 write mode, 192 importing entire reading from, 184–190 modules, 150 entire files, 184–185 importing specific line by line, 187 functions, 152 making a list of lines, 188 parameters, default working with contents, 188 values for, 134 working with large passing information to. See files, 189 functions: arguments return values, 137–142 styling, 154

Index 499 G H games. See Alien Invasion project; Hacker News, 372 Pygame hash mark (#), for comments, 29 , 476 head, of an HTML file, 440 GET requests, 412 HEAD (Git), 492 getting help Hello World, 9 Discord, 484 hello_git.py, 486–491 IRC (Internet Relay Chat), hello_world.py, 10, 15–19 482–483 Heroku, 437. See also Django; Git; official Python documentation, Learning Log project 481 Bash shell, 454 online resources, 480 CLI, installing, 448 r/learnpython, 482 commands rubber duck debugging, 480 config, 458 Slack, 483 destroy, 462 Stack Overflow, 481 login, 453 three main questions, 479 open, 453 Git, 360, 450 ps, 453 branches, 452, 488 rename, 455 commits, 360, 450 run, 454 checking out, 491–493 set, 458 making, 452, 457, 460, 488, databases, setting up, 454 490, 493 django-heroku package, 448 configuring, 451, 486 documentation, 453 detached HEAD, 492 environment variables, setting, files 456–458 adding, 452, 460, 488, 493 error pages, custom, 458–460 ignoring, 451, 487 free plan, limitations of, HEAD, 492 448, 456 installing, 450, 486 making an account, 448 log, checking, 489 Procfile, 450 repositories, 360 projects deleting, 493 deleting, 461 initializing, 452, 487, 493 pushing to Heroku, reverting changes, 490 452–453, 457 status, checking, 452, 457, viewing live, 453 487–493 Python runtime, specifying, 449 GitHub, 360 requirements.txt, 448–449 greater than (>), 75 securing, 456 greater than or equal to (>=), 75 settings.py, modifying for, 450, greeter.py, 114, 130–131 456, 459 greet_users.py, 143 superuser, creating, 454–455 gunicorn package, 448 URLs, user-friendly, 455 hidden files, 451

500 Index hn_article.py, 372 J hn_submissions.py, 373 JSON files Homebrew, 469 examining data, 347 geoJSON file format, 349 I json.dump() function, 348 IDE (integrated development json.load() function, 204 environment), 473 jumbotron, 443 IDLE, 475 if statements K and keyword, 75 keys() method, 101 Boolean expressions, 77 key-value pairs, 92–99. See also checking for dictionaries equality (==), 72 keyword arguments, 132, 133. See equality, ignoring case, 73 also functions empty lists, 87 keywords, 471 inequality (!=), 74 items in a list, 76 items not in a list, 77 L conditional tests, 72–77 language_survey.py, 217 elif statement, 80–84 Learning Log project, 379. See also else statement, 79 Django; Heroku lists and, 85–88 deployment. See Git, Heroku numerical comparisons, 74–76 files or keyword, 76 404.html, 458 simple, 78 500.html, 459 styling guidelines, 90 admin.py, 388 testing multiple conditions, base.html, 399, 403, 423, 425, 83–84 428, 439–443 immutable, 65 edit_entry.html, 419 import *, 153 forms.py, 410, 414 import this, 30 .gitignore, 451 indentation errors, 53–56 index.html, 397, 443 index errors, 47 learning_logs/urls.py, 395, inequality operator (!=), 74 401, 404, 411, 415, 418 infinite loops, 122 learning_log/urls.py, 395, 422 inheritance, 167. See also classes: logged_out.html, 425 inheritance login.html, 422–423, 444 input() function, 114–117 models.py, 385, 390, 431 numerical input, 115–116 new_entry.html, 416 prompts, 114 new_topic.html, 412 insert() method, 38 Procfile, 450 IRC (Internet Relay Chat), 482–483 register.html, 427 itemgetter() function, 374 requirements.txt, 448 items() method, 100 runtime.txt, 449 settings.py, 386, 421, 429, 450, 456, 459

Index 501 Learning Log project, continued removing with del, 39 files, continued removing with pop(), 39–41 topic.html, 404–405, 417, 420 removing with remove(), 41 topics.html, 402, 405, 413, 445 empty, 38 users/urls.py, 422, 426 enumerate() function, 335 users/views.py, 426 for loops, 49–56 views.py, 396, 401, 404, nested, 109, 263 411, 415, 418, 429, 430, if statements and, 85–88 433, 460 indentation errors, 53–56 pages indexes, 35 edit entry, 418–420 errors, 46–47 home, 394–398 negative, 35 login, 422–424 len() function, 45 logout, 424 list comprehensions, 59 new entry, 414–417 naming, 34 new topic, 410–413 numerical lists, 57–60 register, 426 range() function, 58–59 topic, 403 removing all occurrences of a topics, 400–403 value, 125 users app, 421–428 slices, 61–63 virtual environment, 380–381 sorting, 43–46 writing a specification reverse() method, 45 (spec), 380 sorted() function, 44 len() function, 45 sort() method, 43 less than (<), 75 logical errors, 54 less than or equal to (<=), 75 Linux M Hello World, running, 10 Python macOS checking installed version, 8 Hello World, running, 10 installing, 470 Python troubleshooting checking installed version, 7 installation, 11 installing, with Homebrew, Sublime Text, installing, 9 469–470 terminal installing, official running programs from, 12 version, 7–8 starting Python session, 9 troubleshooting lists, 33 installation, 11 as arguments, 143–146 Sublime Text, installing, 8 copying, 63–65 terminal elements running programs from, 12 accessing, 34 starting a Python session, 8 accessing last, 35 magicians.py, 50–53 adding with append(), 37 magic_number.py, 75 adding with insert(), 38 making_pizzas.py, 151–153 identifying unique, 104 mapping earthquakes, 347–357 modifying, 36 building a world map, 351 colorscales, 354

502 Index data N downloading, 347, 358 name errors, 17 examining JSON data, 347 name_function.py, 210–215 extracting locations, 351 name.py, 20 extracting magnitudes, 350 names.py, 210 geoJSON file format, 349 nesting, 106–112 hover text, 356 depth, 110 latitude-longitude ordering, 349 dictionaries in dictionaries, magnitudes, representing, 353 110–111 Scattergeo chart type, 352 dictionaries in lists, 106–108 Matplotlib, 306–323, 336–347 lists in dictionaries, 108–110 axes newline (\n), 22 axis() method, 313 None, 99 ax variable, 307 not (!), 74 removing, 321 number_reader.py, 203 fig variable, 307 numbers, 25–28 formatting plots arithmetic, 26 alpha argument, 342 comparisons, 74–76 built-in styles, 310 exponents, 26 colormaps, 314 floats, 26 custom colors, 314 floor division (//), 260 labels, 307–308 integers, 26 line thickness, 307 mixing integers and floats, 27 shading, 342 order of operations, 26 size, 322 round() function, 294 gallery, 306 underscores in, 28 installing, 306 number_writer.py, 203 line graphs, 306 plot() method, 307, 309 pyplot module, 307 O saving plots, 315 object-oriented programming, 157. scatter plots, 310–313 See also classes subplots() function, 307 open() function, 184 methods, 20, 236–237. See also or keyword, 76 classes modules, 150. See also classes: P modules; functions: modules parameters, 131 modulo operator (%), 116–117, 122 parent classes, 167. See also classes: motorcycles.py, 37–42 inheritance mountain_poll.py, 126 parrot.py, 114, 118–121 mpl_squares.py, 306–310 pass statement, 200 multiplication (*), 26 PEP 8, 68–70, 90, 154 my_car.py, 175 person.py, 140–142 my_cars.py, 177–179 pets.py, 125, 132–136 my_electric_car.py, 176

Index 503 pip, 228 fullscreen mode, 244 installing Django, 381 groups, 248 installing Matplotlib, 306 drawing all elements in, 259 installing Plotly, 324 emptying, 271 installing Pygame, 228 looping through, 250 installing Requests, 361 removing elements from, 251 pi_string.py, 188–190 storing elements in, 248 pizza.py, 147–148 updating all elements in, 249 players.py, 61–63 images, drawing to screen, 235 Plotly, 306 images, loading, 234 Bar() class, 327 installing, 228 data, long format, 353 print() calls in, 251 formatting plots quitting, 244 bars, 368 rect objects colorscales, 354 creating from scratch, 247 hover text, 356, 369–370 positioning, 234, 247–248, marker color, 368 257–258, 260–261, marker size, 353 263–264 Layout() class, 327 responding to input, 230 layout, long format, 367 keypresses, 238 x-axis, 368 mouse clicks, 283 y-axis, 368 screen coordinates, 234 gallery, 324 surfaces, 230 histogram, 326 testing games, 270 installing, 324 pyplot module, 307 offline.plot() function, 327 Python Python figure reference, 371 >>> prompt, 4 Scattergeo chart type, 352 built-in functions, 471 user guide, 371 documentation, 481 positional arguments. See functions: installing arguments on , 470 POST requests, 412 on macOS, official, 7–8 printing_models.py, 143 –146 on macOS, using Homebrew, Project Gutenberg, 198 469–470 .py file extension, 16 on Windows, 5–6, 467–469 Pygame. See also Alien Invasion interpreter, 16 project keywords, 471 background colors, 230–231 PEP 8, 68–70, 90, 154 collisions, 268–269, 272–275, standard library, 180–181 291–292 terminal sessions, 4 colors, 231 versions, 4 creating empty windows, 229 Zen of, 30–31 cursor, hiding, 285 Python Enhancement Proposal displaying text, 280 (PEP), 68 ending games, 276 python_repos.py, 361–365 event loops, 230 python_repos_visual.py, 366–371

504 Index Q f-strings, 21 newlines in, 22 quit values, 118–120 single and double quotes, 19, 24 tabs in, 22 R using variables in, 21 random_walk.py, 316–317 whitespace in, 22–24 random walks, 315–323 strptime() method, 338 choice() function, 317 style guidelines, 68–70 coloring points, 319 blank lines, 69 fill_walk() method, 316 CamelCase, 181 multiple walks, generating, 318 classes, 181 plotting, 317 functions, 154 RandomWalk class, 316 if statements, 90 starting and ending points, 320 indentation, 69 range() function, 57–59 line length, 69 readlines() method, 188 PEP 8, 68 read() method, 185 Sublime Text, 4–10, 474–475 refactoring, 206–208, 236 commenting out code, 475 remember_me.py, 204–208 configuring, 9 Requests package, 361 customizing, 474 return values, 137 indenting and unindenting r/learnpython, 482 code blocks, 474 rollercoaster.py, 116 installing, 7–9 rolling dice, 323–330 line length indicator, 474 analyzing results, 325 running Python programs, 9–10 Die class, 324 saving your configuration, 475 different sizes, 329 tabs and spaces, 474 randint() function, 324 subtraction (-), 26 two dice, 328 superclasses, 168. See also classes: rubber duck debugging, 480 inheritance rw_visual.py, 317–323 survey.py, 217 syntax errors, 24 S syntax highlighting, 16 scatter_squares.py, 311–315 sets, 104 T sitka_highs_lows.py, 340–342 tab (\t), 22 sitka_highs.py, 334–340 testing code, 209–222 Slack, 483 adding tests, 214 sleep() function, 274 assert methods, 216 slice, 61 coverage, 211 split() method, 198 failing tests, 212–214 square brackets ([]), 34 passing tests, 211–212 squares.py, 58, 60 setUp() method, 220 Stack Overflow, 481 test case, 211 storing data, 202–205. See also JSON testing classes, 216–221 strings, 19–25 testing functions, 210–215 changing case, 20 unittest module, 209 format() method, 22 unit tests, 211

Index 505 test_name_function.py, 211–215 W test_survey.py, 218–221 weather data, 334–347 text editors and IDEs web framework, 379 Atom, 476 while loops, 118–127 Emacs and Vim, 476 active flag, 120–121 Geany, 476 break statement, 121 IDLE, 475 infinite, 122 Jupyter Notebooks, 477 moving items between lists, 124 PyCharm, 476 quit values, 118–120 Sublime Text, 4–10, 474–475 whitespace, 22–24 Visual Studio Code, 476 Windows toppings.py, 74, 83–88 Hello World, running, 10 traceback, 18 Python try-except blocks, 194–202. See also checking installed version, 5 exceptions installing, 5–6, 467–469 tuples, 65­–67 troubleshooting installation, type errors, 66 11, 467–469 Sublime Text, installing, 7 U terminal unittest module, 209 running programs from, 12 unit tests, 211 starting a Python session, 6 Unix time, 366 with statement, 185 user_profile.py, 148 word_count.py, 199–201 write_message.py, 191–193 write() method, 192 V values() method, 104 Z variables, 16–19, 28 constants, 28 Zen of Python, 30–31 as labels, 18 ZeroDivisionError, 194 multiple assignment, 28 naming conventions, 17 values, 16 version control system, 485. See also Git virtual environment (venv), 380 voting.py, 79–80

506 Index