The words you are searching are inside this book. To get more targeted content, please make full-text search by clicking here.
Discover the best professional documents and content resources in AnyFlip Document Base.
Search
Published by thanatthuchkamseng, 2020-05-20 13:34:13

python-crash-course

python-crash-course

Django, continued regular expressions,
data 414, 422
associating with a user, 453
connecting to users, 448 user ID values, 449
restricting access to, views, 412
446 – 453 web server gateway
databases
creating, 401 interface, 401
foreign keys, 408 django-boostrap3 app, 456
many-to-one docstrings, 134
relationships, 408 dog.py, 162–166
migrating, 401, 409, 450–451 dot notation, 155, 164
queries, 423
querysets, 410 E
forms, 428–438
cross-site request Einstein, Albert, 29
forgery, 431 electric_car.py, 172–178
displaying, 431 electric_car.py module, 183
GET and POST elif statement, 84–88
requests, 430 else statement, 83-84
ModelForm, 428, 432 Emacs, 497
processing, 430, 434 epoch time, 384
validation, 428 equality operator (==), 77
widgets, 432 even_numbers.py, 62
hashes (for passwords), 406 even_or_odd.py, 121
HTTP 404 error, 452 event loops, 241–242
INSTALLED_APPS, modifying, 405 exceptions, handling, 200
jQuery, 457
localhost, 402 deciding which errors to
@login_required, 447 report, 207
login view, 440
manage.py, 400 else blocks, 202–203
models, 403–405 failing silently, 206–207
privileges, 406 FileNotFoundError, 203–204
runserver command, 401 to prevent crashes, 201–202
static files, 467 try-except blocks, 200–201
superuser, setting up, 406 ZeroDivisionError, 200
templates
anchor tags, 417 F
block tags, 417
context, 420 favorite_languages.py, 100–102,
filters, 423 104–108, 112
linebreaks filter, 423
template tags, 417 FileNotFoundError, 203–204
third party apps, 456 file_reader.py, 190–194
URLs files
namespaces, 417
patterns, 414 closing, 191
large, 195–196
opening, 190
paths, 191–192
reading

entire files, 190–191
line by line, 193
by making a list of lines, 194

518   Index

read/write modes, 198 installing
working with contents, 194 on Linux, 492
writing to on Windows, 492–493

by appending, 199 running Python programs, 493
empty files, 197 get-pip.py, 238. See also pip
multiple lines, 198 GET requests, 430
flags, 124 Git, 378, 505–506
floats, 30–31
foods.py, 67–69 branches, 508
for loops, 53–60 commits, 378, 508
functions, 133
arguments, 135–141 checking out previous, 512
arbitrary, 151–152 making, 509
avoiding errors with, detached HEAD, 512
files
140–141 adding, 508
keyword, 137–138 ignoring, 472, 507
lists as, 147–150 HEAD, 512
optional, 142–144 installing, 506
order of, 137 log, checking, 509
positional arguments, projects
checking status of, 508
136–137, 152 making, 507
built-in, 490 repositories
calling, 133, 134, 139–140 deleting, 513
initializing, 507
multiple times, 136–137 reverting changes, 511–512
defining, 134 GitHub, 378. See also Git
dictionaries, returning, 144–145 greater than (>), 79
import statements, 154 greater than or equal to (>=), 79
lists in greeter.py, 118–119, 134–135
greet_users.py, 147
modifying, 147–149 gunicorn, 469, 470–471
preventing modifying,
H
149–150
modules, storing in, 154–157. See Hacker News, 390
hash mark (#), for comments, 33
also modules head, of an HTML file, 458
parameters, default values HEAD (Git), 512
Hello World, 4
for, 138 hello_world.py, 19–23
passing information to, 134 Heroku. See also Django; Learning
return values, 141–146
styling, 158 Log project
Bash, 475
G databases

games. See Alien Invasion project; migrating, 474
Pygame setting up, 474
using Postgres, 469
Geany, 492–494
commenting out blocks, 494
customizing settings, 493
indenting and unindenting
blocks, 494

Index   519

Heroku, continued indentation errors, 57–60
making an account, 466 index errors, 51
Procfile, 469 inequality operator (!=), 78
projects infinite loops, 126–127
deleting, 481 inheritance, 172. See also classes:
pushing to, 473
securing, 476 inheritance
Python runtime, specifying, 468 input() function
settings.py, modifying for, 468
superuser, creating, 475 numerical input, 119–120
Toolbelt, installing, 466 prompts, 118–119
user-friendly URLs, 476 insert() method, 42
wsgi.py, modifying for, 470 int, 31
IRC (Internet relay chat), 502–503
hex format, for colors, 373 itemgetter() function, 391–392
highs_lows.py, 350–361 items() method, 103
hn_submissions.py, 391–393
Homebrew, 487 J

I jQuery, 457
json.dump() function, 209
IDLE, 496–497 JSON files
commenting out code, 497
customizing settings, 497 converting strings to numerical
installing values, 364
on Linux, 496
on OS X, 496 extracting data, 363
on Windows, 497 json.load() function, 210
jumbotron, 461
if statements
and keyword, 79–80 K
Boolean expressions, 81
checking for keys() method, 104
empty lists, 91 key-value pairs, 96. See also
equality (==), 76–78
inequality (!=), 78 dictionaries
items in a list, 80–81 keyword arguments, 136, 137–138
items not in a list, 81 keywords, 489
special items, 90–91
elif statement, 84–88 L
else statement, 83–84
if-elif-else chains, 84–93 language_survey.py, 224
lists and, 89–92 Learning Log project, 397. See also
numerical comparisons, 78–80
or keyword, 80 Django; Heroku
simple, 82–83 deployment
styling guidelines, 94
testing multiple conditions, commits, using Git, 471–473
87–88 custom error pages, 478–480

import *, 157 get_object_or_404()
import this, 34
method, 480
ignoring files in Git, 472
making a static file

directory, 470
ongoing development, 480
Procfile, 469

520   Index

requirements.txt, 467 if statements, 89–92
SECRET_KEY setting, 481 indentation errors, 57–60
using gunicorn locally, 470 indexes, 39
HTML headers, defining, 458
logging out, 442–443 errors, 50–51
login page, 440–442 negative, 39
migrating the database, insert() method, 42
len() function, 49
450–451 list comprehensions, 63–64
styling, 456 max() function, 63
min() function, 63
Bootstrap, 457 naming, 38
collapsible navigation, 459 numerical, 61–64
jumbotron, 461 pop() method, 43–45
navigation bar, 458–460 range() function, 62–63
selectors, 459 remove() method, 45
registration page, 443–446 removing all occurrences of a
users app
default login view, 440 value, 129
displaying messages to reverse() method, 49
slices, 65–67
logged-in users, 441 sorted() function, 48
logging in a user, 445 sort() method, 47
UserCreationForm, 445 sum() function, 63
len() function, 49 localhost, 402
less than (<), 79 logical errors, 58
less than or equal to (<=), 79 lower() method, 24
Linux lstrip() method, 27
Geany (text editor), 6, 492–494
Python M
checking installed version,
magicians.py, 54–57
5, 486 magic_number.py, 79
installing, 485–486 making_pizzas.py, 155–157
setting up, 5–8 matplotlib
running Hello World, 6–7
terminal formatting plots
running commands from, 8 axes, 337
running programs from, 16 color, 329–330
troubleshooting installation labels, 324–325
line thickness, 324–325
issues, 15 shading, 358
lists, 37–38 size, 338

append() method, 41 installing, 322–323
as arguments, 147–150 plot() function, 324
copying, 67–69 plotting
del, 43
elements dates, 355
multiple data series, 357
accessing, 38–39 pyplot module, 324
adding, 41–42 saving plots, 331
modifying, 40 scatter plots, 326–329
empty, 42 simple line graphs, 324
for loops, 53–60
Index   521

methods, 24, 165, 174–175. See also O
classes
object-oriented programming, 161.
ModelForm, 428, 432 See also classes
modules, 154–157
open() function, 190
aliases for, 157 operator module, 391–392
functions or keyword, 80
OS X
aliases for, 156
importing all, 157 Python
importing specific, 156 checking installed version,
importing an entire 8, 486–487
installing, 486–488
module, 154 setting up, 8–10
modulo operator (%), 120–121
motorcycles.py, 41–46 running Hello World, 10
mountain_poll.py, 130 Sublime Text (text editor), 9,
mpl_squares.py, 324–326
multiplication (*), 30 494–496
my_car.py, 180 terminal
my_cars.py, 181–184
my_electric_car.py, 181 running commands from, 9
running programs from, 16
N troubleshooting installation

name errors, 21–23 issues, 15
name_function.py, 216–221
name.py, 24–25 P
names.py, 216
na_populations.py, 368 parameters, 135, 138–139
nesting parent classes, 172. See also classes:

dictionaries in dictionaries, inheritance
113–114 parrot.py, 118, 122–125
pass statement, 206
dictionaries in lists, 109–111 PEP 8, 72–73
lists in dictionaries, 111–113 person.py, 144–146
newline (\n), 26 Peters, Tim, 34
not (!), 78 pets.py, 129, 136–140
number_reader.py, 209 pi, 190–196
numbers pip, 236
arithmetic, 30
avoiding type errors, 31–32 checking for, 237
comparisons, 78–80 get-pip.py, 238
exponents, 30 installing, 238
floats, 30–31 pi_string.py, 194–196
integers, 30–32 pizza.py, 111, 151–152
order of operations, 30 planning a project, 236
str() function, 32 players.py, 65–67
numbers.py, 61 pop() method, 43–45
number_writer.py, 209 positional arguments, 135,

136–137, 152
Postgres, 469
POST requests, 430

522   Index

printing_models.py, 147–150 installing
print statements, 24 on Linux, 485–486
on OS X, 487
long, 102 on Windows, 488–489
in Python 2, 29
privileges, 406 interpreter, 20
Procfile, 469 keywords, 489
Project Gutenberg, 208 PEP 8, 72–73
prompts, for user input, 118–119 standard library, 184–185
.py file extension, 20 terminal session, 4
Pygal, 322 --version, 486
charts Zen of, 34–36
Python 2.7
histograms, 342–343 creating classes in, 164
links, adding, 390 division of integers in, 32
styling, 386–388 print statements in, 29
tooltips, adding, 387 raw_input() function, 121
color themes, 374 Python Enhancement Proposal
installing, 340
plotting dictionaries, 388 (PEP), 72
rolling dice, 339 python_repos.py, 379–390
WorldMap, 367–374
grouping countries, 371–372 Q
plotting numerical data,
queries
368–372 in databases, 423
styling, 372–374 on GitHub (q=), 378–379
Pygame. See also Alien Invasion
querysets, in databases, 410
project quit values, 122–124
bitmap (.bmp) image files, 244
colors, 242–243 R
creating an empty window, 241
displaying text, 293 random_walk.py, 332
drawing images to the random walks, 331–332

screen, 246 coloring points, 335–336
groups fill_walk() method, 332
multiple walks, generating,
emptying, 282
storing elements in, 259 334–335
updating all elements in, 260 plotting, 333–334
installing, 236–240 RandomWalk class, 332
positioning images with starting and ending points,

rect, 245 plotting, 336
responding to input, 241–242 range() function 61–63
readlines() method, 194
keypresses, 249–250 read() method, 191
mouse clicks, 295–296 rect, positioning images with, 245
screen coordinates, 246 reddit, 502
surfaces, 241 refactoring, 212–214
pyplot module, 324 remember_me.py, 210–214
Python requests package, 379
built-in functions, 490
documentation, 501

Index   523

resources style guidelines, 72
debugging tips, 499–500 blank lines, 73
documentation, 501–502 CamelCaps, 186
IRC (Internet relay chat), classes, 186
502–503 functions, 158
channels, 503 if statements, 94
culture, 503 indentation, 72
making an account, 502 line length, 73
reddit, 502 PEP 8, 72
Stack Overflow, 501
subclasses, 173. See also classes:
return values, 141 inheritance
rollercoaster.py, 120
rolling dice Sublime Text, 494
commenting out code, 496
analyzing results, 341 configuring, 495
different sizes, 345 indenting and unindenting
two dice, 343 code blocks, 496
rubber duck debugging, 500 installing
rw_visual.py, 333–338 on Linux, 494
on OS X, 494
S on Windows, 495
running Python programs, 495
scatter_squares.py, 327–330
SECRET_KEY setting, 481 subtraction (-), 30
setUp() method, 227 superclasses, 173. See also classes:
Sitka, Alaska, weather data,
inheritance
350–362 superuser
slice, 65
sorted() function, 48 in Django, 406
sort() method, 47 in Heroku, 475
split() method, 204 survey.py, 223
SQLite, 401 syntax errors, 28
square brackets ([]), 38 syntax highlighting, 20
squares.py, 62, 64
Stack Overflow, 501 T
storing data
tab (\t), 26
json.dump() method, 209 testing code
json.load() method, 209
saving and reading data, adding tests, 221
assert methods, 218, 222-223
210–211 failing tests, 218–220
str() function, 32 full coverage, 217
strings functions, 216–221
passing tests, 217–218
changing case, 24 test case, 217
concatenating, 25 testing classes, 222–228
newlines in, 26
single and double quotes, 23 examples, 223-226
tabs in, 26 setUp() method, 227
whitespace in, 26–27 unittest module, 215, 217
strip() method, 27 unit tests, 217
test_name_function.py, 217–221

524   Index

test_survey.py, 225–228 W
text editors, 491–497
title() method, 24 weather data, 350–362
Toolbelt, Heroku, 466 web framework, 397
toppings.py, 78, 87–92 while loops
traceback, 22
tracking project files, 378, 471–473. active flag, 124–125
break statement, 125
See also Git infinite, 126–127
try-except blocks, 200–201. See also moving items between lists, 128
quit values, 122–124
exceptions, handling whitespace
tuples adding, 26
stripping, 26–27
defining, 69 Windows
for loop, 70 Geany (text editor), 12–14,
writing over, 71
type errors, 31–32, 70 492–494
Python
U
installing, 11, 488–489
unittest module, 215, 217 setting up, 10–14
unit tests, 217 running Hello World, 14
Unix time, 384 terminal
upper() method, 24 running commands from,
user_profile.py, 152
user.py, 103–104 11–12
users.py, 113 running programs from,

V 16 –17
troubleshooting installation
values
key-value pairs, 96. See also issues, 15
dictionaries with keyword, 190
of variables, 20 word_count.py, 205–207
world_population.py, 363–374
values() method, 107 write_message.py, 197–199
variables write() method, 198

defining, 20 Z
name errors, 21–23
naming conventions, 21 Zen of Python, 34–36
version control system, 378. ZeroDivisionError, 200

See also Git
vim, 497
virtual environment

deactivating, 399
installing virtualenv, 399
voting.py, 83–84

Index   525



Python Crash Course is set in New Baskerville, Futura, Dogma, and­
TheSansMono Condensed.

RESOURCES

Visit https://www.nostarch.com/pythoncrashcourse/ for resources, errata, and more
information.

More no-nonsense books from No Starch Press

Python Playground Automate the Boring Stuff Doing Math with Python
with Python
Geeky Weekend Projects for Use Programming to Explore Algebra,
the Curious Programmer Practical Programming for Statistics, Calculus, and More!
Total Beginners
by mahesh venkitachalam by amit saha
october 2015, 352 pp., $29.95 by al sweigart august 2015, 264 pp., $29.95
isbn 978-1-59327-604-1 april 2015, 504 pp., $29.95 isbn 978-1-59327-640-9
isbn 978-1-59327-599-0

The Linux Command Line Eloquent JavaScript, Black Hat Python
2nd Edition
A Complete Introduction Python Programming for Hackers
A Modern Introduction to Programming and Pentesters
by william e. shotts, jr.
january 2012, 480 pp., $39.95 by marijn haverbeke by justin seitz
isbn 978-1-59327-389-7 december 2014, 472 pp., $39.95 december 2014, 192 pp., $34.95
isbn 978-1-59327-584-6 isbn 978-1-59327-590-7

phone: email:
800.420.7240 or sa l es @ nosta rch.com
415.863.9900 web:
w w w.nosta rch.com

LEARN PYTHON—
FAST!

Python Crash Course is a fast-paced, thorough intro- • Make 2D games that respond to keypresses and
duction to programming with Python that will have you mouse clicks, and that grow more difficult as the
writing programs, solving problems, and making things game progresses
that work in no time.
• Work with data to generate interactive visualizations
In the first half of the book, you’ll learn about basic
programming concepts, such as lists, dictionaries, • Create and customize simple web apps and deploy
classes, and loops, and practice writing clean and them safely online
readable code with exercises for each topic. You’ll
also learn how to make your programs interactive • Deal with mistakes and errors so you can solve your
and how to test your code safely before adding it to own programming problems
a project. In the second half of the book, you’ll put
your new knowledge into practice with three substantial If you’ve been thinking seriously about digging into
projects: a Space Invaders–inspired arcade game, data programming, Python Crash Course will get you up to
visualizations with Python’s super-handy libraries, and a speed and have you writing real programs fast. Why
simple web app you can deploy online. wait any longer? Start your engines and code!

As you work through Python Crash Course, you’ll learn ABOUT THE AUTHOR
how to:
Eric Matthes is a high school science and math teacher
• Use powerful Python libraries and tools, including living in Alaska, where he teaches an introductory
matplotlib, NumPy, and Pygal Python course. He has been writing programs since he
was five years old.

COVERS PYTHON 2 AND 3 $39.95 ($45.95 CDN)

THE FINEST IN GEEK ENTERTAINMENT™ SHELVE IN:
w w w.nostarch.com PROGRAMMING LANGUAGES/
PYTHON
“I LIE FLAT.”
This book uses RepKover—a durable binding that won’t snap shut


Click to View FlipBook Version