Aprendiendo a programar con Python

Aprendiendo a programar con Python

@ProfGastonPerez
@ProfGastonPerez
1 Follower
1 week ago 33

This work highlights the praise received for 'Python Crash Course,' a book that offers an engaging and comprehensive approach to learning programming in Python. Aimed at beginners, it provides a blend of foundational concepts and practical projects, ensuring a hands-on experience. It’s celebrated for its clarity and effectiveness in teaching coding skills.

Aprendiendo a programar con Python

@ProfGastonPerez1 week ago

1/554
2/554
PRAISE FOR 
PYTHON CRASH COURSE
“It has been interesting to see No Starch Press producing future …
3/554
4/554
San Francisco
P Y T H O N C R A S H 
COURSE
3RD EDITION
A H a n d s - O n , P r o j e c t - B a…
5/554
PYTHON CRASH COURSE, 3RD EDITION. Copyright © 2023 by Eric Matthes.
All rights reserved. No part o…
6/554
For my father, who always made time to 
answer my questions about programming, 
and for Ever, who…
7/554
8/554
About the Author
Eric Matthes was a high school math and science teacher for 25 years, and 
he ta…
9/554
10/554
BRIEF CONTENTS
Preface to the Third Edition . . . . . . . . . . . . . . . . . . . . . . . . . . . …
11/554
x   Brief Contents
Chapter 18: Getting Started with Django . . . . . . . . . . . . . . . . . . . .…
12/554
CONTENTS IN DETAIL
PREFACE TO THE THIRD EDITION xxvii
ACKNOWLEDGMENTS xxxi
INTRODUCTION xxxiii
…
13/554
xii   Contents in Detail
Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .…
14/554
Contents in Detail   xiii
Finding the Length of a List . . . . . . . . . . . . . . . . . . . . . .…
15/554
xiv   Contents in Detail
Other Style Guidelines . . . . . . . . . . . . . . . . . . . . . . . . . …
16/554
Contents in Detail   xv
Modifying Values in a Dictionary . . . . . . . . . . . . . . . . . . . . .…
17/554
xvi   Contents in Detail
Exercise 7-9: No Pastrami . . . . . . . . . . . . . . . . . . . . . . . .…
18/554
Contents in Detail   xvii
9
CLASSES 157
Creating and Using a Class . . . . . . . . . . . . . . .…
19/554
xviii   Contents in Detail
Working with a File’s Contents . . . . . . . . . . . . . . . . . . . . …
20/554
Contents in Detail   xix
Testing a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . .…
21/554
xx   Contents in Detail
Limiting the Number of Bullets . . . . . . . . . . . . . . . . . . . . . .…
22/554
Contents in Detail   xxi
Leveling Up . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .…
23/554
xxii   Contents in Detail
Making a Histogram........................................ 322
Customiz…
24/554
Contents in Detail   xxiii
17
WORKING WITH APIS 355
Using an API . . . . . . . . . . . . . . . .…
25/554
xxiv   Contents in Detail
Exercise 18-5: Meal Planner . . . . . . . . . . . . . . . . . . . . . . …
26/554
Contents in Detail   xxv
Creating a requirements.txt File . . . . . . . . . . . . . . . . . . . . …
27/554
xxvi   Contents in Detail
Searching Online . . . . . . . . . . . . . . . . . . . . . . . . . . . .…
28/554
PREFACE TO THE THIRD EDITION
The response to the first and second editions of Python Crash Course …
29/554
xxviii   Preface to the Third Edition
The following is a summary of specific changes that have bee…
30/554
Preface to the Third Edition   xxix
help. Appendix D continues to offer a mini crash course in usi…
31/554
32/554
ACKNOWLEDGMENTS
This book would not have been possible without the wonderful and 
extremely profe…
33/554
xxxii   Acknowledgments
helping newer programmers develop a solid understanding of the Python 
la…
34/554
INTRODUCTION
Every programmer has a story about how 
they learned to write their first program. 
…
35/554
xxxiv   Introduction
I’ll always remember how satisfied I felt, watching my family play a 
game t…
36/554
Introduction   xxxv
so you only have to write blocks of code that perform certain actions once, 
…
37/554
xxxvi   Introduction
Solutions to exercises You should spend significant time on your own 
attemp…
38/554
PART I
BASICS
Part I of this book teaches you the basic concepts you’ll 
need to write Python pr…
39/554
2    Part I: Basics
Chapter 10 shows you how to work with files and handle errors so your 
progra…
40/554
1
GET TING STARTED
In this chapter, you’ll run your first Python 
program, hello_world.py. First…
41/554
4   Chapter 1
Python Versions
Every programming language evolves as new ideas and technologies em…
42/554
Getting Started   5
point. If you want to begin programming quickly, you can use VS Code to 
star…
43/554
6   Chapter 1
Figure 1-1: Make sure you select the checkbox labeled 
Add Python to PATH.
Running…
44/554
Getting Started   7
Python on macOS
Python is not installed by default on the latest versions of …
45/554
8   Chapter 1
This command starts a Python terminal session. You should see a 
Python prompt (>>>…
46/554
Getting Started   9
terminal prompt. Whenever you see the python command in this book, enter 
pyt…
47/554
10   Chapter 1
NOTE If you’re using macOS and a pop-up asks you to install the command line devel…
48/554
Getting Started   11
•	 Step away from your computer, take a short break, and then try again. 
Re…
49/554
12   Chapter 1
On Windows
You can use the terminal command cd, for change directory, to navigate …
50/554
Getting Started   13
TRY IT YOURSELF
The exercises in this chapter are exploratory in nature. Sta…
51/554
52/554
2
V A R I A B L E S A N D 
SIMPLE DATA T YPES
In this chapter you’ll learn about the different …
53/554
16   Chapter 2
When you run the file hello_world.py, the ending .py indicates that the 
file is a…
54/554
Variables and Simple Data Types    17
Naming and Using Variables
When you’re using variables in P…
55/554
18   Chapter 2
Here’s an example of the traceback that Python provides after you’ve accidentally …
56/554
Variables and Simple Data Types    19
This distinction probably won’t matter much in your initial …
57/554
20   Chapter 2
Changing Case in a String with Methods
One of the simplest tasks you can do with s…
58/554
Variables and Simple Data Types    21
a last name, respectively, and then combine those values to …
59/554
22   Chapter 2
To add a tab to your text, use the character combination \t:
>>> print("Python")
…
60/554
Variables and Simple Data Types    23
The value associated with favorite_language 1 contains extra…
61/554
24   Chapter 2
Enter the name of the variable followed by a dot, and then the method 
removeprefi…
62/554
Variables and Simple Data Types    25
something in the code as valid Python code, and it thinks th…
63/554
26   Chapter 2
Numbers
Numbers are used quite often in programming to keep score in games, 
repr…
64/554
Variables and Simple Data Types    27
can appear at any position in a number. Every programming la…
65/554
28   Chapter 2
Python defaults to a float in any operation that uses a float, even if the 
output…
66/554
Variables and Simple Data Types    29
TRY IT YOURSELF
2-9. Number Eight: Write addition, subtract…
67/554
30   Chapter 2
forgotten some of the details. You can always study your code for a while 
and fig…
68/554
Variables and Simple Data Types    31
someone might look over your shoulder one day and say, “Wow,…
69/554
32   Chapter 2
Summary
In this chapter you learned how to work with variables. You learned to use…
70/554
3
INTRODUCING LISTS
In this chapter and the next you’ll learn 
what lists are and how to start w…
71/554
34   Chapter 3
a list usually contains more than one element, it’s a good idea to make the 
name …
72/554
Introducing Lists   35
how the list operations are implemented at a lower level. If you’re receivi…
73/554
36   Chapter 3
TRY IT YOURSELF
Try these short programs to get some firsthand experience with Pyt…
74/554
Introducing Lists   37
Here we define the list motorcycles, with 'honda' as the first element. 
T…
75/554
38   Chapter 3
Building lists this way is very common, because you often won’t know 
the data you…
76/554
Introducing Lists   39
You can remove an item from any position in a list using the del statement…
77/554
40   Chapter 3
How might this pop() method be useful? Imagine that the motorcycles 
in the list a…
78/554
Introducing Lists   41
Here the remove() method tells Python to figure out where 'ducati'
appears…
79/554
42   Chapter 3
3-5. Changing Guest List: You just heard that one of your guests can’t make the 
d…
80/554
Introducing Lists   43
to preserve the original order of your list, and other times you’ll want to…
81/554
44   Chapter 3
We first print the list in its original order 1 and then in alphabetical 
order 2.…
82/554
Introducing Lists   45
You’ll find len() useful when you need to identify the number of aliens 
t…
83/554
46   Chapter 3
Avoiding Index Errors When Working with Lists
There’s one type of error that’s com…
84/554
Introducing Lists   47
If an index error occurs and you can’t figure out how to resolve it, try 
…
85/554
86/554
4
WORKING WITH LISTS
In Chapter 3 you learned how to make a 
simple list, and you learned to wor…
87/554
50   Chapter 4
Or perhaps you’ll want to display each headline from a list of articles on a 
webs…
88/554
Working with Lists   51
Python prints the current value of magician again, which is now 'david'. 
…
89/554
52   Chapter 4
Let’s add a second line to our message, telling each magician that we’re 
looking …
90/554
Working with Lists   53
I can't wait to see your next trick, David.
Carolina, that was a great tr…
91/554
54   Chapter 4
You can usually resolve this kind of indentation error by indenting the 
line or l…
92/554
Working with Lists   55
You can avoid unexpected indentation errors by indenting only when 
you h…
93/554
56   Chapter 4
If you accidentally forget the colon 1, you’ll get a syntax error because 
Python …
94/554
Working with Lists   57
to keep track of a player’s high scores as well. In data visualizations, y…
95/554
58   Chapter 4
Using range() to Make a List of Numbers
If you want to make a list of numbers, you…
96/554
Working with Lists   59
To write this code more concisely, omit the temporary variable square
and…
97/554
60   Chapter 4
To use this syntax, begin with a descriptive name for the list, such as 
squares. …
98/554
Working with Lists   61
Working with Part of a List
In Chapter 3 you learned how to access single…
99/554
62   Chapter 4
Python returns all items from the third item through the end of the list:
['michae…
100/554
Working with Lists   63
Copying a List
Often, you’ll want to start with an existing list and make…
101/554
64   Chapter 4
We copy the original items in my_foods to the new list friend_foods, as we 
did in…
102/554
Working with Lists   65
TRY IT YOURSELF
4-10. Slices: Using one of the programs you wrote in this…
103/554
66   Chapter 4
For example, if we have a rectangle that should always be a certain size, we 
can …
104/554
Working with Lists   67
Python returns all the elements in the tuple, just as it would for a list:…
105/554
68   Chapter 4
Styling Your Code
Now that you’re writing longer programs, it’s a good idea to lea…
106/554
Working with Lists   69
Line Length
Many Python programmers recommend that each line should be le…
107/554
70   Chapter 4
TRY IT YOURSELF
4-14. PEP 8: Look through the original PEP 8 style guide at https:…
108/554
5
IF STATEMENTS
Programming often involves examining 
a set of conditions and deciding which 
a…
109/554
72   Chapter 5
A Simple Example
The following example shows how if tests let you respond to speci…
110/554
if Statements   73
The first line sets the value of car to 'bmw' using a single equal sign, as 
y…
111/554
74   Chapter 5
ensure that every user has a truly unique username, not just a variation on 
the c…
112/554
if Statements   75
You can include various mathematical comparisons in your conditional 
statemen…
113/554
76   Chapter 5
Using or to Check Multiple Conditions
The keyword or allows you to check multiple …
114/554
if Statements   77
if user not in banned_users:
 print(f"{user.title()}, you can post a response …
115/554
78   Chapter 5
5-2. More Conditional Tests: You don’t have to limit the number of tests you creat…
116/554
if Statements   79
Indentation plays the same role in if statements as it did in for loops. All 
…
117/554
80   Chapter 5
structure works well in situations in which you want Python to always execute one …
118/554
if Statements   81
and then have a single print() call that runs after the chain has been 
evalua…
119/554
82   Chapter 5
Omitting the else Block
Python does not require an else block at the end of an if-…
120/554
if Statements   83
if 'extra cheese' in requested_toppings:
 print("Adding extra cheese.")
print…
121/554
84   Chapter 5
TRY IT YOURSELF
5-3. Alien Colors #1: Imagine an alien was just shot down in a gam…
122/554
if Statements   85
5-7. Favorite Fruit: Make a list of your favorite fruits, and then write a seri…
123/554
86   Chapter 5
But what if the pizzeria runs out of green peppers? An if statement 
inside the fo…
124/554
if Statements   87
example. If the conditional test fails, we print a message asking the customer…
125/554
88   Chapter 5
In just a few lines of code, we’ve managed a real-world situation pretty 
effectiv…
126/554
if Statements   89
Styling Your if Statements
In every example in this chapter, you’ve seen good …
127/554
128/554
6
DICTIONARIES
In this chapter you’ll learn how to use 
Python’s dictionaries, which allow you t…
129/554
92   Chapter 6
A Simple Dictionary
Consider a game featuring aliens that can have different color…
130/554
Dictionaries   93
This returns the value associated with the key 'color' from the dictionary alie…
131/554
94   Chapter 6
We start by defining the same dictionary that we’ve been working with. 
We then pr…
132/554
Dictionaries   95
alien_0['color'] = 'yellow'
print(f"The alien is now {alien_0['color']}.")
We …
133/554
96   Chapter 6
This technique is pretty cool: by changing one value in the alien’s dictionary, yo…
134/554
Dictionaries   97
As you can see, we’ve broken a larger dictionary into several lines. Each 
key …
135/554
98   Chapter 6
Let’s see what happens when you ask for the point value of an alien that 
doesn’t …
136/554
Dictionaries   99
number for each person, and store each as a value in your dictionary. Print 
ea…
137/554
100   Chapter 6
for key, value in user_0.items():
 print(f"\nKey: {key}")
 print(f"Value: {value…
138/554
Dictionaries   101
Now, in just a few lines of code, we can display all of the information 
from …
139/554
102   Chapter 6
the dictionary as we did previously, but when the name matches one of our 
friend…
140/554
Dictionaries   103
One way to do this is to sort the keys as they’re returned in the for loop. 
Y…
141/554
104   Chapter 6
This approach pulls all the values from the dictionary without checking for repea…
142/554
Dictionaries   105
6-5. Rivers: Make a dictionary containing three major rivers and the country 
…
143/554
106   Chapter 6
We first create three dictionaries, each representing a different alien. 
We stor…
144/554
Dictionaries   107
the first three aliens to yellow, medium-speed aliens worth 10 points each, 
w…
145/554
108   Chapter 6
on page 99, and store the individual dictionaries in a list called users. All 
of…
146/554
Dictionaries   109
When we loop through the dictionary, the value associated with each person wou…
147/554
110   Chapter 6
A Dictionary in a Dictionary
You can nest a dictionary inside another dictionary,…
148/554
Dictionaries   111
Username: mcurie
 Full name: Marie Curie
 Location: Paris
Notice that the st…
149/554
112   Chapter 6
of the information in a dictionary. You learned to loop through a dictionary’s ke…
150/554
7
USER INPUT AND WHILE LOOPS
Most programs are written to solve an end 
user’s problem. To do so…
151/554
114   Chapter 7
program can work with that information. You’ll use Python’s while loop to 
keep p…
152/554
User Input and while Loops   115
Sometimes you’ll want to write a prompt that’s longer than one li…
153/554
116   Chapter 7
We can resolve this issue by using the int() function, which converts 
the input …
154/554
User Input and while Loops   117
The modulo operator doesn’t tell you how many times one number fi…
155/554
118   Chapter 7
 print(current_number)
 current_number += 1
In the first line, we start counting…
156/554
User Input and while Loops   119
problem, we make sure to give message an initial value. Although …
157/554
120   Chapter 7
Using a Flag
In the previous example, we had the program perform certain tasks wh…
158/554
User Input and while Loops   121
have a flag to indicate whether the overall program is in an acti…
159/554
122   Chapter 7
Using continue in a Loop
Rather than breaking out of a loop entirely without exec…
160/554
User Input and while Loops   123
Now the value of x will start at 1 but never change. As a result,…
161/554
124   Chapter 7
Using a while Loop with Lists and Dictionaries
So far, we’ve worked with only one…
162/554
User Input and while Loops   125
unconfirmed users is empty, the loop stops and the list of confir…
163/554
126   Chapter 7
while polling_active:
 # Prompt for the person's name and response.
1 name = inp…
164/554
User Input and while Loops   127
TRY IT YOURSELF
7-8. Deli: Make a list called sandwich_orders an…
165/554
166/554
8
FUNCTIONS
In this chapter you’ll learn to write functions, which are named blocks of code 
de…
167/554
130   Chapter 8
Defining a Function
Here’s a simple function named greet_user() that prints a gre…
168/554
Functions   131
Entering greet_user('jesse') calls greet_user() and gives the function the 
infor…
169/554
132   Chapter 8
Positional Arguments
When you call a function, Python must match each argument in…
170/554
Functions   133
I have a dog.
My dog's name is Willie.
Calling a function multiple times is a ve…
171/554
134   Chapter 8
The function describe_pet() hasn’t changed. But when we call the function, we exp…
172/554
Functions   135
The simplest way to use this function now is to provide just a dog’s 
name in the…
173/554
136   Chapter 8
Avoiding Argument Errors
When you start to use functions, don’t be surprised if y…
174/554
Functions   137
8-4. Large Shirts: Modify the make_shirt() function so that shirts are large 
by …
175/554
138   Chapter 8
However, when you consider working with a large program that needs 
to store many…
176/554
Functions   139
In this example, the name is built from three possible parts. Because 
there’s al…
177/554
140   Chapter 8
This function takes in simple textual information and puts it into a 
more meanin…
178/554
Functions   141
inputs? We want the user to be able to quit as easily as possible, so each 
promp…
179/554
142   Chapter 8
8-7. Album: Write a function called make_album() that builds a dictionary 
descri…
180/554
Functions   143
Modifying a List in a Function
When you pass a list to a function, the function c…
181/554
144   Chapter 8
 Move each design to completed_models after printing.
 """
 while unprinted_desi…
182/554
Functions   145
print_models() again. If we realize the printing code needs to be modified, 
we c…
183/554
146   Chapter 8
TRY IT YOURSELF
8-9. Messages: Make a list containing a series of short text mess…
184/554
Functions   147
 print("\nMaking a pizza with the following toppings:")
 for topping in toppings:…
185/554
148   Chapter 8
Making a 12-inch pizza with the following toppings:
- mushrooms
- green peppers
…
186/554
Functions   149
You can mix positional, keyword, and arbitrary values in many different ways when…
187/554
150   Chapter 8
having to share your entire program. Knowing how to import functions 
also allows…
188/554
Functions   151
available in your program. If you use this kind of import statement to import 
an…
189/554
152   Chapter 8
The general syntax for providing an alias is:
from module_name import function_na…
190/554
Functions   153
Styling Functions
You need to keep a few details in mind when you’re styling func…
191/554
154   Chapter 8
TRY IT YOURSELF
8-15. Printing Models: Put the functions for the example printing…
192/554
Functions   155
Functions also make your code easier to test and debug. When the bulk 
of your pr…
193/554
194/554
9
CLASSES
Object-oriented programming (OOP) is one of 
the most effective approaches to writing …
195/554
158   Chapter 9
less code. You’ll store your classes in modules and import classes written by 
ot…
196/554
Classes   159
The __init__() Method
A function that’s part of a class is a method. Everything you…
197/554
160   Chapter 9
Let’s make an instance representing a specific dog:
class Dog:
 --snip--
1 my_d…
198/554
Classes   161
To call a method, give the name of the instance (in this case, my_dog) 
and the met…
199/554
162   Chapter 9
TRY IT YOURSELF
9-1. Restaurant: Make a class called Restaurant. The __init__() m…
200/554
Classes   163
 return long_name.title()
3 my_new_car = Car('audi', 'a4', 2024)
print(my_new_car.…
201/554
164   Chapter 9
This time, when Python calls the __init__() method to create a new 
instance, it …
202/554
Classes   165
Here’s an example showing a method called update_odometer():
class Car:
 --snip--
…
203/554
166   Chapter 9
on it between the time we buy it and the time we register it. Here’s a 
method th…
204/554
Classes   167
Add a method called set_number_served() that lets you set the number of 
customers …
205/554
168   Chapter 9
 self.year = year
 self.odometer_reading = 0
 def get_descriptive_name(self):
 …
206/554
Classes   169
Aside from __init__(), there are no attributes or methods yet that are 
particular …
207/554
170   Chapter 9
electric car to whatever degree of accuracy you need. An attribute or 
method tha…
208/554
Classes   171
 """Initialize the battery's attributes."""
 self.battery_size = battery_size
2 de…
209/554
172   Chapter 9
add another method to Battery that reports the range of the car based on 
the bat…
210/554
Classes   173
logical level rather than a syntax-focused level. You’re thinking not about 
Python…
211/554
174   Chapter 9
Importing a Single Class
Let’s create a module containing just the Car class. Thi…
212/554
Classes   175
my_new_car.odometer_reading = 23
my_new_car.read_odometer()
The import statement 1…
213/554
176   Chapter 9
 Initialize attributes of the parent class.
 Then initialize attributes specific …
214/554
Classes   177
Here’s what it looks like to import the entire car module and then 
create a regula…
215/554
178   Chapter 9
class Battery:
 --snip--
class ElectricCar(Car):
 --snip--
The class ElectricC…
216/554
Classes   179
You can also give a module an alias. Here’s how to import the entire 
electric_car …
217/554
180   Chapter 9
One interesting function from the random module is randint(). This 
function take…
218/554
Classes   181
Styling Classes
A few styling issues related to classes are worth clarifying, espec…
219/554
220/554
10
FILES AND EXCEPTIONS
Now that you’ve mastered the basic skills 
you need to write organized p…
221/554
184   Chapter 10
innocent mistakes or from malicious attempts to break your programs. With 
the s…
222/554
Files and Exceptions   185
directory as the .py file we’re writing, the filename is all that Path …
223/554
186   Chapter 10
Relative and Absolute File Paths
When you pass a simple filename like pi_digits.…
224/554
Files and Exceptions   187
you might want to modify the text in the file in some way. For example,…
225/554
188   Chapter 10
to hold the digits of pi. We write a loop that adds each line of digits to 
pi_s…
226/554
Files and Exceptions   189
The output shows that we do indeed have a string containing pi to 
1,0…
227/554
190   Chapter 10
10-2. Learning C: You can use the replace() method to replace any word in a 
str…
228/554
Files and Exceptions   191
This file behaves like any other file on your computer. You can open it…
229/554
192   Chapter 10
TRY IT YOURSELF
10-4. Guest: Write a program that prompts the user for their nam…
230/554
Files and Exceptions   193
Using try-except Blocks
When you think an error may occur, you can wri…
231/554
194   Chapter 10
This program prompts the user to input a first_number 1 and, if the 
user does n…
232/554
Files and Exceptions   195
we print a friendly message telling the user how to avoid this kind of …
233/554
196   Chapter 10
 File "/.../pathlib.py", line 1056, in read_text
 with self.open(mode='r', encod…
234/554
Files and Exceptions   197
Let’s pull in the text of Alice in Wonderland and try to count the numb…
235/554
198   Chapter 10
path = Path('alice.txt')
count_words(path)
Most of this code is unchanged. It’s…
236/554
Files and Exceptions   199
nothing in the except block. Python has a pass statement that tells it …
237/554
200   Chapter 10
TRY IT YOURSELF
10-6. Addition: One common problem when prompting for numerical …
238/554
Files and Exceptions   201
Storing Data
Many of your programs will ask users to input certain kin…
239/554
202   Chapter 10
Now we’ll write a separate program that uses json.loads() to read the 
list back…
240/554
Files and Exceptions   203
Now let’s write a new program that greets a user whose name has 
alrea…
241/554
204   Chapter 10
Otherwise:
Welcome back, Eric!
This is the output you see if the program was al…
242/554
Files and Exceptions   205
 if path.exists():
 contents = path.read_text()
 username = json.load…
243/554
206   Chapter 10
 else:
2 username = get_new_username(path)
 print(f"We'll remember you when you…
244/554
Files and Exceptions   207
Summary
In this chapter, you learned how to work with files. You learn…
245/554
246/554
11
TESTING YOUR CODE
When you write a function or a class, you 
can also write tests for that co…
247/554
210   Chapter 11
You’ll learn to build a series of tests and check that each set of inputs 
resul…
248/554
Testing Your Code   211
Installing pytest
Now that pip is up to date, we can install pytest:
$ p…
249/554
212   Chapter 11
This program imports get_formatted_name() from name_function.py. The 
user can e…
250/554
Testing Your Code   213
Here’s the first test of the function get_formatted_name():
test_name
_f…
251/554
214   Chapter 11
Let’s try to make sense of this output. First of all, we see some information 
a…
252/554
Testing Your Code   215
test_name_function.py:5: TypeError
======================= short test sum…
253/554
216   Chapter 11
In this new version of get_formatted_name(), the middle name is optional. 
If a …
254/554
Testing Your Code   217
The two dots 1 indicate that two tests passed, which is also clear from 
…
255/554
218   Chapter 11
assume is True is actually False, the test will fail and you’ll know there’s an 
…
256/554
Testing Your Code   219
have to provide is a question. Once you have an instance representing a pa…
257/554
220   Chapter 11
Implementing such changes would risk affecting the current behavior 
of the clas…
258/554
Testing Your Code   221
 --snip--
def test_store_three_responses():
 """Test that three individu…
259/554
222   Chapter 11
 question = "What language did you first learn to speak?"
 language_survey = Ano…
260/554
Testing Your Code   223
decorator to the new function, and add the name of this function as a 
pa…
261/554
262/554
PART II
PROJECTS
Congratulations! You now know enough about Python 
to start building interactiv…
263/554
226    Part II: Projects
and visualize data. Learning to make visualizations allows you to explore…
264/554
12
A SHIP THAT FIRES BULLETS
Let’s build a game called Alien Invasion! 
We’ll use Pygame, a coll…
265/554
228   Chapter 12
Making games is an ideal way to have fun while learning a language. It’s 
deeply…
266/554
A Ship That Fires Bullets   229
Starting the Game Project
We’ll begin building the game by creati…
267/554
230   Chapter 12
display window to the attribute self.screen, so it will be available in all meth…
268/554
A Ship That Fires Bullets   231
 self.clock = pygame.time.Clock()
 --snip--
After initializing p…
269/554
232   Chapter 12
mixes equal amounts of red, blue, and green, which produces a light gray 
backgr…
270/554
A Ship That Fires Bullets   233
 def run_game(self):
 --snip--
 # Redraw the screen during each …
271/554
234   Chapter 12
Figure 12-1: The ship for Alien Invasion
Creating the Ship Class
After choosing…
272/554
A Ship That Fires Bullets   235
game will notice that we’re not working with the exact shape of ea…
273/554
236   Chapter 12
class AlienInvasion:
 """Overall class to manage game assets and behavior."""
 …
274/554
A Ship That Fires Bullets   237
Refactoring: The _check_events() and _update_screen() Methods
In …
275/554
238   Chapter 12
 def _update_screen(self):
 """Update images on the screen, and flip to the new …
276/554
A Ship That Fires Bullets   239
When Pygame detects a KEYDOWN event, we need to check whether the …
277/554
240   Chapter 12
 # Movement flag; start with a ship that's not moving.
1 self.moving_right = Fal…
278/554
A Ship That Fires Bullets   241
Moving Both Left and Right
Now that the ship can move continuousl…
279/554
242   Chapter 12
Next, we’ll further refine the ship’s movement. Let’s adjust the ship’s 
speed a…
280/554
A Ship That Fires Bullets   243
 if self.moving_left:
 self.x -= self.settings.ship_speed
 # Upd…
281/554
244   Chapter 12
When you run alien_invasion.py now, the ship should stop moving at 
either edge …
282/554
A Ship That Fires Bullets   245
 self.ship.moving_left = True
 elif event.key == pygame.K_q:
 sy…
283/554
246   Chapter 12
alien_invasion.py
The main file, alien_invasion.py, contains the AlienInvasion c…
284/554
A Ship That Fires Bullets   247
Shooting Bullets
Now let’s add the ability to shoot bullets. We’l…
285/554
248   Chapter 12
super() to inherit properly from Sprite. We also set attributes for the screen 
…
286/554
A Ship That Fires Bullets   249
First, we’ll import the new Bullet class:
alien_invasion.py --sni…
287/554
250   Chapter 12
 def _update_screen(self):
 """Update images on the screen, and flip to the new …
288/554
A Ship That Fires Bullets   251
We need to get rid of these old bullets, or the game will slow dow…
289/554
252   Chapter 12
This limits the player to three bullets at a time. We’ll use this setting in 
Al…
290/554
A Ship That Fires Bullets   253
Run alien_invasion.py one more time, and make sure you can still f…
291/554
292/554
13
ALIENS!
In this chapter, we’ll add aliens to Alien 
Invasion. We’ll add one alien near the to…
293/554
256   Chapter 13
Reviewing the Project
When you’re beginning a new phase of development on a larg…
294/554
Aliens!   257
Creating the Alien Class
Now we’ll write the Alien class and save it as alien.py:
…
295/554
258   Chapter 13
And here’s the updated __init__() method:
alien_invasion.py def __init__(self):
…
296/554
Aliens!   259
Now that the first alien appears correctly, we’ll write the code to draw 
an entire…
297/554
260   Chapter 13
Whenever there’s enough horizontal space to continue the loop, we 
want to do tw…
298/554
Aliens!   261
1 def _create_alien(self, x_position):
 """Create an alien and place it in the row.…
299/554
262   Chapter 13
We call _create_alien(), and pass it the y-value as well as its x-position 4. 
W…
300/554
Aliens!   263
TRY IT YOURSELF
13-1. Stars: Find an image of a star. Make a grid of stars appear o…
301/554
264   Chapter 13
right by the amount stored in alien_speed. We track the alien’s exact position 
…
302/554
Aliens!   265
changes direction. (Using numbers also makes sense because moving right 
involves a…
303/554
266   Chapter 13
 """Drop the entire fleet and change the fleet's direction."""
 for alien in sel…
304/554
Aliens!   267
Detecting Bullet Collisions
We want to know right away when a bullet hits an alien …
305/554
268   Chapter 13
Making Larger Bullets for Testing
You can test many features of Alien Invasion s…
306/554
Aliens!   269
 # Destroy existing bullets and create new fleet.
2 self.bullets.empty()
 self._cr…
307/554
270   Chapter 13
 if not self.aliens:
 # Destroy existing bullets and create new fleet.
 self.bu…
308/554
Aliens!   271
If no collisions occur, spritecollideany() returns None and the if block 
won’t exe…
309/554
272   Chapter 13
We also need to make a few changes in alien_invasion.py to create an 
instance o…
310/554
Aliens!   273
 # Pause.
4 sleep(0.5)
The new method _ship_hit() coordinates the response when an…
311/554
274   Chapter 13
1 if alien.rect.bottom >= self.settings.screen_height:
 # Treat this the same as…
312/554
Aliens!   275
Most of _ship_hit() is unchanged. We’ve moved all the existing code 
into an if blo…
313/554
276   Chapter 13
objects on the screen and to respond to specific situations, such as when the 
f…
314/554
14
SCORING
In this chapter, we’ll finish building Alien 
Invasion. We’ll add a Play button to st…
315/554
278   Chapter 14
Adding the Play Button
In this section, we’ll add a Play button that appears bef…
316/554
Scoring   279
Next, we prepare a font attribute for rendering text 3. The None argument tells Pyg…
317/554
280   Chapter 14
Because we need only one Play button, we’ll create the button in the 
__init__()…
318/554
Scoring   281
Starting the Game
To start a new game when the player clicks Play, add the followin…
319/554
282   Chapter 14
 # Get rid of any remaining bullets and aliens.
2 self.bullets.empty()
 self.al…
320/554
Scoring   283
Passing False to set_visible() tells Pygame to hide the cursor when the 
mouse is o…
321/554
284   Chapter 14
during the game reset when we start a new game. Here’s the __init__()
method for…
322/554
Scoring   285
because when the aliens move faster across the screen, they’ll also come 
down the …
323/554
286   Chapter 14
TRY IT YOURSELF
14-3. Challenging Target Practice: Start with your work from Exe…
324/554
Scoring   287
 # Prepare the initial score image.
4 self.prep_score()
Because Scoreboard writes …
325/554
288   Chapter 14
Next, we make an instance of Scoreboard in __init__():
alien_invasion.py def __i…
326/554
Scoring   289
Updating the Score as Aliens Are Shot Down
To write a live score onscreen, we updat…
327/554
290   Chapter 14
We call prep_score() after resetting the game stats when starting a new 
game. T…
328/554
Scoring   291
 def increase_speed(self):
 """Increase speed settings and alien point values."""
…
329/554
292   Chapter 14
commas at appropriate places in the numerical value that’s provided. This 
resul…
330/554
Scoring   293
Here’s the prep_high_score() method:
scoreboard.py def prep_high_score(self):
 """…
331/554
294   Chapter 14
The first time you play Alien Invasion, your score will be the high score, 
so i…
332/554
Scoring   295
1 self.level_image = self.font.render(level_str, True,
 self.text_color, self.setti…
333/554
296   Chapter 14
Figure 14-5: The current level appears just below the current score.
NOTE In som…
334/554
Scoring   297
Next, we need to modify Scoreboard to create a group of ships we can 
display. Here…
335/554
298   Chapter 14
To display the ships on the screen, we call draw() on the group, and 
Pygame dra…
336/554
Scoring   299
TRY IT YOURSELF
14-5. All-Time High Score: The high score is reset every time a pla…
337/554
338/554
15
GENER ATING DATA
Data visualization is the use of visual representations to explore and prese…
339/554
302   Chapter 15
have to be numbers; with the basics you learned in the first part of this 
book,…
340/554
Generating Data   303
1 fig, ax = plt.subplots()
ax.plot(squares)
plt.show()
We first import th…
341/554
304   Chapter 15
We’ll use a few of the available customizations to improve this plot’s 
readabil…
342/554
Generating Data   305
Correcting the Plot
Now that we can read the chart better, we can see that …
343/554
306   Chapter 15
Using Built-in Styles
Matplotlib has a number of predefined styles available. Th…
344/554
Generating Data   307
To plot a single point, pass the single x- and y-values of the point to 
sc…
345/554
308   Chapter 15
Plotting a Series of Points with scatter()
To plot a series of points, we can pa…
346/554
Generating Data   309
plt.style.use('seaborn')
fig, ax = plt.subplots()
2 ax.scatter(x_values, y…
347/554
310   Chapter 15
Almost every element of a chart is customizable, so you can tell Matplotlib 
to …
348/554
Generating Data   311
tell pyplot which colormap to use with the cmap argument. This code colors 
…
349/554
312   Chapter 15
Random Walks
In this section, we’ll use Python to generate data for a random wal…
350/554
Generating Data   313
 # Keep taking steps until the walk reaches the desired length.
1 while len…
351/554
314   Chapter 15
1 rw = RandomWalk()
rw.fill_walk()
# Plot the points in the walk.
plt.style.us…
352/554
Generating Data   315
while True:
 # Make a random walk.
 --snip--
 plt.show()
 keep_running =…
353/554
316   Chapter 15
We use range() to generate a list of numbers equal to the number of 
points in t…
354/554
Generating Data   317
plot the last x- and y-values in red with a size of 100 as well. Make sure y…
355/554
318   Chapter 15
This example creates a random walk with 50,000 points and plots each 
point at s…
356/554
Generating Data   319
TRY IT YOURSELF
15-3. Molecular Motion: Modify rw_visual.py by replacing ax…
357/554
320   Chapter 15
Installing Plotly
Install Plotly using pip, just as you did for Matplotlib:
$ p…
358/554
Generating Data   321
# Make some rolls, and store results in a list.
results = []
2 for roll_nu…
359/554
322   Chapter 15
then append this value to frequencies 4. We print this list before making a 
vis…
360/554
Generating Data   323
Figure 15-12: The initial plot produced by Plotly Express
Customizing the P…
361/554
324   Chapter 15
Figure 15-13: A simple bar chart created with Plotly
Rolling Two Dice
Rolling t…
362/554
Generating Data   325
# Visualize the results.
title = "Results of Rolling Two D6 Dice 1,000 Time…
363/554
326   Chapter 15
Plotly has an update_layout() method that can be used to make a wide 
variety of…
364/554
Generating Data   327
Figure 15-15 shows the resulting chart. Instead of one most likely result, 
…
365/554
328   Chapter 15
TRY IT YOURSELF
15-6. Two D8s: Create a simulation showing what happens when you…
366/554
16
DOWNLOADING DATA
In this chapter, you’ll download datasets 
from online sources and create wo…
367/554
330   Chapter 16
By the end of this chapter, you’ll be prepared to work with various types 
of da…
368/554
Downloading Data   331
Next, we build a reader object 2. This is an object that can be used 
to p…
369/554
332   Chapter 16
We can see that the dates and their high temperatures are stored in columns 2 an…
370/554
Downloading Data   333
# Plot the high temperatures.
plt.style.use('seaborn')
fig, ax = plt.subp…
371/554
334   Chapter 16
an object representing July 1, 2021, using the strptime() method from the 
datet…
372/554
Downloading Data   335
reader = csv.reader(lines)
header_row = next(reader)
# Extract dates and …
373/554
336   Chapter 16
Plotting a Longer Timeframe
With our graph set up, let’s include additional data…
374/554
Downloading Data   337
 current_date = datetime.strptime(row[2], '%Y-%m-%d')
 high = int(row[4])
…
375/554
338   Chapter 16
fig, ax = plt.subplots()
1 ax.plot(dates, highs, color='red', alpha=0.5)
ax.plo…
376/554
Downloading Data   339
First, let’s run the code to see the headers that are included in this 
da…
377/554
340   Chapter 16
The traceback tells us that Python can’t process the high temperature for 
one o…
378/554
Downloading Data   341
Figure 16-6: Daily high and low temperatures for Death Valley
Many dataset…
379/554
342   Chapter 16
6. On the next page, you can select the kinds of data you want. You can 
downloa…
380/554
Downloading Data   343
each one was. Because the data is stored in the GeoJSON format, we’ll work …
381/554
344   Chapter 16
We read the data file as a string, and use json.loads() to convert the 
string r…
382/554
Downloading Data   345
 ]
 },
 "id": "ak0224bju1jx"
 },
The key "properties" contains a lot of…
383/554
346   Chapter 16
Notice how short this code is. The neatly formatted file readable_eq_data
.json …
384/554
Downloading Data   347
 lats.append(lat)
print(mags[:10])
print(lons[:5])
print(lats[:5])
We m…
385/554
348   Chapter 16
Figure 16-7: A simple map showing where all the earthquakes in the last 24 hours …
386/554
Downloading Data   349
Figure 16-8: The map now shows the magnitude of all earthquakes in the last…
387/554
350   Chapter 16
We add one more argument, to modify the base map over which the 
earthquakes are…
388/554
Downloading Data   351
To make this change, we need to pull a little more data from the file:
eq_…
389/554
352   Chapter 16
illustrates the geological structure of the planet. Plotly offers a wide range 
…
390/554
Downloading Data   353
formats, you’ll be able to learn how to work with other data formats more 
…
391/554
392/554
17
WORKING WITH APIS
In this chapter, you’ll learn how to write 
a self-contained program that g…
393/554
356   Chapter 17
easily processed format, such as JSON or CSV. Most apps that use external 
data …
394/554
Working with APIs   357
The following snippet shows the first few lines of the response:
{
1 "to…
395/554
358   Chapter 17
# Convert the response object to a dictionary.
5 response_dict = r.json()
# Pro…
396/554
Working with APIs   359
1 print(f"Total repositories: {response_dict['total_count']}")
print(f"Co…
397/554
360   Chapter 17
GitHub’s API returns a lot of information about each repository: there 
are 78 k…
398/554
Working with APIs   361
Summarizing the Top Repositories
When we make a visualization for this da…
399/554
362   Chapter 17
Some interesting projects appear in these results, and it might be worth 
lookin…
400/554
Working with APIs   363
Save a copy of the program we’ve been working on as python_repos
_visual.…
401/554
364   Chapter 17
Figure 17-1: The most-starred Python projects on GitHub
Styling the Chart
Plotl…
402/554
Working with APIs   365
Figure 17-2: A title has been added to the main chart, and to each axis as…
403/554
366   Chapter 17
fig.update_layout(title_font_size=28, xaxis_title_font_size=20,
 yaxis_title_fon…
404/554
Working with APIs   367
3 repo_link = f"<a href='{repo_url}'>{repo_name}</a>"
 repo_links.append(…
405/554
368   Chapter 17
More About Plotly and the GitHub API
Plotly’s documentation is extensive and wel…
406/554
Working with APIs   369
Everything in this program should look familiar, because we’ve used 
it a…
407/554
370   Chapter 17
3 submission_dicts = []
for submission_id in submission_ids[:5]:
 # Make a new …
408/554
Working with APIs   371
to the discussion page, and the number of comments the submission current…
409/554
372   Chapter 17
17-3. Testing python_repos.py: In python_repos.py, we printed the value of 
stat…
410/554
18
GET TING STARTED WITH DJANGO
As the internet has evolved, the line between 
websites and mobi…
411/554
374   Chapter 18
you’ll refine the Learning Log project, and then deploy it to a live server so 
…
412/554
Getting Started with Django   375
two lowercase Ls, not two ones). If you use a command such as py…
413/554
376   Chapter 18
NOTE Django releases a new version about every eight months, so you may see a new…
414/554
Getting Started with Django   377
 Apply all migrations: admin, auth, contenttypes, sessions
Runn…
415/554
378   Chapter 18
term localhost refers to a server that only processes requests on your system; 
…
416/554
Getting Started with Django   379
Starting an App
A Django project is organized as a group of ind…
417/554
380   Chapter 18
3 def __str__(self):
 """Return a string representation of the model."""
 retur…
418/554
Getting Started with Django   381
 # Default django apps.
 'django.contrib.admin',
 --snip--
]
…
419/554
382   Chapter 18
Setting Up a Superuser
Django allows you to create a superuser, a user who has a…
420/554
Getting Started with Django   383
To register Topic with the admin site, enter the following:
fro…
421/554
384   Chapter 18
Defining the Entry Model
For a user to record what they’ve been learning about c…
422/554
Getting Started with Django   385
Migrating the Entry Model
Because we’ve added a new model, we n…
423/554
386   Chapter 18
the admin interface if you see only the first part of an entry, rather than the 
…
424/554
Getting Started with Django   387
If you know the ID of a particular object, you can use the metho…
425/554
388   Chapter 18
only if the entry is longer than 50 characters. Use the admin site to add an 
en…
426/554
Getting Started with Django   389
In the main ll_project folder, open the file urls.py. You should…
427/554
390   Chapter 18
The actual URL pattern is a call to the path() function, which takes 
three argu…
428/554
Getting Started with Django   391
access any data provided by the view. Because our view for the h…
429/554
392   Chapter 18
NOTE You might see the following error message:
ModuleNotFoundError: No module n…
430/554
Getting Started with Django   393
</p>
2 {% block content %}{% endblock content %}
The first par…
431/554
394   Chapter 18
is part of learning_logs, so we include learning_logs in the path to the parent 
…
432/554
Getting Started with Django   395
The new URL pattern is the word topics, followed by a forward sl…
433/554
396   Chapter 18
1 <ul>
2 {% for topic in topics %}
3 <li>{{ topic.text }}</li>
4 {% empty %}
…
434/554
Getting Started with Django   397
Django to generate a link matching the URL pattern with the name…
435/554
398   Chapter 18
When Django finds a URL that matches this pattern, it calls the view 
function t…
436/554
Getting Started with Django   399
 <li>There are no entries for this topic yet.</li>
 {% endfor %…
437/554
400   Chapter 18
Figure 18-5: The detail page for a single topic, showing all entries for a topic
…
438/554
Getting Started with Django   401
In Chapter 19, you’ll make intuitive, user-friendly pages that a…
439/554
440/554
19
USER ACCOUNTS
At the heart of a web application is the ability for any user, anywhere in the …
441/554
404   Chapter 19
Allowing Users to Enter Data
Before we build an authentication system for creati…
442/554
User Accounts   405
The new_topic URL
The URL for a new page should be short and descriptive. Whe…
443/554
406   Chapter 19
GET and POST Requests
The two main types of requests you’ll use when building ap…
444/554
User Accounts   407
The new_topic Template
Now we’ll make a new template called new_topic.html to…
445/554
408   Chapter 19
Place the link after the list of existing topics. Figure 19-1 shows the 
resulti…
446/554
User Accounts   409
default widget choices. Here we’re telling Django to use a forms.Textarea ele…
447/554
410   Chapter 19
We update the import statement to include the EntryForm we just made. 
The defin…
448/554
User Accounts   411
The form’s action argument includes the topic.id value in the URL, 
so the vi…
449/554
412   Chapter 19
Editing Entries
Now we’ll make a page so users can edit the entries they’ve adde…
450/554
User Accounts   413
block, which runs for a GET request, we make an instance of EntryForm with 
t…
451/554
414   Chapter 19
 <p>{{ entry.date_added|date:'M d, Y H:i' }}</p>
 <p>{{ entry.text|linebreaks }}…
452/554
User Accounts   415
TRY IT YOURSELF
19-1. Blog: Start a new Django project called Blog. Create an…
453/554
416   Chapter 19
 # Default django apps.
 --snip--
]
--snip--
Now Django will include the acco…
454/554
User Accounts   417
The login page’s pattern matches the URL http://localhost:8000/accounts/
logi…
455/554
418   Chapter 19
Add the following code to the end of settings.py:
settings.py --snip--
# My set…
456/554
User Accounts   419
Figure 19-4: The login page
Logging Out
Now we need to provide a way for use…
457/554
420   Chapter 19
consistent position below any other content on the page. The form itself has 
th…
458/554
User Accounts   421
The register() View Function
The register() view function needs to display a …
459/554
422   Chapter 19
where a personalized greeting in the header tells them their registration 
was s…
460/554
User Accounts   423
NOTE The registration system we’ve set up allows anyone to make any number of …
461/554
424   Chapter 19
We first import the login_required() function. We apply login_required()
as a de…
462/554
User Accounts   425
@login_required
def new_entry(request, topic_id):
 --snip--
@login_required…
463/554
426   Chapter 19
Identifying Existing Users
When we migrate the database, Django will modify the …
464/554
User Accounts   427
We start by issuing the makemigrations command 1. In the output, 
Django indi…
465/554
428   Chapter 19
Make the following change to the topics() function in views.py:
learning_logs/
…
466/554
User Accounts   429
A 404 response is a standard error response that’s returned when a 
requested…
467/554
430   Chapter 19
1 new_topic = form.save(commit=False)
2 new_topic.owner = request.user
3 new_to…
468/554