The book “Learning Python: game programming, data visualization, web applications. 3rd ed.

image Hi, habrozhiteli! We released the third version # 1 Best Seller in Python Programming Amazon – A popular Python guide in the world.

You can not only learn it as quickly as possible, but also learn how to write programs, fix errors and create working applications. In the first part of the book, you will be introduced to basic programming concepts such as variables, lists, classes, and loops, and simple exercises will teach you how to use clean code templates. You will learn how to make programs interactive and how to test code before adding to a project.

In the second part, you will put the new knowledge into practice and create three projects: an arcade game in the style of Space Invaders, data visualization with convenient Python libraries and a simple web application that can be quickly deployed online. When working with a book, you will learn: ∙ Use powerful libraries and Python tools: Pygame, Matplotlib, Plotly, and Django ∙ Create 2D games of varying complexity that can be controlled with the keyboard and mouse ∙ Create interactive data visualization ∙ Design, configure and deploy web applications ∙ Deal with bugs and errors

The new edition has been carefully revised and reflects the latest advances in Python programming practices. The first part of the book was supplemented with new information on f-lines, constants, and data management. In the second part, the project code was updated. The project structure and code have become cleaner and more understandable, now they use the full power of popular libraries and tools, such as Plotly and Django.

The following is a summary of the changes in the third edition:

In Chapter 1, Python installation instructions were simplified for users of all major operating systems. Now I recommend using the Sublime Text text editor, which is popular among both beginners and professionals, and works on all operating systems.

Chapter 2 provides a more detailed description of how variables are implemented in Python. Variables are described as text labels for values, which allows the reader to better understand the behavior of variables in Python. The book makes extensive use of the f-lines introduced in Python 3.6, a much simpler and more convenient mechanism for using values ​​in strings. Python 3.6 also introduced the ability to use underscores to represent large numbers (for example, 1_000_000); she is also included in this edition. Multiple assignment of variables was presented in one of the projects of the first edition; the description has been compiled and moved to chapter 2 for the convenience of readers. Finally, an understandable convention system for representing constants in Python is also included in this chapter.

Chapter 6 introduces the get () method for reading values ​​from a dictionary, which can return the default value if there is no key.

The Alien Invasion project (chapters 12–14) is now fully based on the use of classes. The game itself is a class (instead of a series of functions, as in the previous edition). This greatly simplifies the overall structure of the game, reduces the number of function calls and necessary parameters. Readers familiar with the first edition will appreciate the simplicity of the new class-based approach. Pygame can now be installed with a single-line command in all systems, and the reader can choose between starting the game in full screen or window mode.

In data visualization projects, the installation instructions for Matplotlib have been simplified for all operating systems. Matplotlib-based visualizations use the subplots () function, which is more convenient for learning how to build complex visualizations. The Rolling Dice project from Chapter 15 uses Plotly, a visualization library with simple syntax, high-quality maintenance, and beautiful output with rich customization options.

In chapter 16, the meteorological project was translated into NOAA data, which demonstrated greater stability over the years than the site used in the first edition. The mapping project is now dedicated to global seismic activity; by the time the project is completed, a magnificent visualization will be built, visually depicting the boundaries of tectonic plates along the coordinates of all earthquakes for a given period of time. You will learn how to map any datasets containing geographic coordinates.

Chapter 17 uses the Plotly library to visualize Python-related activity in open source projects on GitHub.

The Learning Log project (chapters 18–20) is built on the latest version of Django, and the latest version of Bootstrap is used to design it. The project deployment process in Heroku has been simplified by using the django-heroku package, and it uses environment variables instead of editing files. This solution is simpler and better suited to how professional programmers deploy modern Django projects.

Appendix A has been completely redesigned. It included recommendations for installing Python. Appendix B includes detailed recommendations for setting up Sublime Text and provides brief descriptions of the main text editors and integrated environments used today. Appendix B provides links to newer and more popular online resources for help, and Appendix D offers a short tutorial on using Git for version control.

We understand that it is surprising to many that we have released the third edition of the book, and the original book 2ed. The reason for this incident is simple. Six months after the release of the first edition in Russian, the author made significant but minor changes to the book, corrected many codes. After looking at the number of changes, we decided to name the new book “Second Edition”. So the second Russian-language publication was released on May 30, 2017.

And now the 2nd international edition had to be released as
“Learning Python: game programming, data visualization, web applications. 3rd ed.

Excerpt. Dictionaries

Sometimes it is necessary to save many dictionaries in a list or save a list as the value of a dictionary element. Creating complex structures of this kind is called embedding. You can embed multiple dictionaries into a list, a list of items in a dictionary, or even a dictionary inside another dictionary. As the following examples demonstrate, attachment is an extremely powerful mechanism.

List of dictionaries

The alien_0 dictionary contains a variety of information about one alien, but there is no place to store information about the second alien, not to mention the whole screen clogged by aliens. How to simulate an invasion fleet? For example, you can create a list of aliens in which each element is a dictionary with information about an alien. For example, the following code builds a list of three aliens:
   alien_0 = {'color': 'green', 'points': 5}
   alien_1 = {'color': 'yellow', 'points': 10}
   alien_2 = {'color': 'red', 'points': 15}
❶ aliens = [alien_0, alien_1, alien_2]
   for alien in aliens:

First, three dictionaries are created, each of which represents a separate alien. At point ❶, each dictionary is listed with the name aliens. Finally, the program loops through the list and displays each alien:

{'color': 'green', 'points': 5}
{'color': 'yellow', 'points': 10}
{'color': 'red', 'points': 15}

Of course, in a realistic example, more than three aliens will be used, which will be generated automatically. In the following example, the range () function creates a fleet of 30 aliens:

# Создание пустого списка для хранения пришельцев.
aliens = []

# Создание 30 зеленых пришельцев.
❶ for alien_number in range(30):
❷      new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
❸      aliens.append(new_alien)

   # Вывод первых 5 пришельцев:
❹ for alien in aliens[:5]:
   # Вывод количества созданных пришельцев.
❺ print(f"Total number of aliens: {len(aliens)}")

At the beginning of the example, the list for storing all the aliens that will be created is empty. At point ❶, the range () function returns a set of numbers, which simply tells Python how many times the loop should repeat. Each time the cycle is completed, a new alien ❷ is created, which is then added to the aliens ❸ list. At point ❹, the segment is used to display the first five aliens, and at point ❺ the length of the list is displayed (to demonstrate that the program really generated the entire fleet of 30 aliens):

{'speed': 'slow', 'color': 'green', 'points': 5}
{'speed': 'slow', 'color': 'green', 'points': 5}
{'speed': 'slow', 'color': 'green', 'points': 5}
{'speed': 'slow', 'color': 'green', 'points': 5}
{'speed': 'slow', 'color': 'green', 'points': 5}

Total number of aliens: 30

All aliens have the same characteristics, but Python treats each alien as a separate object, which allows you to change the attributes of each owner individually.

How to work with so many? Imagine that in this game some aliens change color and begin to move faster. When it comes time to change colors, we can use the for loop and if command to change the color. For example, to turn the first three aliens into yellow, moving at medium speed and bringing the player 10 points each, you can do this:

# Создание пустого списка для хранения пришельцев.
aliens = []

# Создание 30 зеленых пришельцев.
for alien_number in range (0,30):
     new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}

for alien in aliens[0:3]:
     if alien['color'] == 'green':
         alien['color'] = 'yellow'
         alien['speed'] = 'medium'
         alien['points'] = 10

# Вывод первых 5 пришельцев:
for alien in aliens[0:5]:

To change the first three aliens, we iterate over the elements of a segment that includes only the first three aliens. At the moment, all aliens are green (‘green’), but this will not always be the case, so we write an if command, which ensures that only green aliens will change. If the alien is green, then his color changes to yellow (‘yellow’), speed to medium (‘medium’), and the reward increases to 10 points:

{'speed': 'medium', 'color': 'yellow', 'points': 10}
{'speed': 'medium', 'color': 'yellow', 'points': 10}
{'speed': 'medium', 'color': 'yellow', 'points': 10}
{'speed': 'slow', 'color': 'green', 'points': 5}
{'speed': 'slow', 'color': 'green', 'points': 5}

The cycle can be expanded by adding an elif block to turn yellow aliens into red ones – fast and bringing the player 15 points each. We will not cite all the code, and the loop looks like this:

for alien in aliens[0:3]:
     if alien['color'] == 'green':
         alien['color'] = 'yellow'
         alien['speed'] = 'medium'
         alien['points'] = 10
    elif alien['color'] == 'yellow':
        alien['color'] = 'red'
        alien['speed'] = 'fast'
        alien['points'] = 15

A solution with storing dictionaries in a list is quite common when each dictionary contains different attributes of one object. For example, you can create a dictionary for each user of the site, as was done in the program on p. 114, and save the individual dictionaries in a list named users. All dictionaries in the list must have the same structure so that you can iterate over the list and perform the same operations with each dictionary object.

Dictionary List

Instead of putting a dictionary in a list, it is sometimes convenient to put a list in a dictionary. Imagine how you would describe the ordered pizza in the program. If we restrict ourselves only to the list, only the list of toppings for pizza can be saved. When using a dictionary, the topping list can be just one aspect of the pizza description.

In the following example, two types of information are stored for each pizza: base and topping list. The topping list is the value associated with the ‘toppings’ key. To use elements in the list, you must specify the dictionary name and the key ‘toppings’, as for any other value in the dictionary. Instead of a single value, a list of toppings will be obtained:
   # Сохранение информации о заказанной пицце.
❶ pizza = {
         'crust': 'thick',
         'toppings': ['mushrooms', 'extra cheese'],

   # Описание заказа.
❷ print(f"You ordered a {pizza['crust']}-crust pizza "
        "with the following toppings:")

❸ for topping in pizza['toppings']:
print("t" + topping)

Work starts at point ❶ with a dictionary with information about the ordered pizza. The string value ‘thick’ is associated with a key in the ‘crust’ dictionary. Another key ‘toppings’ has a list value that stores all ordered toppings. At point ❷, a description of the order is displayed before creating the pizza. If you need to split a long line in a print () call, select a point to split the output line and end the line with a quote. Indent the next line, add an opening quotation mark, and continue with the line. Python automatically concatenates all strings found in parentheses. For the conclusion of additions, a for ❸ loop is written. To list the toppings, we use the ‘toppings’ key, and Python takes the list of toppings from the dictionary.

The following message describes the pizza we are about to create:

You ordered a thick-crust pizza with the following toppings:
      extra cheese

Nesting a list in a dictionary can be used every time more than one value must be associated with one dictionary key. If answers were saved in the list in the previous example with programming languages, one participant in the survey could select several favorite languages ​​at once. When enumerating a dictionary, the value associated with each person would be a list of languages ​​(instead of one language). In the for loop of the dictionary, another loop is created to iterate over the list of languages ​​associated with each participant:
❶ favorite_languages = {
          'jen': ['python', 'ruby'],
          'sarah': ['c'],
          'edward': ['ruby', 'go'],
          'phil': ['python', 'haskell'],

❷ for name, languages in favorite_languages.items():
        print(f"n{name.title()}'s favorite languages are:")
❸      for language in languages:

You see at point ❶ that the value associated with each name is now a list. Some participants have one favorite programming language, while others have several. When iterating over a dictionary at point ❷, a variable named languages ​​is used to store each value from the dictionary, because we know that each value will be a list. In the main cycle, according to the elements of the dictionary, another cycle ❸ iterates over the elements of the list of favorite languages ​​of each participant. Now, each survey participant can specify as many favorite programming languages ​​as they like:

Jen's favorite languages are:

Sarah's favorite languages are:

Phil's favorite languages are:

Edward's favorite languages are:

To further improve the program, include an if command at the beginning of the for loop of the dictionary to check whether the participant has selected more than one programming language (the check is based on the value of len (languages)). If the participant has only one favorite language, the message text is changed for the singular (for example, “Sarah’s favorite language is C”).

»More details on the book can be found at publishing site

Table of contents


For Khabrozhiteley a 25% discount on the coupon – Python

Upon payment of the paper version of the book, an electronic book is sent by e-mail.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *