More on this book
Community
Kindle Notes & Highlights
by
Eric Matthes
Read between
September 1, 2017 - March 20, 2018
You can actually use pop() to remove an item in a list at any position by including the index of the item you want to remove in parentheses.
If you only know the value of the item you want to remove, you can use the remove() method.
You can also sort this list in reverse alphabetical order by passing the argument reverse=True to the sort() method.
The sorted() function lets you display your list in a particular order but doesn’t affect the actual order of the list.
To reverse the original order of a list, you can use the reverse() method.
We can also use the range() function to tell Python to skip numbers in a given range. For example, here’s how we would list the even numbers between 1 and 10:
A list comprehension allows you to generate this same list in just one line of code. A list comprehension combines the for loop and the creation of new elements into one line, and automatically appends each new element.
Often, you’ll want to start with an existing list and make an entirely new list based on the first one. Let’s explore how copying a list works and examine one situation in which copying a list is useful.
If we had simply set friend_foods equal to my_foods, we would not produce two separate lists. For example, here’s what happens when you try to copy a list without using a slice:
Instead of storing a copy of my_foods in friend_foods at ➊, we set friend_foods equal to my_foods. This syntax actually tells Python to connect the new variable friend_foods to the list that is already contained in my_foods, so now both variables point to the same list.
A tuple looks just like a list except you use parentheses instead of square brackets.
Although you can’t modify a tuple, you can assign a new value to a variable that holds a tuple. So if we wanted to change our dimensions, we could redefine the entire tuple:
One of the oldest PEPs is PEP 8, which instructs Python programmers on how to style their code. PEP 8 is fairly lengthy, but much of it relates to more complex coding structures than what you’ve seen so far.
Testing for equality is case sensitive in Python.
When someone submits a new username, that new username is converted to lowercase and compared to the lowercase versions of all existing usernames. During this check, a username like 'John' will be rejected if any variation of 'john' is already in use.
We start by defining the same dictionary that we’ve been working with. We then print this dictionary, displaying a snapshot of its information. At ➊ we add a new key-value pair to the dictionary: key 'x_position' and value 0. We do the same for key 'y_position' at ➋. When we print the modified dictionary, we see the two additional key-value pairs:
Typically, you’ll use empty dictionaries when storing user-supplied data in a dictionary or when you write code that generates a large number of key-value pairs automatically.
The game is controlled by a while loop ➌ that contains an event loop and code that manages screen updates. An event is an action that the user performs while playing the game, such as pressing a key or moving the mouse. To make our program respond to events, we’ll write an event loop to listen for an event and perform an appropriate task depending on the kind of event that occurred. The for loop at ➍ is an event loop.
sys.exit() to exit the game ➎. The call to pygame.display.flip() at ➏ tells Pygame to make the most recently drawn screen visible. In this case it draws an empty screen each time through the while loop to erase the old screen so that only the new screen is visible. When we move the game elements around, pygame.display.flip() will continually update the display to show the new positions of elements and hide the old ones, creating the illusion of smooth movement.
Each time we introduce new functionality into our game, we’ll typically introduce some new settings as well. Instead of adding settings throughout the code, let’s write a module called settings that contains a class called Settings to store all the settings in one place. This approach allows us to pass around one settings object instead of many individual settings.
In addition, it makes our function calls simpler and makes it easier to modify the game’s appearance as our project grows. To modify the game, we’ll simply change some values in settings.py instead of searching for different settings throughout our files.
Sometimes it’s useful to be able to plot and style individual points based on certain characteristics. For example, you might plot small values in one color and larger values in a different color. You could also plot a large data set with one set of styling options and
To remove the outlines around points, pass the argument edgecolor='none' when you call scatter():
To change the color of the points, pass c to scatter() with the name of a color to use, as shown here:
A colormap is a series of colors in a gradient that moves from a starting to ending color. Colormaps are used in visualizations to emphasize a pattern in the data.
Rolling Dice of Different Sizes
DOWNLOADING DATA
Many data sets you work with will have missing data, improperly formatted data, or incorrect data. Use the tools you learned in the first half of this book to deal with these situations. Here we used a try-except-else block to handle missing data. Sometimes you’ll use continue to skip over some data or use remove() or del to eliminate some data after it’s been extracted.
This data comes from one of the many data sets that the Open Knowledge Foundation (http://data.okfn.org/) makes freely available.
The file is basically one long Python list. Each item is a dictionary with four keys: a
The json.load() function converts the data into a format Python can work with: in this case, a list.
It’s often the case that raw data isn’t formatted consistently, so we come across errors a lot. Here the error occurs because Python can’t directly turn a string that contains a decimal, '1127437398.85751', into an integer
We address this error by converting the string to a float and then converting that float to an integer:
Before we can focus on mapping, we need to address one last aspect of the data. The mapping tool in Pygal expects data in a particular format: countries need to be provided as country codes and populations as values. Several standardized sets of country codes are frequently used when working with geopolitical data; the codes included in population_data.json are three-letter codes, but Pygal uses two-letter codes. We need a way to find the two-digit code from the country name.
Pygal’s country codes are stored in a module called i18n, short for internationalization. The dictionary COUNTRIES contains the two-letter country codes as keys and the country names as values. To see these codes, import the dictionary from the i18n module and print its keys and values:
This is replaced by pygal.maps.world import COUNTRIES
http://pygal.org/en/stable/documentation/types/maps/pygal_maps_world.html
Each call to add() sets up a new color for the set of countries and adds that color to a key on the left of the graph with the label specified here.
Pygal styles are stored in the style module from which we import the style RotateStyle ➊. This class takes one argument, an RGB color in hex format ➋. Pygal then chooses colors for each of the groups based on the color provided. The hex format is a string with a hash mark (#) followed by six characters: the first two represent the red component of the color, the next two represent the green component, and the last two represent the blue component. The component values can range from 00 (none of that color) to FF (maximum amount of that color). If you search online for hex color chooser, you
...more
A web API is a part of a website designed to interact with programs that use very specific URLs to request certain information. This kind of request is called an API call. The requested data will be returned in an easily processed format, such as JSON or CSV. Most apps that rely on external data sources, such as apps that integrate with social media sites, rely on API calls.
The API returns the information in JSON format, so we use the json() method ➎ to convert the information to a Python dictionary. We store the resulting dictionary in response_dict
At ➋ we make an instance of Pygal’s Config class, called my_config; modifying the attributes of my_config will customize the appearance of the chart.
Now when we make an instance of Bar at ➐, we pass my_config as the first argument, and it sends all of our configuration settings in one argument. We can make as many style and configuration changes as we want through my_config, and the line at ➐ won’t change.
Pygal uses the URL associated with 'xlink' to turn each bar into an active link. You can click any of the bars in the chart, and the GitHub page for that project will automatically open in a new tab in your browser.
Separating one project’s libraries from other projects is beneficial and will be necessary when we deploy Learning Log to a server in Chapter 20.
Any time we modify a database, we say we’re migrating the database. Issuing the migrate command for the first time tells Django to make sure the database matches the current state of the project. The first time we run this command in a new project using SQLite (more about SQLite in a moment), Django will create a new database for us. At ➊ Django reports that it will make the database tables needed to store the information we’ll use in this project (Synchronize unmigrated apps), and then make sure the database structure matches the current code (Apply all migrations).
A Django project is organized as a group of individual apps that work together to make the project work as a whole. For now, we’ll create just one app to do most of the work for our project. We’ll add another app to manage user accounts in Chapter 19
The command startapp appname tells Django to create the infrastructure needed to build an app. If you look in the project directory now, you’ll see a new folder called learning_logs ➊
A model tells Django how to work with the data that will be stored in the app. Code-wise, a model is just a class; it has attributes and methods, just like every class we’ve discussed.

