0% found this document useful (0 votes)
71 views168 pages

Sanet - ST B0CZ4JHLCY

Uploaded by

koranbase
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
71 views168 pages

Sanet - ST B0CZ4JHLCY

Uploaded by

koranbase
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 168

Python Programming

Made Simple
Learn Progressively with Self-Contained Code

⋄⋄⋄

Christina Daniel, Ph.D.


ii

Copyright © 2024 by Christina Daniel

The content contained within this book may not be reproduced, duplicated
or transmitted without direct written permission from the author or the pub-
lisher. Under no circumstances will any blame or legal responsibility be held
against the publisher, or author, for any damages, reparation, or monetary
loss due to the information contained within this book.

Disclaimer Notice:

Please note the information contained within this document is for educational
and entertainment purposes only. All effort has been executed to present
accurate, up to date, and reliable, complete information. No warranties of
any kind are declared or implied. Readers acknowledge that the author isn’t
engaging in the rendering of legal, financial, medical or professional advice.
The content within this book has been derived from various sources. Please
consult a licensed professional before attempting any techniques outlined in
this book.

By reading this document, the reader agrees that under no circumstances is


the author responsible for any losses, direct or indirect, which are incurred as
a result of the use of information contained within this document, including,
but not limited to, – errors, omissions, or inaccuracies.

Legal Notice:

This book is copyright protected. This book is only for personal use. You
can’t amend, distribute, sell, use, quote or paraphrase any part, or the content
within this book, without the consent of the author or publisher.

Trademark Notice:

“Python” and the Python Logo are trademarks of the Python Software Foun-
dation.
Contents

1 Introduction 1

I The Basics of Python 3

2 How to Run Python Code 5


2.1 What Is a Shell? . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2 Opening a Shell . . . . . . . . . . . . . . . . . . . . . . . . . . 5
2.2.1 Mac . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.2.2 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3 Managing Software . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3.1 Mac . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.3.2 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2.4 Is Python Installed? . . . . . . . . . . . . . . . . . . . . . . . 8
2.5 Uninstalling Python . . . . . . . . . . . . . . . . . . . . . . . 8
2.5.1 Mac . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
2.5.2 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.6 Installing Python 3.12 . . . . . . . . . . . . . . . . . . . . . . 9
2.6.1 Mac . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.6.2 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.7 Using the Python Interpreter . . . . . . . . . . . . . . . . . . 10
2.8 How to Use Visual Studio . . . . . . . . . . . . . . . . . . . . 11
2.8.1 Install Visual Studio . . . . . . . . . . . . . . . . . . . 11
2.8.2 Make a Folder . . . . . . . . . . . . . . . . . . . . . . . 12
iv CONTENTS

2.8.3 Put a Python File in the Folder . . . . . . . . . . . . . 12


2.8.4 Run the Python File . . . . . . . . . . . . . . . . . . . 13

3 Data and Variables 15


3.1 What Is Data? . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.2 What Is a Data Type? . . . . . . . . . . . . . . . . . . . . . . 15
3.2.1 Integer . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.2.2 Float . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.2.3 Complex . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.2.4 String . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
3.2.5 Boolean . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.2.6 NoneType . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.3 What Is a Variable? . . . . . . . . . . . . . . . . . . . . . . . . 20
3.3.1 Storing Data with a Variable . . . . . . . . . . . . . . . 20

4 Operations 21
4.1 Arithmetic Operations . . . . . . . . . . . . . . . . . . . . . . 21
4.1.1 Addition . . . . . . . . . . . . . . . . . . . . . . . . . . 21
4.1.2 Subtraction . . . . . . . . . . . . . . . . . . . . . . . . 22
4.1.3 Multiplication . . . . . . . . . . . . . . . . . . . . . . . 23
4.1.4 Division . . . . . . . . . . . . . . . . . . . . . . . . . . 24
4.1.5 Modulus . . . . . . . . . . . . . . . . . . . . . . . . . . 25
4.1.6 Exponentiation . . . . . . . . . . . . . . . . . . . . . . 26
4.2 String Operations . . . . . . . . . . . . . . . . . . . . . . . . . 26
4.2.1 Concatenating Strings . . . . . . . . . . . . . . . . . . 27
4.2.2 Indexing a String . . . . . . . . . . . . . . . . . . . . . 27
4.2.3 Finding the Length of a String . . . . . . . . . . . . . . 28
4.2.4 Slicing a String . . . . . . . . . . . . . . . . . . . . . . 29

5 Control Flow 31
5.1 Comparison Operators . . . . . . . . . . . . . . . . . . . . . . 31
5.1.1 Equal To . . . . . . . . . . . . . . . . . . . . . . . . . . 31
5.1.2 Not Equal To . . . . . . . . . . . . . . . . . . . . . . . 32
CONTENTS v

5.1.3 Greater Than . . . . . . . . . . . . . . . . . . . . . . . 32


5.1.4 Greater Than or Equal To . . . . . . . . . . . . . . . . 33
5.1.5 Less Than . . . . . . . . . . . . . . . . . . . . . . . . . 33
5.1.6 Less Than or Equal To . . . . . . . . . . . . . . . . . . 34
5.2 Logical Operators . . . . . . . . . . . . . . . . . . . . . . . . . 35
5.2.1 Logical Not . . . . . . . . . . . . . . . . . . . . . . . . 35
5.2.2 Logical Or . . . . . . . . . . . . . . . . . . . . . . . . . 37
5.2.3 Logical And . . . . . . . . . . . . . . . . . . . . . . . . 37
5.3 Conditional Statements . . . . . . . . . . . . . . . . . . . . . . 38
5.3.1 If Statement . . . . . . . . . . . . . . . . . . . . . . . . 38
5.3.2 If. . . Else Statement . . . . . . . . . . . . . . . . . . . . 39
5.3.3 If. . . Elif. . . Else Statement . . . . . . . . . . . . . . . . 39
5.4 Loops . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
5.4.1 While Loop . . . . . . . . . . . . . . . . . . . . . . . . 40
5.4.2 For Loop . . . . . . . . . . . . . . . . . . . . . . . . . . 41

6 Data Structures 43
6.1 Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
6.2 Tuples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
6.3 Dictionaries . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

7 Functions 49
7.1 Writing a Function . . . . . . . . . . . . . . . . . . . . . . . . 49
7.1.1 Naming a Function . . . . . . . . . . . . . . . . . . . . 49
7.1.2 Implementing a Function . . . . . . . . . . . . . . . . . 49
7.2 Built-In Functions . . . . . . . . . . . . . . . . . . . . . . . . 51
7.2.1 Input and Output . . . . . . . . . . . . . . . . . . . . . 51

8 Object-Oriented Programming 53
8.1 Writing a Class . . . . . . . . . . . . . . . . . . . . . . . . . . 53
8.1.1 Defining Attributes . . . . . . . . . . . . . . . . . . . . 53
8.1.2 Defining Methods . . . . . . . . . . . . . . . . . . . . . 54
8.2 Using a Class . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
vi CONTENTS

8.2.1 What Is an Instance? . . . . . . . . . . . . . . . . . . . 55


8.2.2 Creating an Instance . . . . . . . . . . . . . . . . . . . 55
8.2.3 Accessing Data with an Attribute . . . . . . . . . . . . 57
8.2.4 Modifying Data with an Attribute . . . . . . . . . . . . 58
8.2.5 A Convention for Attributes . . . . . . . . . . . . . . . 59
8.2.6 Calling a Method . . . . . . . . . . . . . . . . . . . . . 61
8.3 Design Tip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
8.4 Built-In Classes . . . . . . . . . . . . . . . . . . . . . . . . . . 63

9 Inheritance 65
9.1 Inheritance of Attributes . . . . . . . . . . . . . . . . . . . . . 65
9.1.1 Inheriting an Attribute . . . . . . . . . . . . . . . . . . 65
9.1.2 Customizing Data Stored with an Attribute . . . . . . 66
9.1.3 Adding an Attribute . . . . . . . . . . . . . . . . . . . 67
9.2 Inheritance of Methods . . . . . . . . . . . . . . . . . . . . . . 68
9.2.1 Inheriting the init Method . . . . . . . . . . . . . . 68
9.2.2 Customizing the init Method . . . . . . . . . . . . . 69
9.2.3 Inheriting a Method . . . . . . . . . . . . . . . . . . . 71
9.2.4 Customizing a Method . . . . . . . . . . . . . . . . . . 71
9.2.5 Adding a Method . . . . . . . . . . . . . . . . . . . . . 72

10 Modules and Libraries 75


10.1 What Is a Module? . . . . . . . . . . . . . . . . . . . . . . . . 75
10.2 What Is a Library? . . . . . . . . . . . . . . . . . . . . . . . . 75
10.3 What’s pip? . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
10.3.1 Is pip Installed? . . . . . . . . . . . . . . . . . . . . . . 76
10.3.2 Installing pip . . . . . . . . . . . . . . . . . . . . . . . 76
10.4 Virtual Environments . . . . . . . . . . . . . . . . . . . . . . . 76
10.4.1 What Is a Virtual Environment? . . . . . . . . . . . . 76
10.4.2 How to Make a Virtual Environment . . . . . . . . . . 77
10.4.3 Activating a Virtual Environment . . . . . . . . . . . . 78
10.4.4 Viewing Software in a Virtual Environment . . . . . . 78
CONTENTS vii

10.4.5 Deactivating a Virtual Environment . . . . . . . . . . . 79


10.4.6 Removing a Virtual Environment . . . . . . . . . . . . 79
10.5 Installing Python Code . . . . . . . . . . . . . . . . . . . . . . 79
10.6 Importing Python Code . . . . . . . . . . . . . . . . . . . . . 80
10.6.1 Importing a Module . . . . . . . . . . . . . . . . . . . 80
10.6.2 Importing a Library . . . . . . . . . . . . . . . . . . . 83

II Make a Game 85

11 Start a Project 87
11.1 Make a Folder . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
11.2 Display a Path . . . . . . . . . . . . . . . . . . . . . . . . . . 88
11.2.1 Mac . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
11.2.2 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . 88
11.3 Change the Working Directory . . . . . . . . . . . . . . . . . . 88
11.4 Install a Python Library . . . . . . . . . . . . . . . . . . . . . 89

12 Create a Window 91
12.1 Download Images and Sounds . . . . . . . . . . . . . . . . . . 93
12.2 Load Images and Sounds . . . . . . . . . . . . . . . . . . . . . 93
12.3 Add Images to the Game . . . . . . . . . . . . . . . . . . . . . 95

13 Write Classes 99
13.1 The Image Class . . . . . . . . . . . . . . . . . . . . . . . . . 99
13.2 The GameObject Class . . . . . . . . . . . . . . . . . . . . . . 104
13.3 The Rocket Class . . . . . . . . . . . . . . . . . . . . . . . . . 107
13.4 The Asteroid Class . . . . . . . . . . . . . . . . . . . . . . . . 108
13.5 The Button Class . . . . . . . . . . . . . . . . . . . . . . . . . 109

14 Fill in the Gaps 115


14.1 Add Four Global Variables . . . . . . . . . . . . . . . . . . . . 115
14.2 Add Three Functions . . . . . . . . . . . . . . . . . . . . . . . 117
14.2.1 Start . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
viii CONTENTS

14.2.2 Pause . . . . . . . . . . . . . . . . . . . . . . . . . . . 119


14.2.3 Create an Asteroid . . . . . . . . . . . . . . . . . . . . 121
14.3 Add One Method . . . . . . . . . . . . . . . . . . . . . . . . . 123
14.4 Add Four Functions . . . . . . . . . . . . . . . . . . . . . . . . 125
14.4.1 Handling a Collision . . . . . . . . . . . . . . . . . . . 125
14.4.2 Losing the Game . . . . . . . . . . . . . . . . . . . . . 127
14.4.3 Increasing the Score . . . . . . . . . . . . . . . . . . . 129
14.4.4 Winning the Game . . . . . . . . . . . . . . . . . . . . 131

15 Complete the Project 135


15.1 Update app.py . . . . . . . . . . . . . . . . . . . . . . . . . . 135
15.2 Final Version of app.py . . . . . . . . . . . . . . . . . . . . . . 142

16 Conclusion 147

17 Bibliography 149

18 Index 157
Chapter 1

Introduction

What do Spotify, Instagram, and YouTube have in common? Each of these


applications uses Python to a certain extent. As you can see, the Python
language is helpful in various contexts, including music streaming, social net-
working, and video sharing.
You may be new to programming, preparing for a job interview, or work-
ing on a project. Without the right resources, coding can be a challenging
experience. No one likes to spend hours or even days looking for an error that
could have been easily avoided.
This book is designed to help you master the foundations of Python pro-
gramming. You can check your understanding of important topics such as
data types, control flow, functions, and object-oriented programming. In the
last few chapters, you will find a tutorial for creating a game. You can use
this tutorial to apply what you learned in previous chapters.
A little about me: In 2023, I graduated from Georgetown University with a
Ph.D. in physics. While working on my research, I heavily relied on Python to
perform calculations that would be impossible–or ridiculously tedious–without
a computer. I wrote code to analyze systems of particles that obeyed physical
laws. This research required me to have a solid understanding of computer
programming.
One of Python’s main advantages is that anyone with internet access can
easily reuse high-quality code that other organizations wrote. In programming,
reusable code is called a library, and there are Python libraries for scientific
work, data science, and web development.
I wrote this book to share what I know about Python in the simplest way
possible so that others can learn effectively. The topics in this book were
2 Introduction

extensively researched and tested. However, you are encouraged to verify


claims by running code and examining output.
But how do you run code, particularly Python code? The next chapter an-
swers this question and guides you through downloading the Python language
and other software.
Part I

The Basics of Python


Chapter 2

How to Run Python Code

In this chapter, you will get set up for coding in Python. First, you will learn
what a shell is. Then, you will use a shell to see if Python is installed on
your computer. After that, you can uninstall and install specific versions of
Python. Once you have a version of Python installed, you will learn how to
run Python code.

2.1 What Is a Shell?

A shell is a window where you can run a command. The exact appearance of
a shell varies from one computer to another. Still, Figure 2.1 can give you a
good idea of what a shell looks like. You can run a command with a shell by
typing the command in the window and pressing the Enter key.
You do need to be careful when using a shell; typing nonsense and carelessly
running commands is not recommended. In this book, you will use a shell to
run basic, well-tested commands.

2.2 Opening a Shell

The process for opening a shell depends on the type of computer that you are
using.
6 How to Run Python Code

Figure 2.1: A graphical representation of a shell.

2.2.1 Mac
If you are using a Mac, the shell is usually called a terminal. To open a
terminal, click on the small magnifying glass in the upper right corner of your
screen. Then, type “terminal” in the search field and select the application
named Terminal that appears.

2.2.2 Windows
On a Windows computer, there are two shells–the Command Prompt is one of
them. In this book, sometimes there are instructions for Windows users. These
instructions are for the Command Prompt. To open a Command Prompt, click
on the Windows icon, type the words “Command Prompt” in the search field,
and click on the displayed application.

2.3 Managing Software


Python is software, and you must install it before using it. But how do you in-
stall software? This section is about managing software on Mac and Windows
computers.
2.3 Managing Software 7

2.3.1 Mac
Homebrew provides a way to manage software on a Mac. If you are using a
Mac, you should install homebrew. Soon, you will use homebrew to install
Python!
So, how do you install homebrew? You may be surprised to learn that it
involves multiple steps.
First, open a terminal. Then, type the following command in the terminal.

xcode - select -- install

To run this command in the terminal, press the Enter key on the keyboard.
When you run this command, your computer will install tools for software
development.
After that, go to this website: brew.sh
While visiting that website, copy the command under the heading “Install
Homebrew.” The command that you should copy is a long line of text.
Once you have copied that line, use Command-V on your keyboard to paste
the line into the terminal.
Finally, run the command. Now you are installing homebrew! Follow the
prompts as needed.
After the homebrew installation is complete, locate the “Next steps” sec-
tion that appeared in the terminal. If you read that section, you will realize
that there are two more commands to run. Follow those instructions.
After that, homebrew should be ready to use. To be sure, open a new
terminal and run this command.

brew update

If, after running this command, you do not see an error in the terminal,
you have successfully installed homebrew.

2.3.2 Windows
You do not need to install anything because you can manage the installation
and uninstallation of software with the Control Panel.
8 How to Run Python Code

2.4 Is Python Installed?


You can find out if Python is installed on your computer by looking for an
existing version of Python. On Windows and Mac computers, checking the
version of Python involves typing a command in a shell. In particular, you
can run the following command in the shell.

python -- version

One of two things will happen after typing this command and pressing
enter. The first is that you will see the version of Python that is installed on
your computer. In this case, Python is already on your computer, and the
version shown in the shell is the version that is installed. The second option
is that you will see an error message similar to “python is not recognized” or
“command not found.”

2.5 Uninstalling Python


You may wish to uninstall a specific version of Python at some point. This
section is optional.

2.5.1 Mac
Suppose you want to uninstall Python 3.9. To do this, run the following
command in the terminal.

brew uninstall python@3 .9

This command can uninstall different versions of Python–you just need to


specify the version. For example, you would run the following command to
uninstall Python 3.8 instead of Python 3.9.

brew uninstall python@3 .8

That’s all you need to do to uninstall a version of Python.


2.6 Installing Python 3.12 9

2.5.2 Windows
If you are using a Windows computer, you can uninstall a specific version of
Python with the Control Panel. If you are using Windows 10, you can uninstall
software by navigating to the Control Panel, selecting Programs, and clicking
Programs and Features. You should see a search field. Type “python” in this
field to see the Python programs that are currently installed on your computer.
To uninstall a program related to Python, select the program and press the
“uninstall” button.

2.6 Installing Python 3.12


This book uses Python 3.12. Here is how to install it.

2.6.1 Mac
On a Mac, run this command in the terminal.

brew install python@3 .12

That’s it! If you see an error, refer to the previous section about installing
homebrew.

2.6.2 Windows
To install Python 3.12 on a Windows computer, go to this website:

https://www.python.org/

Once you have visited Python’s official website, click the “Downloads” tab.
You should see a button to download the latest version of Python for Windows.
At the time of writing, Python 3.12 is the newest version. If this is the case
for you, click the button. Otherwise, you can search Python’s website for a
way to download version 3.12 of Python; most likely, you can scroll down on
the web page that you are currently viewing.
After downloading Python 3.12, click on what was downloaded and press
“run.” A window for installing Python should appear. Towards the bottom of
10 How to Run Python Code

this window, there is a checkbox for adding Python to the PATH. Be sure to
check this box. Then, follow the prompts to complete the installation. That’s
it!

2.7 Using the Python Interpreter


Now that you have installed Python, you can use the interpreter, which inter-
prets code one line at a time. To start the interpreter for Python 3.12, run
this command in a shell.

python3 .12

You should see three greater-than signs.

>>>

You have started the interpreter, which allows you to run Python code one
line at a time.
As a first example, go ahead and type the following Python code.

>>> print ( " Hello World ! " )

Then press Enter. You just ran one line of Python code, and you should
see the following output.

Hello World !

The Python code that you ran caused text to appear. To exit the inter-
preter, type exit() and press the Enter key.

>>> exit ()
2.8 How to Use Visual Studio 11

2.8 How to Use Visual Studio


If you anticipate writing several lines of code, you should use an Integrated
Development Environment (IDE). One of the best IDEs is Visual Studio.

Figure 2.2: A snapshot of Visual Studio.

2.8.1 Install Visual Studio


To download Visual Studio, go to the following website.

https://visualstudio.microsoft.com/downloads/

The remaining steps depend on whether you use a Mac or a Windows


computer.
12 How to Run Python Code

Mac

Scroll to the section that mentions macOS. Then, hover over the “Free down-
load” button. When a drop-down menu appears, select “macOS Universal
Package.” An application will automatically start downloading. After a few
seconds, double-click on the application to launch the Visual Studio installer.
Before pressing “Install,” check the “.NET Core” box. Now, you just need to
wait for the installation to complete.

Windows

In the “Community” section for Windows, click the “Free download” button.
A file should start downloading. Next, click on the downloaded file and follow
the instructions from the installer. Eventually, you will need to choose from
various “Workloads.” At this point, select “.NET desktop development.” Then,
press “Install.” When the installation is complete, press “Launch” to start
using Visual Studio.

2.8.2 Make a Folder


Putting a folder on your Desktop is a common way to start a project. For this
tutorial, create a folder called my project and save the folder on your Desktop.
Then, use Visual Studio to open the folder that you created. You should see
the folder’s name in the side bar on the left.

2.8.3 Put a Python File in the Folder


After following the instructions in the previous section called “Creating a
Folder,” use Visual Studio to make a file called hello world.py–be sure to use
the extension .py so that you are making a Python file. In the side bar on the
left, you should see a Python file within the folder called my project. You can
put Python code in this file.
For this tutorial, type the following code in the empty file after clicking
hello world.py in the side bar.

print ( " Hello World ! " )


2.8 How to Use Visual Studio 13

Now, you have a file with Python code. Remember to save the file! If you
are not using the Python interpreter, you must save the code before running
it.

2.8.4 Run the Python File


There are two ways to run a Python file. The first way is project-oriented,
whereas the second is straightforward.

Method 1

First, run the following command in a shell. Note that Visual Studio has a
built-in shell.

cd Desktop

Next, run a similar command.

cd my_project

Now, the shell is configured to run the hello world.py file within the folder
named my project. To run this file with Python 3.12, type and run the follow-
ing command in the shell.

python3 .12 hello_world . py

After running that command, you should see the following output.

Hello World !

You just ran a Python file. Sometimes, a Python file is called a Python
script.
14 How to Run Python Code

Method 2

Using Visual Studio, select the Python file that you wish to run. Then press
the “play” button–this button has a triangle on it. Visual Studio will run the
Python file that is currently selected. That’s all you need to do!

⋄⋄⋄

Now you know how to run Python code. The following chapters are about
the Python language itself.
Chapter 3

Data and Variables

Computers have memory, and this memory can store data. In computer pro-
gramming, you can store data with a variable. In this chapter, you will learn
about data in the context of the Python programming language and how to
store data with a variable.

3.1 What Is Data?


Data is information. Here is an example of some data.

" hello "

Here is another example.

Of course, data can be more complex than this, but these examples are
helpful for understanding what data is, at least in Python.

3.2 What Is a Data Type?


In Python, there are data types. This section is about understanding data
types that are built into Python.
16 Data and Variables

3.2.1 Integer
What is an integer? In math, an integer is a number such as 5. But is the
number 5 an integer in Python? To find out, create and save a Python file
containing this code.

print ( type (5) )

Then, run the Python file. You should see the following output.

< class ‘int ’ >

There are angle brackets, the word class, and the letters int surrounded
by single quotes. This output indicates that int is the class or data type
for the number 5. As you may have guessed, int is short for integer. Other
numbers with the int data type are as follows.

-1, -2, -0, 0, 1, 2

To check, go to your Python file, replace the number 5 with one of these six
numbers, and view the output.
Notice that the previous six numbers do not have any decimal points.

3.2.2 Float
Adding a decimal point to the right produces the following numbers.

-1., -2., -0., 0., 1., 2.

In Python, these numbers are not integers. They are called floats. The cor-
responding data type is float. To verify, you can run the following Python
code.

print ( type (0.) )

You should see the following output.


3.2 What Is a Data Type? 17

< class ‘ float ’ >

Once again, there are angle brackets and the word class. But this time,
single quotes surround the word float. So, the data type for 0 followed by a
decimal point is float.
What happens if you add a zero to the right of each decimal point?
-1.0, -2.0, -0.0, 0.0, 1.0, 2.0
If you write Python code to print the data type of one of these numbers, you
will find that the data type is float.
There are many more floats. Here are some others.
0.5, 1.3, 2.2, -1.1, -2.9, -0.4

3.2.3 Complex
If you have taken an algebra course, you have probably heard of the imaginary
unit. In Python, the symbol for the imaginary unit is j.
Place the following code in a Python file to further investigate complex
numbers in Python.

print ( type (2 + 3 j ) )

What is the output of this code? After running the file, the output contains
the word complex surrounded by single quotes.

< class ‘ complex ’ >

So, the data type of the number 2 + 3j is complex. In other words, 2 +


3j belongs to a class named complex. Python has a built-in data type for
complex numbers!
What else can Python do with these complex numbers? First, the real part
of 2 + 3j can be accessed and printed.

print ( type (2 + 3 j ) . real )


18 Data and Variables

After running this code, you’ll see 2.0, which is a float even though the
integer 2 was typed! Python converted the integer into a float.
Similarly, the imaginary part can be accessed and printed.

print ( type (2 + 3 j ) . imag )

After running the updated Python file, you will see 3.0, a float. Python
converted the integer to a float.

3.2.4 String
In this section, you will determine the data type of characters surrounded by
quotes.
Consider the following data.

" Hello World ! "

This data is an example of a string. To check, run the following Python


code.

print ( type ( " Hello World ! " ) )

The output comprises angle brackets, the word class, and str surrounded
by single quotes.

< class ‘str ’ >

So, the data type for "Hello World!" is str, which is short for string.
A string’s outer quotes can be single quotes instead of double quotes. If
you need to put a single quote within a string, surround all of the characters
by double quotes. On the other hand, if you need a double quote inside of a
string, surround all of the characters by single quotes.
3.2 What Is a Data Type? 19

3.2.5 Boolean

Python has several keywords, which are special words that have specific char-
acteristics.
One example of a keyword is True. As you may have guessed, another
keyword is False. What are the data types of these two keywords?

print ( type ( True ) )

The above code outputs angle brackets, the word class, and the word
bool surrounded by single quotes.

< class ‘ bool ’ >

You can run a similar test for the keyword False. You will find that the
data type for the keywords True and False is bool. In other words, True and
False belong to a class named bool. In Python, bool is short for Boolean.

3.2.6 NoneType

In Python, you can use the keyword None. What is the data type of this
keyword?

print ( type ( None ) )

The output indicates that the data type of the keyword None is NoneType.

< class ‘ NoneType ’ >

Why does the keyword None exist? Well, this keyword can indicate that
something hasn’t been set correctly, especially in the context of variables.
20 Data and Variables

3.3 What Is a Variable?


You can store data with a variable, similar to saving code in a file. A variable
has a name, and the data it stores can change over time as code runs.

3.3.1 Storing Data with a Variable


To store data with a variable, use an equals sign. For example, the follow-
ing line of code shows how to store the number 5 with a variable named
my variable.

my_variable = 5

In this example, the integer 5 is assigned to a variable named my variable.


The integer 5 is stored in the computer’s memory when this Python code runs.
Here is a quick test. Suppose you have a Python file with the following
code. When the Python file runs, what is in the shell?

my_variable = 5

my_variable = " hello "

print ( my_variable )

The answer is not 5! The code in this file runs in a particular order over
time. First, the variable stores the integer 5. Then, the variable stores the
string "hello". When the third line runs, the variable is storing "hello", so
hello is displayed in the shell. The data stored by the variable changes from
5 to "hello" as the Python code is run one line at a time.
Chapter 4

Operations

An operation involves two operands and an operator. You can use Python to
operate on data. This chapter examines two kinds of operations: arithmetic
operations and string operations.

4.1 Arithmetic Operations


In this section, you will use the Python interpreter to view the result of an
arithmetic operation. You can launch the Python interpreter by running the
following command in a shell.

python3 .12

After running this command, the interpreter that launches is for version
3.12 of Python. If you have a different version of Python installed, you can
use that, but your results might differ from those in this chapter.

4.1.1 Addition

The first arithmetic operation examined in this chapter is addition. In Python,


you can perform addition with the + operator. Here is a simple example with
two integers.
22 Operations

>>> 2 + 3

The operands are the integers 2 and 3. The result of this arithmetic oper-
ation is 5, which is another integer.

Next, suppose the first operand is a float instead of an integer. What


happens to the result?

>>> 2.0 + 3

The result is a float because the first operand is a float.

5.0

What happens when the second operand is a float?

>>> 2 + 3.0

Once again, the result is 5.0, which is a float.

5.0

4.1.2 Subtraction
This section is about subtraction in Python. To subtract one number from
another, use the - operator. Consider the following example.

>>> 5 - 4

When the operands are the integers 5 and 4, the result is 1, another integer.
4.1 Arithmetic Operations 23

Next, change the first operand from the integer 5 to the float 5.0 to see
how the Python interpreter handles this kind of subtraction.

>>> 5.0 - 4

The result is the float 1.0 because the first operand is a float.

1.0

Similarly, the result is a float when the first operand is an integer and the
second operand is a float.

>>> 5 - 4.0

The result is a float.

1.0

In Python 3.12, addition and subtraction are similar.

4.1.3 Multiplication
In Python, you can perform multiplication with the * operator.
What happens when the integer 10 is multiplied by the integer 5?

>>> 10 * 5

The result is the integer 50.

50
24 Operations

Here is a second example in which the first operand is a float. The first
operand is 10.0, and the second operand is 5.

>>> 10.0 * 5

This time, the result is 50.0, which is a float.

50.0

Here is a third example in which the first operand is an integer, and the
second operand is a float.

>>> 10 * 5.0

As you may have expected, the result is the float 50.0 even though the
first number is the integer 10.

50.0

4.1.4 Division
In Python, you can perform division with the / operator.
Here is an example. The operands are the integers 10 and 5.

>>> 10 / 5

The result of this division is the float 2.0! This behavior is new. In this
case, the answer is a float instead of an integer, even though both operands
are integers.

2.0
4.1 Arithmetic Operations 25

Here is a second example of an integer divided by an integer: what happens


when 1 is divided by 2?

>>> 1/2

The result is 0.5, a float.

0.5

Next, suppose the first operand is the float 10.0 and the second operand
is the integer 5. What is the result?

>>> 10.0 / 5

The result is 2.0, a float.

2.0

Here is a third and final example of division in Python. In the following


code, the second operand is the float 5.0, and the first is the integer 10.

>>> 10 / 5.0

The result is 2.0, which is a float.

2.0

4.1.5 Modulus
In Python, the modulo operator is %. This operator computes the remainder
in the context of division.
For example, consider the following input and output. The operands are
10 and 5.
26 Operations

>>> 10 % 5

The result of 10 modulo 5 is 0 because 10 divided by 5 results in a remain-


der of 0.

Here is another example with operands 8 and 6.

>>> 8 % 6

The result is not 0 this time. The result of 8 modulo 6 is 2 because 8


divided by 6 leaves a remainder of 2.

4.1.6 Exponentiation
Use two asterisks ** for exponentiation in Python. Do not use the caret as
this symbol is for something else.
In the next example, Python is used to compute 2 to the power of 3.

>>> 2 ** 3

The result of this arithmetic operation is 8.

4.2 String Operations


When coding, sometimes strings need to be altered. This section examines
string operations such as concatenation.
4.2 String Operations 27

4.2.1 Concatenating Strings


Adding strings together is known as concatenating the strings. You can con-
catenate strings with the + operator.
As an example, here is how to concatenate three strings.

>>> " hello " + " " + " world ! "

The result is one string.

‘ hello world ! ’

You can generate the same output by concatenating the following two
strings.

>>> " hello " + " world ! "

The result is the same string as in the previous example.

‘ hello world ! ’

With the + symbol, you can add integers and concatenate strings. Reusing
the same symbol for two or more operations is an example of operator over-
loading in computer science.

4.2.2 Indexing a String


Even though Python does not have a data type for characters, a string is
composed of characters.
To access a single character of a string, use an index. The first character in
a string corresponds to an index of 0; the second character corresponds to an
index of 1; the third character corresponds to an index of 2; and so on until
the last character of the string.
For example, you can access the first character of the string "hello" with
an index surrounded by square brackets.
28 Operations

>>> " hello " [0]

In this case, the index is 0. Therefore, the result is the string ‘h’.

‘h ’

You can also place an index and square brackets at the end of a variable’s
name.

>>> my_string = " hello "


>>> my_string [0]

When the first line runs, a variable stores the string "hello" in the com-
puter’s memory. In the second line, there is an index of 0. The index and
square brackets access or extract the string’s first character stored in memory.
Finally, ‘h’ is displayed in the shell.

‘h ’

4.2.3 Finding the Length of a String


Sometimes, one needs to determine the length of a string. The length of a
string is equivalent to the number of characters in the string.
What is the length of the string "hello"? To find out, run the following
code with the Python interpreter.

>>> len ( " hello " )

The length of this string is 5 because the string "hello" has five characters.
The outer quotes do not contribute to the string’s length.

5
4.2 String Operations 29

You may be surprised to learn that there is something called an empty


string in Python. You can make an empty string with two double quotes.
What is the length of an empty string? Run this code with the Python
interpreter to find out.

>>> len ( " " )

Since an empty string contains no characters within the outer quotes, the
length of an empty string is 0.

4.2.4 Slicing a String


Slicing allow you to access part of a string.
Suppose there is a variable named my string. The syntax for slicing a
string is as follows.

my string[start:stop:step]

Here, start, stop, and step are variables for integers. The value stored in
start indicates where to start slicing the original string, inclusive; if start is
storing 0, the resulting string will include the character at index 0.
Similarly, the value stored in stop indicates where to stop slicing the string,
exclusive; if stop is storing 10, the result will not include the character at index
10.
You can skip over characters with the variable named step.
Suppose you want to slice the string "Hello world!" with a start of 0,
a stop of 11, and a step of 1.

>>> " Hello world ! " [0:11:1]

The character at index 0 is H—the output includes this character. No


characters are skipped because step is 1. The variable named stop is 11. The
character at index 11 is the exclamation mark, which is not included in the
30 Operations

output. Therefore, the string ‘Hello world’ without an exclamation point


is displayed.

‘ Hello world ’

Here is an example with a step of 2.

>>> " Hello world ! " [1:11:2]

In this case, start is storing the integer 1. Looking at the original string,
the character at index 1 is e, so the resulting string includes the letter e.
The variable named stop is storing 11. The character at index 11 is the
exclamation mark, so the output does not include an exclamation point.
Recall that the original string is "Hello world!" and the variable named
step is storing a value of 2. The first step from the letter e leads to the letter
l, and the second step leads to another l. The second l is in the output.
After that, two more steps are made by skipping the letter o and arriving
at the space. The space is in the output. This process repeats. As a result,
the string ‘el ol’ is displayed.

‘ el ol ’
Chapter 5

Control Flow

A Python file is read or executed from top to bottom as time progresses. How-
ever, this ordering scheme can be adjusted by including certain keywords. Be-
fore learning more about control flow, you will gain additional background in-
formation on topics such as comparison operators and logical operators. Then,
you will learn how to control the flow of code with conditional statements and
loops.

5.1 Comparison Operators


In the previous chapter, you learned about arithmetic operators such as +, -,
*, and /. In contrast, this section is about comparison operators, such as ==.

5.1.1 Equal To
You can compare two quantities with the == operator. What happens when
the operands are 10 and 9?

>>> 10 == 9

The result is False. In Python, 10 is not equal to 9.

False
32 Control Flow

What if 10 is compared to 10.0?

>>> 10 == 10.0

The result is True. Even though 10 is an integer and 10.0 is a float, these
two quantities are equivalent.

True

Here is a third example with the == operator.

>>> 0 == -0

The result is True, so 0 and -0 are equivalent in Python.

True

5.1.2 Not Equal To


With the != operator, you can check if one quantity is not equal to another
quantity. Here is an example in which the operands are 2 and 3.

>>> 2 != 3

The result is True. In Python, 2 is not equal to 3.

True

5.1.3 Greater Than


Python has a > operator for determining if one quantity is greater than another.
Here is an example with the numbers 10 and 100.
5.1 Comparison Operators 33

>>> 10 > 100

The result is False.

False

⋄⋄⋄

Here is some terminology: a Boolean expression is an expression that


evaluates to True or False. In the previous example, the Boolean expression
is 10 > 100, which evaluates to False.
What is the simplest Boolean expression? There are two correct answers.
If your answer is True, you are correct. The other correct answer is False.
Interestingly, True evaluates to True, and False evaluates to False. Check
with the Python interpreter!

5.1.4 Greater Than or Equal To


Python has a >= operator. Here is one way to use it.

>>> 10 >= 10

The Boolean expression 10 >= 10 evaluates to True.

True

5.1.5 Less Than


The less than operator is <.
Is -5 less than 0 in Python?
34 Control Flow

>>> -5 < 0

The Boolean expression -5<0 evaluates to True, so -5 is less than 0 in


Python.

True

5.1.6 Less Than or Equal To


Python has a <= operator.
Here is an example in which both operands are 7.

>>> 7 <= 7

The left side equals the right side, and the Boolean expression evaluates to
True.

True

⋄⋄⋄

The previous examples focused entirely on comparing numbers, but you


can also compare data stored with variables. Suppose two variables named
variable 1 and variable 2 store numbers. Now, consider the following ex-
pression.

>>> variable_1 <= variable_2

What this Boolean expression evaluates to depends on the values stored


by the variables.
5.2 Logical Operators 35

5.2 Logical Operators


In addition to comparison operators, the Python language has logical opera-
tors. In Python, there are three logical operators:

1. not

2. and

3. or

5.2.1 Logical Not


Make sure to distinguish the “logical not” operator from the “not equal to”
operator! In other words, be sure to distinguish the word not from the !=
operator. If you write the following code, you will get a syntax error.

>>> 2 not = 3

In computer programming, a syntax error indicates that there is a problem


with the way that the characters in the code are arranged.

SyntaxError

Here is how to use the “logical not” operator correctly. First, consider the
following variables and values.

>>> variable_1 = 200


>>> variable_2 = 200

Next, place a “logical not” operator to the left of a Boolean expression.


Put the Boolean expression in parentheses.

>>> not ( variable_1 == variable_2 )


36 Control Flow

Both variables are storing 200, so the Boolean expression in parentheses


evaluates to True. Putting the word not in front of the parentheses causes the
entire Boolean expression to evaluate to False.

False

You may have realized that the previous example had two Boolean expres-
sions.

1. variable 1 == variable 2

2. not (variable 1 == variable 2)

The following table summarizes what the “logical not” operator does.

Figure 5.1: The truth table for the “logical not” operator.

This table is called a truth table. You can check one row of this table by
typing the following code in the Python Interpreter.

>>> not True

The expression not True evaluates to False.

False

The above example with variable 1 and variable 2 involves one Boolean
expression within another, and the entire Boolean expression is of the form
not True.
5.2 Logical Operators 37

5.2.2 Logical Or
A truth table is helpful for understanding the “logical or” operator. The
following table demonstrates what the “logical or” operator does. As you
can see, the word or goes between two Boolean expressions. There are four
possibilities, so Figure 5.2 has four rows.

Figure 5.2: The truth table for the “logical or” operator.

5.2.3 Logical And


The “logical and” operator goes between two Boolean expressions.
38 Control Flow

Figure 5.3: The truth table for the “logical and” operator.

5.3 Conditional Statements


A computer can run code based on whether a Boolean expression evaluates to
True. This is done with a conditional statement.

5.3.1 If Statement
The most basic type of conditional statement is the “if statement.” Suppose a
Python file contains the following code.

variable_1 = 2
variable_2 = 3

if variable_1 == variable_2 :
print ( " The numbers are equal " )

If you try to run this code, you will not see any output! The indented
code with the word print will not run. Why is this? The Boolean expression,
variable 1 == variable 2, will evaluate to False. As a result, the indented
code will not run.
In general, the indented code right below an “if statement” runs if the
Boolean expression evaluates to True. To verify this claim, assign a value
of 3 to variable 1. Now, variable 1 and variable 2 store the same num-
ber. When running this code, is anything printed in the shell? You should
5.3 Conditional Statements 39

see the message The numbers are equal in the shell because variable 1 ==
variable 2 evaluates to True.
You used an “if statement” to control whether a line of code ran. In other
words, you controlled the flow of code.

5.3.2 If. . . Else Statement

Another conditional statement is the “if...else statement.” Perhaps you would


like the computer to run some code for the case of a Boolean expression eval-
uating to False. You can do this with an “if...else statement”. All of the
indented code right below the word else is run only if the Boolean expression
after the word if evaluates to False, not both!
Here is the structure of an “if...else statement.”

variable_1 = 2
variable_2 = 3

if variable_1 == variable_2 :
print ( " The numbers are equal . " )
else :
print ( " The numbers are not equal . " )

Try running this code with Visual Studio. Then, change the numbers
assigned to the variables. What happens when the numbers change? Printing
both sentences is impossible during a given run because a Boolean expression
evaluates to either True or False.

5.3.3 If. . . Elif. . . Else Statement

A third conditional statement is the “if...elif...else statement.” Perhaps you


have several Boolean expressions to check. An “if...elif...else statement” is
helpful for this situation. Consider the following example.
40 Control Flow

variable_1 = 5
variable_2 = 3

if variable_1 == variable_2 :
print ( " option 1 " )
elif variable_1 > variable_2 :
print ( " option 2 " )
else :
print ( " option 3 " )

What does this code print? If you copy and paste this code into Visual
Studio and run the Python file, you will see the following text in the shell.

option 2

Why was this printed? The expression variable 1 == variable 2 evalu-


ates to False, so the indented code right below the word if is skipped. The
next line of code that runs contains the word elif. The expression after the
word elif evaluates to True, so the indented code right below the word elif
runs. After this, nothing else is printed.
What lines of code run when the integer 3 is assigned to variable 1 and
variable 2? In this case, the first Boolean expression evaluates to True, and
the indented code below the word if runs. After this, nothing else is printed.
The third and final option is that both Boolean expressions evaluate to
False. In this case, the indented code right below the word else runs.

5.4 Loops
In Python, a loop allows for running one or several lines of code until a con-
dition, which is a Boolean expression, is not met. The computer programmer
chooses this condition. There are two main types of loops: the “while loop”
and the “for loop.”

5.4.1 While Loop


A “while loop” contains the word while and a Boolean expression. The in-
dented code runs if the Boolean expression or condition evaluates to True.
5.4 Loops 41

Here is an example. The condition is x < 10.

x = 0

while x < 10:


print ( x )
x = x + 1

The indented code consists of two lines. The first line prints the data
stored by the variable named x. To understand the second line, break it into
two parts. First, Python adds the integer 1 to the value stored by x. Then,
Python assigns the result of this arithmetic operation to x.
Initially, x is 0, and the condition x < 10 reduces to 0 < 10. The indented
code runs since this condition evaluates to True. In the first line, 0 is printed.
In the second line, x+1 evaluates to 1 because x currently stores 0. Then,
Python assigns 1 to x.
Next, Python checks the condition. The expression x < 10 reduces to 1
< 10, which evaluates to True. Therefore, all of the indented code runs. In
the first line, 1 is printed. In the second line, x+1 evaluates to 2 because x
currently stores 1. Then, Python assigns 2 to x.
Each of these repeated processes is called an iteration. Iterations continue
until the condition evaluates to False, which occurs when x is 10. This code
prints the numbers 0 through 9.

5.4.2 For Loop


A “for loop” starts with the word for. Here is an example of a “for loop.”

for letter in " word " :


print ( letter )

There are four iterations, one for each letter in the string "word". This
code prints each character of the string "word"—first, the variable named
letter stores the string "w". Then, a w is printed. After this, letter stores
the string "o", and an o is printed. This process repeats, causing the letters
r and d to be printed in the shell. After this, the last character of the string
"word" has been reached, so nothing else is printed.
42 Control Flow

The loop shown above is just one type of “for loop” in Python. Other
types of “for loops” require knowing how to store more than one piece of data
in a single structure.
Chapter 6

Data Structures

In Python, you can store multiple pieces of data in one structure. This can be
done with a list, a tuple, or a dictionary. These are called data structures.

6.1 Lists
Here is an example of a list.

["A", "B", "C", "D", "E"]

The elements of this list are strings.


As shown in the following code, you can access an element of a list with
an index.

my_list = [ " A " , " B " , " C " , " D " , " E " ]

print ( my_list [0])

In the first line, a variable named my list stores a list. In the second line,
an index and square brackets access the first element of the list. Then, Python
prints this element.
As shown in the following code, you can use a “for loop” to access each
element in a list.
44 Data Structures

my_list = [ " A " , " B " , " C " , " D " , " E " ]

for element in my_list :


print ( element )

This code prints the letters A through E in the shell.


Next, here is how to modify an element of a list.

my_list = [ " A " , " B " , " C " , " D " , " E " ]

my_list [0] = " X "

print ( my_list [0])

When running this code, the letter X is printed instead of A. Since you can
change the elements of a list, lists are said to be mutable.
As shown below, you can use the append function to add or append an
element to the end of a list.

my_list = [ " A " , " B " , " C " , " D " , " E " ]

my_list . append ( " F " )

print ( my_list [5])

After appending, the string "F" is at index 5, and Python prints the letter
F in the shell.

6.2 Tuples
Tuples are different from lists. One key difference is that tuples are im-
mutable, meaning that you cannot alter the original elements.
Here is an example of a tuple.

my_tuple = ( " A " , " B " , " C " , " D " , " E " )
6.3 Dictionaries 45

The above code uses parentheses to create a tuple.


Use an index to access an element of a tuple. The following code prints
the first element of my tuple.

my_tuple = ( " A " , " B " , " C " , " D " , " E " )

print ( my_tuple [0])

The previous code prints the letter A.


Finally, use a “for loop” to access each element of a tuple.

my_tuple = ( " A " , " B " , " C " , " D " , " E " )

for element in my_tuple :


print ( element )

After a particular element is accessed, Python prints it. The letters A


through E are displayed in the shell.

6.3 Dictionaries
Dictionaries differ from lists and tuples because they have keys and values.
Each key has an associated value, and two keys cannot be the same. A key is
similar to an index because you can use a key to access a value.
Here is one way to create and store a dictionary.

my_dictionary = {
" Alexa " : " A " ,
" Bob " : " B " ,
" Chris " : " C " ,
" David " : " D "
}

The keys are the students’ names, and the values are the letter grades. You
can also construct a dictionary with different data types; the keys and values
do not have to be strings.
46 Data Structures

To access Alexa’s grade, use the corresponding key, which is the string
"Alexa".

my_dictionary = {
" Alexa " : " A " ,
" Bob " : " B " ,
" Chris " : " C " ,
" David " : " D "
}

print ( my_dictionary [ " Alexa " ])

The previous code stores a dictionary and uses a key to print the letter A.
To access all the keys and values in a dictionary, use a “for loop.”

my_dictionary = {
" Alexa " : " A " ,
" Bob " : " B " ,
" Chris " : " C " ,
" David " : " D "
}

for key in my_dictionary :


print ( key , my_dictionary [ key ])

The above code prints all of the keys and values in the dictionary.
Dictionaries, like lists, are mutable, so you can alter a dictionary after
creating it. For example, you can modify an existing value as follows.

my_dictionary = {
" Alexa " : " A " ,
" Bob " : " B " ,
" Chris " : " C " ,
" David " : " D "
}

my_dictionary [ " Alexa " ] = " A + "

print ( my_dictionary [ " Alexa " ]

When running this code, A+ is printed instead of A.


6.3 Dictionaries 47

To add to an existing dictionary, use a new key.


The following code shows how to add a new value to a dictionary.

my_dictionary = {
" Alexa " : " A " ,
" Bob " : " B " ,
" Chris " : " C " ,
" David " : " D "
}

my_dictionary [ " Fiona " ] = " F "

print ( my_dictionary [ " Fiona " ])

The above code adds new data to the dictionary and prints the letter F.
48 Data Structures
Chapter 7

Functions

In Python, a function can have inputs and outputs. However, these inputs and
outputs are not necessarily required. The inputs, if any, are called arguments
or parameters, and the outputs, if any, are specified with the word return.

7.1 Writing a Function


Functions help organize an entire coding project into smaller parts. Suppose
you need to alter some part of a program. In that case, you can quickly locate
a particular function instead of searching through an enormous block of code
that does many things. Decomposing a complicated computer program into
its constituent parts is an excellent programming practice.

7.1.1 Naming a Function


Typically, the name of a function should be descriptive. If more than one
word is needed to describe what the function does, then an underscore can
be put in between words. If you get in the habit of making descriptive and
specific names for functions you will likely thank yourself later when you need
to re-read and understand code that you wrote on different days.

7.1.2 Implementing a Function


To write or implement a function, put instructions in the form of code in the
body of a function. The body of a function starts in the line right after the
50 Functions

function name. Everything in the body of a function should be indented. Also,


before the function name, write the word def.
Here is an example of how to start writing a function.

def c o n v e r t _ f r o m _ m e t e r s _ t o _ f e e t () :
# The function ’s body starts here .

This function has yet to be implemented; instead, there is a comment. In


Python, a comment starts with a # symbol. You can use comments to write
notes in a Python file.
You may have noticed the parentheses after the function name. As written,
there are no parameters, so you cannot pass data to the function. While this
syntax is valid, having no parameters is not ideal for this example. This func-
tion should convert an arbitrary number in meters into a number in feet. The
input to the function should be a number in meters. The following updated
code includes one parameter named meters.

def c o n v e r t _ f r o m _ m e t e r s _ t o _ f e e t ( meters ) :
feet = 0

In addition, there is a variable named feet, which is a local variable. A


local variable is defined and only accessible within the body of a function.
A function can output some data if you use the word return.

def c o n v e r t _ f r o m _ m e t e r s _ t o _ f e e t ( meters ) :
feet = 0
return feet

As written, this function outputs or returns 0 regardless of the input. The


output needs to be corrected. This function should utilize the parameter
named meters. Since there are approximately three feet in one meter, the
next step is to multiply the number of meters by 3.28084.

def c o n v e r t _ f r o m _ m e t e r s _ t o _ f e e t ( meters ) :
feet = meters * 3.28084
return feet
7.2 Built-In Functions 51

Now, the number of feet depends on the number of meters. This function
correctly converts meters to feet.
The last step is to call the function to check that the function works as
intended.
Consider the following code. The function is called in the last line.

def c o n v e r t _ f r o m _ m e t e r s _ t o _ f e e t ( meters ) :
feet = meters * 3.28084
return feet

print ( c o n v e r t _ f r o m _ m e t e r s _ t o _ f e e t (2) )

Here, the integer 2 is the input to the function. In computer programming,


the input to a function is also called an argument.
The above code prints the float 6.56168, suggesting there are about six
feet in two meters. This output makes sense!
This function can convert any value in meters to a number in feet. To
do so, change the argument from 2 to another number. In general, functions
facilitate reusing code instead of writing the same code more than once.

7.2 Built-In Functions


The previous section outlined how to write a function. You should know
that Python already has several built-in functions. One example of a built-in
function is the abs function, which computes the absolute value of a number.
Another example is the print function. When you call the print function,
you put an argument in the parentheses.

7.2.1 Input and Output

Sometimes, it is helpful to receive information from the user of a Python pro-


gram. This section shows how to request information with a function named
input, which is built into the Python language.
52 Functions

Requesting Input from the User

Here is an example of how to use the input function to get input from the
user.

name_of_user = input ( " Enter your name . " )

When the above code runs, the following prompt appears in the shell.

Enter your name .

At this point, the user can type their name in the shell and press the Enter
key. What the user types is stored in the variable name of user. Then, the
code stops running.

Printing Output

Sometimes, it is helpful to display output to the user. The following code


prints the name that the user typed in the shell.

name_of_user = input ( " Enter your name . " )


print ( " Your name is " + name_of_user + " . " )

If you type the name Bob in the shell and press the Enter key, Python
displays the following text.

Enter your name . Bob


Your name is Bob .

Recall that string concatenation involves the + operator. Did you notice
that the argument of the print function consists of concatenated strings?
Chapter 8

Object-Oriented Programming

Object-oriented programming is a very useful type of programming supported


by many languages, including Python. This section will teach you how to
write and use a class. Object-oriented programming facilitates the creation of
reusable and organized code.

8.1 Writing a Class


A class has a name that goes after the word class. When choosing a name,
use the convention of capitalizing the first letter of each word.
The body of a class must have some indented code. If you do not know what
to write in the body of the class, the word pass can be used as a placeholder
so that there is no error when running the Python file. The word pass doesn’t
do anything.
Here is how to define a class named MyClass.

class MyClass :
pass

8.1.1 Defining Attributes


A class may or may not have attributes. Any attribute must be defined,
meaning you must assign data to the attribute. An attribute is a variable
defined in the body of a class.
54 Object-Oriented Programming

Here is an example of a class with an attribute named color.

class Car :
color = " red "

In this case, the Car class “has a” color. This kind of “has a” relationship
between an attribute and a class is a common way to structure code.
Here is an example with an attribute named make.

class Car :
color = " red "
make = " BMW "

As you can see, a class can define more than one attribute.

8.1.2 Defining Methods


The body of a class can contain methods. A method is a function that is
associated with a class.
Here is Python code with a method named drive.

class Car :
color = " red "
make = " BMW "
def drive ( self ) :
print ( " driving ! " )

The drive method prints the string "driving!" in the shell. You may have
noticed that this method has a parameter named self. While not strictly re-
quired, most Python programmers include the word self as the first parameter
of a method.

The init Method

When defining a class in Python, it is a good programming practice to include


code for a method named init . The name of this method consists of two
underscores on each side of the text init.
8.2 Using a Class 55

Here is one way to write an init method.

class Car :
color = " red "
make = " BMW "
def __init__ ( self ) :
pass
def drive ( self ) :
print ( " driving ! " )

Since the init method is, well, a method, the above code follows the
convention of including the word self as the first parameter.
What is the purpose of the init method? You can use this method to
set attributes while creating an instance. The following section explains how
to achieve this.

8.2 Using a Class

Using a class entails creating an instance of that class. You can create more
than one instance of the same class.

8.2.1 What Is an Instance?

A frequently used statement in computer programming courses is that an


object is an instance of a class. This statement is accurate!

8.2.2 Creating an Instance

In the following code, an instance of the Car class is created and stored in the
last line.
56 Object-Oriented Programming

class Car :
color = " red "
make = " BMW "
def __init__ ( self ) :
print ( " This method was called ! " )
def drive ( self ) :
print ( " driving ! " )

my_car = Car ()

The code on the right side of the equals sign creates an instance of the Car
class. Then, a variable named my car stores this instance. When storing an
instance of a class with a variable, be sure to choose a variable name that is
different from the name of the class.
When creating the instance of the class Car, the init method is auto-
matically called. As a result, the above code prints the following text in the
shell.

This method was called !

⋄⋄⋄

In the above code, the init method has one parameter named self.
What is this word for? One way to find out is to print it. Consider the
following code that prints the word self.

class Car :
color = " red "
make = " BMW "
def __init__ ( self ) :
print ( self )
def drive ( self ) :
print ( " driving ! " )

my_car = Car ()

The above code displays the following text in the shell.


8.2 Using a Class 57

< __main__ . Car object at 0 x10d406ed0 >

According to the output, the word self contains information about a Car
object. Since an object is an instance of a class, the word self contains
information about an instance of the Car class.
The 0x10d406ed0 in the output is a memory address. If you run the above
code on your own computer, you will almost certainly see a different memory
address. The memory address indicates where the instance is stored in your
computer’s memory.
To answer the original question, the word self refers to the instance of
the Car class that is created.

8.2.3 Accessing Data with an Attribute


When creating an instance of a class, the instance obtains the attributes de-
fined in the class. You can access the data stored with an instance’s attribute
using the following syntax.

name of instance.name of attribute

To understand this syntax, consider the following code.

class Car :
color = " red "
make = " BMW "
def __init__ ( self ) :
pass
def drive ( self ) :
print ( " driving ! " )

my_car = Car ()
print ( " My car ’s color is " , my_car . color )
print ( " My car ’s make is " , my_car . make )

In the above code, the my car variable stores an instance. The data stored
with the instance’s attribute named color is accessed by writing my car,
putting a dot, and then writing the word color. The same is done for the
attribute named make. The following text is printed in the shell.
58 Object-Oriented Programming

My car ’ s color is red


My car ’ s make is BMW

Next, here is an example that uses the word self.

class Car :
color = " red "
make = " BMW "
def __init__ ( self ) :
print ( self . color )
def drive ( self ) :
print ( " driving ! " )

my_car = Car ()

The above code displays the following text in the shell.

red

The word self was used within the body of the init method to access
the data stored with an instance’s attribute.

8.2.4 Modifying Data with an Attribute


The following code shows how to modify the data stored with an attribute.

class Car :
color = " red "
make = " BMW "
def __init__ ( self ) :
pass
def drive ( self ) :
print ( " driving ! " )

my_car = Car ()
print ( " My car ’s color was " , my_car . color )
my_car . color = " black "
print ( " My car ’s color is now " , my_car . color )
8.2 Using a Class 59

The above code prints the following output in the shell.

My car ’ s color was red

My car ’ s color is now black

In this example, an instance of the class Car is stored with the variable
called my car. According to the output, the data stored with the attribute
named color changed from "red" to "black".

8.2.5 A Convention for Attributes


A widespread convention is to assign data to attributes within the body of an
init method.
The following code demonstrates this convention.

class Car :
def __init__ ( self , color , make ) :
self . color = color
self . make = make
def drive ( self ) :
print ( " driving ! " )

my_car = Car ( " green " , " Tesla " )


print ( " My car ’s color is " , my_car . color )
print ( " My car ’s make is " , my_car . make )

With respect to the previous example, there are four changes.

1. The attributes named color and make are not defined in the first two
lines of the class.

2. The init method has parameters named color and make.

3. When the instance of the Car class is created, two pieces of data–
specifically, "green" and "Tesla"–are specified.

4. Within the body of the init method, parameters are used to assign
data to the instance’s attributes.
60 Object-Oriented Programming

The previous code prints the following information.

My car ’ s color is green

My car ’ s make is Tesla

Using this convention, you can make more than one instance of the same
class while assigning unique data to each instance’s attributes.
The following code creates two instances of the Car class. For each instance,
data is assigned to the attributes within the body of the init method.

class Car :
def __init__ ( self , color , make ) :
self . color = color
self . make = make
def drive ( self ) :
print ( " driving ! " )

my_car = Car ( " green " ," Tesla " )


print ( " My car ’s color is " , my_car . color )
print ( " My car ’s make is " , my_car . make )

her_car = Car ( " silver " ," Volkswagen " )


print ( " Her car ’s color is " , her_car . color )
print ( " Her car ’s make is " , her_car . make )

After running this code, the following text is displayed in the shell.

My car ’ s color is green

My car ’ s make is Tesla

Her car ’ s color is silver

Her car ’ s make is Volkswagen

Using this convention, the data stored by a given attribute differs from one
instance to another.
8.2 Using a Class 61

8.2.6 Calling a Method


You may be wondering about the drive method. After creating an instance,
you can call methods other than the init method. A method can be called
by using the following syntax.

name of instance.name of method(arg 1, arg 2)

When calling a method, any number of arguments can be included as long


as they correspond to the method’s parameters. The word self should not
be included as an argument, even if one of the parameters is self. If the
method’s only parameter is self, no arguments are needed, as shown below.

name of instance.name of method()

Here is an example that uses a method named drive. Unlike calling a


function, calling a method must involve an instance of a class. In other words,
a method is called on an instance.

class Car :
def __init__ ( self , color , make ) :
self . color = color
self . make = make
def drive ( self ) :
print ( " A " , self . make , " is driving ! " )

my_car = Car ( " green " , " Tesla " )


my_car . drive ()

After running the above code, the following text appears in the shell.

A Tesla is driving !

Why is this printed? First, the drive method is called on the instance
stored with my car. No arguments are specified because the drive method
only has one parameter: self. In the body of the drive method, the data
stored with the attribute named make is accessed with the word self, followed
by a dot and the word make.
Here is another example.
62 Object-Oriented Programming

class Car :
def __init__ ( self , color , make ) :
self . color = color
self . make = make
def drive ( self ) :
print ( " A " , self . make , " is driving ! " )

my_car = Car ( " green " ," Tesla " )


her_car = Car ( " silver " ," Volkswagen " )
my_car . drive ()
her_car . drive ()

In the above code, the variables named my car and her car store instances
of the class Car. The drive method is called on each instance. As a result,
the following text is printed.

A Tesla is driving !

A Volkswagen is driving !

The data stored in the attribute named make depends on the instance.
Finally, suppose the drive method has two parameters.

class Car :
def __init__ ( self , color , make ) :
self . color = color
self . make = make
def drive ( self , dir ) :
print ( " A " , self . make , " is heading " , dir )

my_car = Car ( " green " ," Tesla " )


my_car . drive ( " north " )

When the drive method is called on the instance, one argument is speci-
fied: "north" for the dir parameter.
The above code prints the following message in the shell.

A Tesla is heading north


8.3 Design Tip 63

Now you know how to call a method on an instance!

8.3 Design Tip


One way to design classes is to use nouns for class names and verbs for method
names. The previous example used this technique; the class’s name was Car,
and one of the methods was named drive. This naming convention makes
code easy for humans to understand. However, there may be situations where
a different technique is advantageous.

8.4 Built-In Classes


Python has built-in classes. Do you remember seeing the following output
earlier in this book?

< class ‘int ’ >

The following code displays this output in the shell.

print ( type (2) )

When the type of 2 is printed, ‘int’ for integer is displayed. Here, int is
the name of a built-in class, and this name is displayed within single quotes.
To investigate built-in classes further, consider the following Python code
that prints the type of a string.

print ( type ( " hello " ) )

Here is the output.

< class ‘str ’ >

When the type of the string "hello" is printed, ‘str’ for string is shown.
Here, str is the name of a built-in class.
64 Object-Oriented Programming

In these examples, "hello" is an instance of the class named str, and 2


is an instance of the class named int.
When you assign an integer to a variable, you create and store an instance
of the class named int.
Chapter 9

Inheritance

You inherited genes from your parents. In biology, inheritance is a process


of passing genetic information from one generation to another. An analogous
process exists in object-oriented programming. In particular, a child class
can inherit code from a parent class. In computer science, inheritance is a
technique for reusing and organizing code.

9.1 Inheritance of Attributes


This section covers how a child class inherits attributes from a parent class.

9.1.1 Inheriting an Attribute


Suppose you have a parent class named Mammal, which defines one attribute.

class Mammal :
habitat = " ocean "

You are told to write a child class named Dolphin that inherits from the
Mammal class. After all, a dolphin is a mammal. This kind of “is a” relationship
is typical when designing classes. Inheritance is achieved by putting a pair of
parentheses after the name of the child class and then putting the name of
the parent class in the parentheses. The following example demonstrates this
syntax.
66 Inheritance

class Mammal :
habitat = " ocean "

class Dolphin ( Mammal ) :


pass

dolphin = Dolphin ()
print ( dolphin . habitat )

In the second-to-last line, an instance of the Dolphin class is created. Then,


dolphin.habitat is printed.
After running the code, the following text is displayed in the shell.

ocean

How is the word ocean printed when pass is the only word in the Dolphin
class? The Dolphin class inherits the attribute named habitat from the
parent class.

9.1.2 Customizing Data Stored with an Attribute


Suppose a child class named Monkey inherits from the parent class named
Mammal. Since monkeys do not live in the ocean, the data stored with the
attribute named habitat should be customized for the Monkey class.
The following code shows how a child class can customize or update the
data stored with an attribute.

class Mammal :
habitat = " ocean "

class Monkey ( Mammal ) :


habitat = " forest "

monkey = Monkey ()
mammal = Mammal ()

print ( " monkey ’s habitat : " , monkey . habitat )


print ( " mammal ’s habitat : " , mammal . habitat )
9.1 Inheritance of Attributes 67

The above code prints the following text in the shell.

monkey ’ s habitat : forest

mammal ’ s habitat : ocean

This code successfully customizes the data stored with the habitat at-
tribute for the child class without affecting the parent class.

9.1.3 Adding an Attribute


You can add an attribute to the body of a child class without affecting the
parent class.
Here is an example.

class Mammal :
habitat = " ocean "

class Monkey ( Mammal ) :


habitat = " forest "
fur_color = " brown "

monkey = Monkey ()
mammal = Mammal ()
print ( monkey . fur_color )

This code prints the following text in the shell.

brown

The body of the child class named Monkey defines an attribute named
fur color. Also, a variable named monkey stores an instance of the Monkey
class. This instance has an attribute named fur color, even though the parent
class does not define this attribute.
In addition, a variable named mammal stores an instance of the parent class.
An error message will appear if you try to use mammal to access data stored in
an attribute named fur color.
68 Inheritance

9.2 Inheritance of Methods

Like the inheritance of attributes, a child class can inherit methods from a
parent class.

9.2.1 Inheriting the init Method

First, does a child class inherit the init method in the parent class? The
short answer is yes.
In the following code, there is an init method in the parent class.

class Mammal :
habitat = " ocean "
def __init__ ( self ) :
print ( " a method in the parent class " )

class Monkey ( Mammal ) :


pass

monkey = Monkey ()

The above code prints the following message in the shell.

a method in the parent class

When creating an instance of the Monkey class, the init method in the
parent class is called.
It is also possible to use the parent class’s init method to assign data
to an attribute for an instance of a child class. Consider the following example.
9.2 Inheritance of Methods 69

class Mammal :
def __init__ ( self , habitat ) :
self . habitat = habitat

class Monkey ( Mammal ) :


pass

mammal = Mammal ( " lake " )


monkey = Monkey ( " forest " )

print ( mammal . habitat )


print ( monkey . habitat )

Even though the child class does not have code for an init method,
the following text is printed in the shell.

lake
forest

The child class inherited the init method from the parent class, and
the instance named monkey has an attribute named habitat.

9.2.2 Customizing the init Method


As shown in the following code, you can customize the init method for a
child class.

class Mammal :
def __init__ ( self , habitat ) :
self . habitat = habitat

class Monkey ( Mammal ) :


def __init__ ( self , habitat , tail_length ) :
self . habitat = habitat
self . tail_length = tail_length

mammal = Mammal ( " lake " )


monkey = Monkey ( " forest " ," 30 inches " )
print ( monkey . tail_length )
70 Inheritance

The body of the child class has an init method. In this method, data
is assigned to an attribute named tail length. Not all mammals have tails,
so the parent class does not include an attribute named tail length. When
the code runs, the following information is printed.

30 inches

The instance of the Monkey class has an attribute named tail length.

⋄⋄⋄

To achieve the same functionality, you can use a function named super.
The following example uses the word super.

class Mammal :
def __init__ ( self , habitat ) :
self . habitat = habitat

class Monkey ( Mammal ) :


def __init__ ( self , habitat , tail_length ) :
super () . __init__ ( habitat )
self . tail_length = tail_length

mammal = Mammal ( " lake " )


monkey = Monkey ( " forest " ," 30 inches " )

print ( monkey . habitat )


print ( monkey . tail_length )
print ( mammal . habitat )

This code displays the following information in the shell.

forest

30 inches

lake
9.2 Inheritance of Methods 71

9.2.3 Inheriting a Method

Suppose the Mammal class has a method named move. Would the Monkey class
inherit that method? To find out, call the method on an instance of the Monkey
class.

class Mammal :
def __init__ ( self , habitat ) :
self . habitat = habitat
def move ( self ) :
print ( " moving ! " )

class Monkey ( Mammal ) :


pass

monkey = Monkey ( " forest " )


monkey . move ()

This code generates the following output.

moving !

The move method is called on an instance of the Monkey class. The Monkey
class inherits the move method from the parent class, so the text moving! is
displayed in the shell.

9.2.4 Customizing a Method

The following example shows that a child class can customize a method.
72 Inheritance

class Mammal :
def __init__ ( self , habitat ) :
self . habitat = habitat
def move ( self ) :
print ( " moving " )

class Monkey ( Mammal ) :


def move ( self ) :
print ( " climbing " )

monkey = Monkey ( " forest " )


mammal = Mammal ( " ocean " )

monkey . move ()
mammal . move ()

The child class has code for a method named move, just like the parent
class. The parameters are the same, too. The following words are printed in
the shell when the above code runs.

climbing

moving

A method named move is called on an instance of the Monkey class. The


same is done for an instance of the Mammal class.
The output is the text climbing followed by the text moving. Why is
this? In each class, there is code for a method named move. The move method
is customized or updated in the body of the child class without affecting the
parent class. This technique is an example of overriding a method in object-
oriented programming.

9.2.5 Adding a Method


The following example shows how to add a method to a child class without
affecting the parent class. A method named jump is added to the body of the
Monkey class. Including a method named jump in the Mammal class does not
make much sense–after all, some mammals, like elephants, cannot jump.
9.2 Inheritance of Methods 73

class Mammal :
def __init__ ( self , habitat ) :
self . habitat = habitat

class Monkey ( Mammal ) :


def jump ( self ) :
print ( " jumping ! " )

monkey = Monkey ( " forest " )


monkey . jump ()

After running this code, the following text is displayed in the shell.

jumping !

In the above code, a method named jump is in the body of the child class.
The parent class does not have this method.
After creating an instance of the Monkey class, the jump method is called
on this instance. As a result, the text jumping! is displayed in the shell.
If you try to call a method named jump on an instance of the Mammal class,
you will see an error message.
74 Inheritance
Chapter 10

Modules and Libraries

Once you start working on more complex projects, many lines of code are
needed, and managing all the code in one Python file becomes unmanageable
very quickly. A solution to this problem is using several Python files. Then,
regardless of the size of the project you are working on, you can ensure that
each Python file contains a manageable amount of code, such as 100 lines.

10.1 What Is a Module?


At some point, you might want to use code from one Python file in another.
When Python file A uses code from Python file B, Python file B is called a
module.
Suppose you made a folder named my project. Within this folder, you
made two Python files: setup.py and main.py.
Python has several built-in modules, such as random and math. You can
use code from these modules in your own projects.

10.2 What Is a Library?


A library is reusable code that consists of several modules. Libraries enable
you to build valuable programs without having to reinvent the wheel. One
example of a library is pandas, which is for data science. Another example
is NumPy, which is a library for scientific computing. Sometimes, people use
the terms library and package interchangeably.
76 Modules and Libraries

10.3 What’s pip?


You can manage Python libraries with pip, a program automatically installed
with Python 3.4 or higher. This section teaches you how to install a Python
library with pip.

10.3.1 Is pip Installed?


First, check if pip is installed on your computer. To do this, open a shell and
run the following command.

pip -- version

If pip is installed, you should see a version number in the shell.

10.3.2 Installing pip


If you saw an error when attempting to view a version of pip, you should install
pip. You can do this by running the following command in a shell.

python -m ensurepip -- upgrade

10.4 Virtual Environments


Where you install a library matters, especially if you are working on multiple
Python projects. Project A might need version X of a library, but project B
might need version Y of the same library. Virtual environments are helpful in
this kind of situation.

10.4.1 What Is a Virtual Environment?


A virtual environment allows you to install different software for each
project. If you use a virtual environment, you can keep track of what li-
braries you have installed for that virtual environment and see the version
number for each library.
10.4 Virtual Environments 77

10.4.2 How to Make a Virtual Environment


This section breaks down the process of making a virtual environment.

Make a Folder

The first step is to ensure you have a folder named my project saved on your
Desktop. This folder will contain your Python files.

Navigate to the Correct Location

The next step is to navigate to the correct location. A virtual environment


should be created within the folder for your project. Run the following com-
mand in a shell.

cd Desktop

Then, run a similar command.

cd my_project

In the next section, you will create a virtual environment in the correct
location.

Create a Virtual Environment

You will now create a virtual environment with a Python module named venv.
This module is automatically included in Python version 3.3 or higher. After
following the instructions in the previous section, you can create a virtual envi-
ronment within the folder for your project by running the following command
in a shell.

python -m venv my_environment

The previous command with the word venv creates a virtual environment
named my environment.
78 Modules and Libraries

If you prefer, you can use a different name for the virtual environment.
If you do, replace my environment with your alternate name in the previous
command and subsequent commands.

10.4.3 Activating a Virtual Environment


You need to activate the virtual environment you created in order to use it.
The command for activating a virtual environment depends on whether you
use a Mac or a Windows computer. After activating a virtual environment,
the shell displays the name of the active virtual environment in parentheses.

Mac

If you are using a Mac, you can activate a virtual environment as follows.

source my_environment / bin / activate

Windows

If you are using Windows, you can activate a virtual environment like this.

my_environment \ Scripts \ activate

10.4.4 Viewing Software in a Virtual Environment


One of the main advantages of using a virtual environment is that you can see
which libraries are installed in that virtual environment. To see the libraries,
ensure you have activated a virtual environment for your Python project.
Next, type the following command in the shell.

pip list

You should see software names and corresponding version numbers in the
shell. Those packages, libraries, or programs are associated with the virtual
environment that is currently activated.
10.5 Installing Python Code 79

Making a Requirements File

You can save all the libraries associated with a virtual environment to a file.
This file is typically named requirements.txt.
To do this, run the following command within an active virtual environ-
ment.

pip freeze > requirements . txt

A file named requirements.txt should appear in the folder for your Python
project. This file lists the Python libraries associated with the active virtual
environment. If nothing is listed, you have not installed any libraries for the
active virtual environment. Once you have installed libraries while a virtual
environment is active, the requirements.txt file will list those libraries.

10.4.5 Deactivating a Virtual Environment


To deactivate an active virtual environment, run the following command.

deactivate

After running this command in the shell, the virtual environment has been
deactivated. The name of the virtual environment in the parentheses should
vanish. If needed, you can now activate a different virtual environment for a
separate project.

10.4.6 Removing a Virtual Environment


To remove a virtual environment, delete the folder with the name of the virtual
environment.

10.5 Installing Python Code


This section assumes that you have pip installed. You may wish to review the
What’s pip? section.
80 Modules and Libraries

This section uses the SciPy library to demonstrate the process of installing
a library. You can install SciPy by running the following command within an
active virtual environment. You have an active virtual environment if, in the
shell, you see an environment name within parentheses.

pip install scipy

If you are not using a virtual environment, you can still run the above
command in the shell. However, using a virtual environment is highly recom-
mended for a project that uses multiple libraries so that you can keep track of
which software you are using for that project.
To install a library other than SciPy—such as NumPy or Pandas—use
the Internet to locate official documentation for the library you would like
to install. Then, follow the installation instructions, which almost certainly
utilize the following syntax.

pip install library name

For a given library, you must determine what library name is to construct
the correct command. You can install the library by running the above com-
mand in the shell after replacing library name with the right text. You can
use a virtual environment if desired.

10.6 Importing Python Code


To use code located in a different Python file, you need to import the code.

10.6.1 Importing a Module


In this section, you will learn how to import a module.

Importing a Built-In Module

Recall that Python has several built-in modules, such as random and math.
Consider the math module. To use code from the math module in your own
Python file, place the following code at the top of your Python file.
10.6 Importing Python Code 81

import math

Now, you can use functions from the math module, such as factorial and
sqrt. The best part is that you didn’t have to write these functions! I don’t
know about you, but writing an algorithm to compute the square root of a
number sounds challenging. In exchange for this timesaver, reviewing official
documentation for the code you import is a good programming practice.
Here is an example of how to use a function from the math module.

import math

print ( math . sqrt (4) )

In the above code, a function named sqrt from the math module prints the
square root of the integer 4. Due to the print function, the float 2.0 appears
in the shell.
There is another way to use a function from a module. In particular, you
can use the following syntax.

from math import sqrt

print ( sqrt (4) )

This time, the module’s name is not before the function’s name. The above
code prints the float 2.0 in the shell.
There is a third way to utilize a module’s function. As shown in the
following code, you can import the math module while specifying a custom
name for the module.

import math as mm

print ( mm . sqrt (4) )

Here, the custom name is mm. After running the code, the float 2.0 is
displayed.
82 Modules and Libraries

Importing Code from Another Python File

Suppose you have two Python files, star.py and application.py, in the same
folder and would like to use code from star.py in the application.py file.
The star.py file contains the following function.

def print_star () :
print ( " * " )

As you can see, print star is in the star.py file.


Next, suppose the following code is in the application.py file.

import star

star . print_star ()

In the first line of application.py, the star module is imported. Then, the
print star function is called.
When running application.py, the following character is displayed in the
shell.

So, a function was written in one Python file used in another.

⋄⋄⋄

You can also use a class from another Python file. For example, suppose
star.py contains code for a class named Star instead of a print star function.

class Star :
def __init__ ( self ) :
print ( " A method was called . " )

Even though the Star class is written in star.py, you can use this class
10.6 Importing Python Code 83

in application.py. For example, suppose application.py contains the following


code.

from star import Star

my_star = Star ()

In the first line, application.py imports the Star class from the star mod-
ule.
When application.py runs, the following text is displayed.

A method was called .

As you can see, the init method for the Star class was called.

10.6.2 Importing a Library


This section shows how to install and import a Python library. The NumPy
library is used as an example.
To install the NumPy library, use pip. The following command should be
run in a shell.

pip install numpy

If desired, you can run the previous line of code in an active virtual envi-
ronment.
Next, import the NumPy library by putting the following code at the top
of a Python file.

import numpy

Alternatively, you can import the NumPy library like this.

import numpy as np
84 Modules and Libraries

Now you can use code from this library.


A commonly used function from the NumPy library is named linspace.
This function returns numbers that are evenly spaced across an interval that
you specify.
Here is an example of how to use the linspace function.

import numpy

a = 0

b = 10

N = 4

arr = numpy . linspace (a ,b ,N , endpoint = True )

print ( a )

The last argument is endpoint=True, so the returned numbers will include


the endpoint, which is 10. When the above code runs, the following data is
printed in the shell.

[ 0. 3.33333333 6.66666667 10. ]

The quantity returned by the linspace function is an instance of the


numpy.ndarray class, which you can verify by using the type function.
The linspace function is one of many parts of the NumPy library. Official
documentation for NumPy and other libraries is online.
Part II

Make a Game
Chapter 11

Start a Project

In the previous chapters, you investigated the basics of Python. Now is a


fantastic time to put what you learned into practice. Plus, making a game is
entertaining!

Figure 11.1: A snapshot of the game.

The remaining chapters form a tutorial for developing a two-dimensional


game. After clicking the start button, the user moves the rocket to the left
and right. The objective is to avoid incoming asteroids.
88 Start a Project

11.1 Make a Folder


While progressing through this tutorial, you will encounter several files. All
the files go in one folder. So, the first step is to make a folder for this project.
Save the folder on your Desktop. Then, use Visual Studio to open the folder
that you created.

11.2 Display a Path


Open a shell. Remember that Visual Studio has a built-in shell. Run one of
the following commands to display a path.

11.2.1 Mac

pwd

11.2.2 Windows

cd

11.3 Change the Working Directory


In the previous section, you displayed a path in the shell. The last part of
this path, the text immediately after the rightmost slash, is the name of the
working directory. If this name is the same as the name of the folder for
this project, you are all set—skip to the next section. Otherwise, follow the
steps in this section to change the working directory.
Since the folder for this project is on your Desktop, run the following
command in the shell.

cd Desktop
11.4 Install a Python Library 89

After running the above command, the working directory is your Desktop’s
folder.
Next, run the following command. Be sure to replace name of project
with the name of the folder you made.

cd name_of_project

11.4 Install a Python Library


This game uses a Python library named pygame. You may wish to use a virtual
environment. If so, refer to the section titled Virtual Environments.
To install pygame, run the following command in the shell.

pip install pygame


90 Start a Project
Chapter 12

Create a Window

You installed a library named pygame at the end of the previous chapter. In
this chapter, you will use this library to create a window for the game.
In Visual Studio, create a Python file named app.py and ensure that this
file is within the folder you created for this project.
Next, put the following line of Python code at the top of app.py.

import pygame

The pygame library contains modules that must be initialized. To initialize


them, add this code to the app.py file.

pygame . init ()

Next, create a window by adding the following code.

window = pygame . display . set_mode ((1280 ,790) )

Note that pygame.display is a module. Within this module is a function


named set mode, which creates a window for the game. The tuple (1280,790)
is an argument that specifies the dimensions of the game’s window. This
window has 1280 pixels in the horizontal direction and 790 pixels in the vertical
direction.
At this point, try running app.py with the following command in the shell.
92 Create a Window

python app . py

If you saw a ModuleNotFoundError, try replacing python with python3


or python3.12. This may change the version of Python that you are using.
You can even run the commands python --version and python3 --version
to see the version numbers. Before proceeding, ensure that you can run the
app.py file. You should see a message like this.

pygame 2.5.2 ( SDL 2.28.3 , Python 3.12.1)


Hello from the pygame community .
https :// www . pygame . org / contribute . html

When running app.py, why didn’t a window appear? You created a win-
dow, but the window immediately disappeared. To fix this, add a “while loop”
to prevent the window from vanishing.

running = True
while running :
for event in pygame . event . get () :
if event . type == pygame . QUIT :
running = False

This “while loop” runs until the user presses the button for closing the win-
dow. If you run app.py now, you will see a window with a black background.
Why does this work?
You assigned the keyword True to a variable named running. The code in
the “while loop” executes until running is False.
In the body of the “while loop”, you wrote a “for loop” that uses the code
pygame.event.get(). Here, pygame.event is a module, and get is a function.
This function gets instances of a pygame class named Event.
During an iteration of the “for loop,” a variable named event stores one of
the instances from pygame.event.get(). An instance of the Event class has
an attribute named type. If the user presses the close button on the game’s
window, this attribute is set to pygame.QUIT.
There is an “if statement” within the body of the “for loop”. You use the ==
operator to check if the data stored with event.type is equal to pygame.QUIT.
If so, you set the variable named running to False, which causes the current
12.1 Download Images and Sounds 93

iteration of the “while loop” to be the final one. Below the “while loop,” there
is no more code. The window vanishes as the user would expect.
Here is all of the code for this section. This code goes in the app.py file.

import pygame
pygame . init ()

window = pygame . display . set_mode ((1280 ,790) )

running = True
while running :
for event in pygame . event . get () :
if event . type == pygame . QUIT :
running = False

Running app.py should cause a window with a black background to appear.


If you press the close button, the window should vanish.
The “if statement” is important—otherwise, there would be an infinite
loop, which runs forever. If you accidentally made and ran an infinite loop,
click the shell and press control-C to stop the Python code from running!

12.1 Download Images and Sounds


This game uses images and sounds. You can download them from the following
location.

https://github.com/python-programming-made-simple/a

Be sure to place the downloaded files within the folder you created for this
project. You do not need to download the README.md file.

12.2 Load Images and Sounds


Create a file named load.py–this will contain the code for loading the images
and sounds. In particular, put the following code in load.py.
94 Create a Window

import pygame

metal_png = pygame . image . load ( " metal . png " )


start_png = pygame . image . load ( " start . png " )
pause_png = pygame . image . load ( " pause . png " )
lives_png = pygame . image . load ( " lives . png " )
score_png = pygame . image . load ( " score . png " )
background_png = pygame . image . load ( " background . png " )
game_over_png = pygame . image . load ( " game_over . png " )
game_win_png = pygame . image . load ( " game_win . png " )
rocket_png = pygame . image . load ( " rocket . png " )
asteroid_png = pygame . image . load ( " asteroid . png " )

start_sound = pygame . mixer . Sound ( " start . mp3 " )


collision_sound = pygame . mixer . Sound ( " collision . mp3 " )
pause_sound = pygame . mixer . Sound ( " pause . mp3 " )
game_over_sound = pygame . mixer . Sound ( " game_over . mp3 " )
game_win_sound = pygame . mixer . Sound ( " game_win . mp3 " )
point_sound = pygame . mixer . Sound ( " point . mp3 " )

asteroids = []
score = 0
lives = 3
12.3 Add Images to the Game 95

The pygame library has a module named image. Within this module is a
function named load. In the load.py file, you use the load function to load
each PNG file. The load function returns an instance of the Surface class,
and you store each instance with a variable. The Surface class is from the
pygame library.
The pygame library contains another module named mixer. This module
includes a class named Sound. In the load.py file, you create instances of the
Sound class while specifying the names of mp3 files. Then, you store each
instance of the Sound class with a variable.
At the end of the file, you define three variables: asteroids, score, and
lives. You assign an empty list to asteroids.
The load.py file is complete.

⋄⋄⋄

Next, modify app.py by adding the line with the comment.

import pygame
pygame . init ()
import load # add this line !

window = pygame . display . set_mode ((1280 ,790) )

running = True
while running :
for event in pygame . event . get () :
if event . type == pygame . QUIT :
running = False

Now, you can use the variables from load.py in app.py.


Finally, try running app.py–if there are no errors, proceed to the next
section.

12.3 Add Images to the Game


In this section, you will use a method named blit to add three images to the
game’s window.
96 Create a Window

The blit method is from the Surface class. You can call the blit method
on the window variable, which stores an instance of the Surface class. Before
the “while loop,” add the following line of code to the app.py file.

window . blit ( load . background_png ,(0 ,0) )

In this line, you pass two arguments to the blit method. The first ar-
gument is load.background png, which stores information about the back-
ground image. You use the load module to access this data.
The second argument is the tuple (0,0). This tuple indicates that the
upper left corner of the background image should be placed at (0,0). These
two numbers are for the window’s coordinate system. The first number is the
x-coordinate, and the second is the y-coordinate.
The window’s positive x-axis points to the right and runs along the top of
the window, not including the section with the close button. The window’s
positive y-axis points down and runs along the window’s left edge. Therefore,
(0,0) corresponds to the upper left corner of the window, not including the
section with the close button.
The next step is to include the following code before the “while loop.”

window . blit ( load . metal_png ,(0 ,720) )

This line adds an image of a metal dashboard to the bottom of the game’s
window.
Next, add an image of a start button to the game’s window. The following
line of code goes before the “while loop.”

window . blit ( load . start_png ,(10 ,730) )

Finally, add the following code before the “while loop.”

pygame . display . update ()

This above line updates the game’s window.


Now, the app.py file should look like this.
12.3 Add Images to the Game 97

import pygame
pygame . init ()
import load
window = pygame . display . set_mode ((1280 ,790) )

window . blit ( load . background_png ,(0 ,0) )


window . blit ( load . metal_png ,(0 ,720) )
window . blit ( load . start_png ,(10 ,730) )
pygame . display . update ()

running = True
while running :
for event in pygame . event . get () :
if event . type == pygame . QUIT :
running = False

Run the app.py file. The game’s window should resemble the following
illustration. If not, ensure the images are in the same folder as the app.py file.
If that doesn’t work, you can perform a Google search for the error message
that you see in the shell.

Figure 12.1: The game’s window with three images.


98 Create a Window
Chapter 13

Write Classes

In this chapter, you will dive into object-oriented programming by writing


classes. The first class that you will write is named Image.

13.1 The Image Class

This class manages images in the bottom right corner of the game’s window.
For example, you will use this class to display a numerical score on the game’s
window.
The strategy is to specify a number, make an image of the number, and
place this image on the game’s window with the blit method. For aesthetic
reasons, there is a small background image for the number.
To start, make a new file named image.py and include the following code
at the top.

import pygame

Next, write an outline of a class named Image.


100 Write Classes

import pygame

class Image :
def __init__ ( self , window , position , png , png_position ) :
pass
def display ( self , my_string ) :
pass

The init method has five parameters: self, window, position, png,
and png position.
Next, assign parameters to attributes.

import pygame

class Image :
def __init__ ( self , window , position , png , png_position ) :
self . window = window
self . position = position
self . png = png
self . png_position = png_position
def display ( self , my_string ) :
pass

The body of the init method contains four attributes.


Next, add the following line of code to the display method.

my_font = pygame . font . SysFont ( " Arial " ,16)

Here, pygame.font is a module from the pygame library. Within this mod-
ule is a function named SysFont, which creates an instance of a pygame class
named Font. You store this instance with a variable named my font.
Next, add the following lines to the display method.

white = (255 ,255 ,255)


number = my_font . render ( my_string . zfill (3) , True , white )

Here, you call a method named render on my font. The first argument
involves my string. For this tutorial, assume that my string stores a string
13.1 The Image Class 101

containing a number. For example, the string ‘5’ is a valid piece of data.
The zfill(3) method is used for aesthetic reasons. This method returns a
string containing three digits. If the string ‘5’ were stored with the my string
parameter, then my string.zfill(3) would return the string ‘005’.
The second argument is the keyword True so that the numbers have smooth
edges.
The third argument specifies a color for the numbers. The color white is
represented by the tuple (255,255,255).
Finally, the render method returns an instance of the Surface class. This
instance contains information about an image of a white, three-digit number.
You store this image with a variable named number.

⋄⋄⋄

Next, add a background image for the number. Use the blit method.

self . window . blit ( self . png , self . png_position )

Notice the use of attributes. These attributes are accessed with the word
self.
Now, use the blit method again.

self . window . blit ( number , self . position )

The previous line places the image of a number on the game’s window.
The Image class is now complete! Here is the final code for the image.py
file.
102 Write Classes

import pygame

class Image :
def __init__ ( self , window , position , png , png_position ) :
self . window = window
self . position = position
self . png = png
self . png_position = png_position
def display ( self , my_string ) :
my_font = pygame . font . SysFont ( " Arial " ,16)
white = (255 ,255 ,255)
number = my_font . render ( my_string . zfill (3) , True , white )
self . window . blit ( self . png , self . png_position )
self . window . blit ( number , self . position )
13.1 The Image Class 103

Now that the Image class has been written, you can use it. First, return
to the app.py file. Then, write the following line.

import image

Next, make a few empty lines before pygame.display.update(). Then,


create two instances of the Image class in the space you just made.

p_1 = (1232 ,752)


p_2 = (1220 ,730)
score_image = image . Image ( window , p_1 , load . score_png , p_2 )
p_3 = (1172 ,752)
p_4 = (1160 ,730)
lives_image = image . Image ( window , p_3 , load . lives_png , p_4 )

The variables named score image and lives image store instances of the
Image class. Also, the tuples specify locations of images.
Next, call the display method on each instance, to show a numerical
score and a number of lives. Assume that load.score and load.lives store
integers.

score_image . display ( str ( load . score ) )


lives_image . display ( str ( load . lives ) )

First, you converted an integer to a string. Then, you called the display
method on score image and lives image.
At this point, the app.py file should have the following code. For good
measure, test the code by running app.py. You should see 000 for the initial
score and 003 for the initial number of lives!
104 Write Classes

import pygame
pygame . init ()
import load
import image

window = pygame . display . set_mode ((1280 ,790) )

window . blit ( load . background_png ,(0 ,0) )


window . blit ( load . metal_png ,(0 ,720) )
window . blit ( load . start_png ,(10 ,730) )

p_1 = (1232 ,752)


p_2 = (1220 ,730)
score_image = image . Image ( window , p_1 , load . score_png , p_2 )
p_3 = (1172 ,752)
p_4 = (1160 ,730)
lives_image = image . Image ( window , p_3 , load . lives_png , p_4 )
score_image . display ( str ( load . score ) )
lives_image . display ( str ( load . lives ) )

pygame . display . update ()

running = True
while running :
for event in pygame . event . get () :
if event . type == pygame . QUIT :
running = False

13.2 The GameObject Class

In this section, you will write a fairly generic class named GameObject. Eventu-
ally, two child classes named Asteroid and Rocket will inherit the GameObject
class.
To begin, create a new file named game object.py. Then, add the following
outline for the class.
13.2 The GameObject Class 105

class GameObject :
def __init__ ( self , window , image ,x , y ) :
pass
def draw ( self ) :
pass

There is an init method and a method named draw. The init


method has five parameters, and the draw method has one.
Next, assign four parameters to attributes in the body of the init
method.

class GameObject :
def __init__ ( self , window , image ,x , y ) :
self . window = window
self . image = image
self . x = x
self . y = y
def draw ( self ) :
pass

Next, implement the draw method, which simply adds an image to the
window for the game.
106 Write Classes

class GameObject :
def __init__ ( self , window , image ,x , y ) :
self . window = window
self . image = image
self . x = x
self . y = y
def draw ( self ) :
self . window . blit ( self . image ,( self .x , self . y ) )
13.3 The Rocket Class 107

In the body of the draw method, you call the blit method. There are two
arguments. The first argument, self.image, stores an image. The second
argument, (self.x, self.y), is a pair of coordinates indicating where on
the window to place the upper left corner of the image.
The game object.py file is complete.

13.3 The Rocket Class

In this section, you will write a class named Rocket. This class inherits from
the GameObject class written in the previous section.
First, make a new file named rocket.py. Then, place the following code at
the top of the file.

import game_object

Next, outline a class that inherits from the GameObject class.

import game_object

class Rocket ( game_object . GameObject ) :


def translate_left ( self ) :
pass
def translate_right ( self ) :
pass

There are two methods for horizontally translating an image of a rocket.


The Rocket class inherits the init method from the parent class, GameObject.

Next, implement the methods.


108 Write Classes

import game_object

class Rocket ( game_object . GameObject ) :


step = 10
def translate_left ( self ) :
if self . x >= self . step :
self . x = self . x - self . step
def translate_right ( self ) :
if self . x + 100 <= 1280 - self . step :
self . x = self . x + self . step

First, the integer 10 is assigned to an attribute named step. This at-


tribute specifies the number of pixels the rocket moves when translate left
or translate right is called.
The translate left method translates the rocket to the left without let-
ting it move off the game’s window. The x attribute is for the left edge of
the image of the rocket. Checking whether the x attribute is greater than or
equal to 10 pixels ensures that there are at least 10 pixels between the left
edge of the game’s window and the left edge of the rocket’s image. If so, the
x attribute decreases by 10 pixels. In other words, the image translates to the
left.
Similarly, the translate right method translates the rocket to the right
without letting it move off the game’s window. The width of the image for
the rocket is 100 pixels. So, self.x + 100 corresponds to the right edge of
the rocket’s image. The width of the game’s window is 1280 pixels. Checking
whether the right edge of the rocket’s image is less than or equal to 1270 pixels
ensures that there are at least 10 pixels between the right edge of the window
and the right edge of the rocket’s image. If so, the x attribute increases by 10
pixels. So, the image translates to the right.

13.4 The Asteroid Class

Like the Rocket class, the Asteroid class should inherit from the GameObject
class.
First, create a new file named asteroid.py. Then, place the following code
at the top of the file.
13.5 The Button Class 109

import game_object

Next, write an outline for the class.

import game_object

class Asteroid ( game_object . GameObject ) :


def translate_down ( self ) :
pass

The Asteroid class inherits the init method from the parent class.
Also, there is a method named translate down.
Next, implement the method.

import game_object

class Asteroid ( game_object . GameObject ) :


def translate_down ( self ) :
self . y = self . y + 1

In the above code, you add the integer 1 to the value stored with the y
attribute. Then, you assign the sum to the y attribute. When called, this
method causes an image of an asteroid to translate downward by one pixel.

13.5 The Button Class


In this section, you will write a class that enables an image of a button to
function like a button [58].
First, make a new file named button.py. This class will use the pygame
library, so put the following line of code at the top of the file.

import pygame

Next, outline the class.


110 Write Classes

import pygame

class Button :
def __init__ ( self ,x ,y , image ) :
pass
def left_click ( self ) :
pass

This class includes a method named left click.


First, get the position of the cursor.

import pygame

class Button :
def __init__ ( self ,x ,y , image ) :
pass
def left_click ( self ) :
cursor_position = pygame . mouse . get_pos ()

The get pos function from the pygame.mouse module returns a tuple rep-
resenting the cursor’s position on the game’s window.
Next, assume that the image parameter is an instance of the Surface
class. The Surface class includes a method named get rect, which returns an
instance of the Rect class. This pygame class allows you to manage rectangular
areas. In this situation, the Rect class is helpful because a rectangular area is
associated with an image of a button.

import pygame

class Button :
def __init__ ( self ,x ,y , image ) :
self . rectangle = image . get_rect ()
def left_click ( self ) :
cursor_position = pygame . mouse . get_pos ()

The get rect method is called on image. The resulting instance of the
Rect class is stored with an attribute named rectangle.
Next, add one line to the init method.
13.5 The Button Class 111

import pygame

class Button :
def __init__ ( self ,x ,y , image ) :
self . rectangle = image . get_rect ()
self . rectangle . topleft = (x , y )
def left_click ( self ) :
cursor_position = pygame . mouse . get_pos ()

The Rect class includes an attribute named topleft. The tuple (x,y)
is assigned to self.rectangle.topleft in order to specify the position of a
button’s rectangular area.
Next, add an “if statement” to the left click method.

import pygame

class Button :
def __init__ ( self ,x ,y , image ) :
self . rectangle = image . get_rect ()
self . rectangle . topleft = (x , y )
def left_click ( self ) :
cursor_position = pygame . mouse . get_pos ()
if self . rectangle . collidepoint ( cursor_position ) :
pass

The “if statement” involves a method named collidepoint, which is from


the Rect class. This method is called to determine if the cursor is on a button’s
image.
Next, add a line of code to the “if statement.”
112 Write Classes

import pygame

class Button :
def __init__ ( self ,x ,y , image ) :
self . rectangle = image . get_rect ()
self . rectangle . topleft = (x , y )
def left_click ( self ) :
cursor_position = pygame . mouse . get_pos ()
if self . rectangle . collidepoint ( cursor_position ) :
if pygame . mouse . get_pressed () [0] == True :
pass

The mouse module includes a function named get pressed. This function
returns a tuple representing states of buttons on a mouse. The index 0 is used
to access the state of the mouse’s left button.
This left click method should return True if the cursor is on the image
for the button and there is a left click. Otherwise, False should be returned.
The following code finalizes the button.py file.
13.5 The Button Class 113

import pygame

class Button :
def __init__ ( self ,x ,y , image ) :
self . rectangle = image . get_rect ()
self . rectangle . topleft = (x , y )
def left_click ( self ) :
cursor_position = pygame . mouse . get_pos ()
if self . rectangle . collidepoint ( cursor_position ) :
if pygame . mouse . get_pressed () [0] == True :
return True
else :
return False
114 Write Classes
Chapter 14

Fill in the Gaps

Classes are defined, but this game requires additional code for various features.
For example, how is the game going to start? How should an image of an
asteroid appear on the window? In this chapter, you will fill in gaps like these
by using variables and writing functions.

14.1 Add Four Global Variables


First, create a file named booleans.py. Then, add the following code.
116 Fill in the Gaps

started_game = False
button_pressed = False
game_over = False
game_won = False
14.2 Add Three Functions 117

These variables are global variables as they are written outside of func-
tions. The booleans.py file is complete.

14.2 Add Three Functions


In this section, you will add functions for starting the game, pausing the game,
and creating an asteroid.

14.2.1 Start
When the user clicks on the start button, certain lines of code should run. In
this section, you will write those lines of code within a function named start.
First, make a file named start.py.
Next, put two lines at the top.

import booleans as bln


import load

There is one parameter named window.


Then, outline the start function.

import booleans as bln


import load

def start ( window ) :


pass

Next, add a few lines of code to the function’s body.


118 Fill in the Gaps

import booleans as bln


import load

def start ( window ) :


load . start_sound . play ()
bln . started_game = True
bln . button_pressed = True
window . blit ( load . pause_png ,(10 ,730) )
14.2 Add Three Functions 119

In the first line, you play a sound. The global variable start sound from
load.py stores an instance of a pygame class named Sound. When you call the
play method on this instance, a sound plays.
Next, you set started game to True. You also set button pressed to
True.
Finally, you add an image of a pause button to the game’s window.
The start.py file is complete.

14.2.2 Pause
Certain lines of code should run when the user presses the pause button.
First, make a file named pause.py.
Then, add two lines.

import booleans as bln


import load

Next, outline the pause function.

import booleans as bln


import load

def pause ( window ) :


pass

Finally, implement the function.


120 Fill in the Gaps

import booleans as bln


import load

def pause ( window ) :


load . pause_sound . play ()
bln . started_game = False
bln . button_pressed = True
window . blit ( load . start_png ,(10 ,730) )
14.2 Add Three Functions 121

First, you play a sound to signify a pause in the game.


Then, you set started game to False and button pressed to True.
Finally, you add an image of a start button.
The pause.py file is complete.

14.2.3 Create an Asteroid


An asteroid should be created at the top of the game’s window at a “random”
horizontal location.
First, return to the file named asteroid.py.
Then, add two lines to the top of the file.

import load
import random

import game_object

class Asteroid ( game_object . GameObject ) :


def translate_down ( self ) :
self . y = self . y + 1

Recall that the random module is built into the Python language.
Next, add a function named create asteroid to this file. The code for this
function goes outside of the class’s body. A lack of indentation is important!

import load
import random

import game_object

class Asteroid ( game_object . GameObject ) :


def translate_down ( self ) :
self . y = self . y + 1

def create_asteroid ( window ) :


pass

Finally, implement the function.


122 Fill in the Gaps

import load
import random

import game_object

class Asteroid ( game_object . GameObject ) :


def translate_down ( self ) :
self . y = self . y + 1

def create_asteroid ( window ) :


r = random . randint (0 ,1205)
asteroid = Asteroid ( window , load . asteroid_png ,r , -30)
load . asteroids . append ( asteroid )
14.3 Add One Method 123

First, you create a “random” integer in the closed interval [0,1205] with
the randint function from the random module.
In the second line, you create an instance of the Asteroid class. To do so,
you set the x attribute to the “random” integer. Also, you set the y attribute
to -30 so that only part of an asteroid is initially visible. This instance is
stored with a local variable named asteroid.
In the last line, you utilize a method named append to add the instance to
the end of the list stored with the asteroids variable from the load.py file.
The asteroid.py file is now complete.

14.3 Add One Method


In this section, you will write a method that determines whether the rocket
has collided with an asteroid.
To begin, return to the rocket.py file. You will add the method to the
Rocket class.
First, outline a method named collision.

import game_object

class Rocket ( game_object . GameObject ) :


step = 10
def translate_left ( self ) :
if self . x >= self . step :
self . x = self . x - self . step
def translate_right ( self ) :
if self . x + 100 <= 1280 - self . step :
self . x = self . x + self . step
def collision ( self , asteroid ) :
pass

The parameters’ names are self and asteroid.


Recall that the Surface class from pygame includes a method named
get rect, which returns an instance of the Rect class. The Rect class in-
cludes a method named colliderect, which returns True if two rectangular
areas overlap and False otherwise.
Next, implement the method.
124 Fill in the Gaps

import game_object

class Rocket ( game_object . GameObject ) :


step = 10
def translate_left ( self ) :
if self . x >= self . step :
self . x = self . x - self . step
def translate_right ( self ) :
if self . x + 100 <= 1280 - self . step :
self . x = self . x + self . step
def collision ( self , asteroid ) :
as te ro id _r ec ta ng le = asteroid . image . get_rect ()
as te ro id _r ec ta ng le . topleft = ( asteroid .x , asteroid . y )
rocket_rectangle = self . image . get_rect ()
rocket_rectangle . topleft = ( self .x , self . y )
if rocket_rectangle . colliderect ( ast er oi d_ re ct an gl e ) :
return True
else :
return False
14.4 Add Four Functions 125

Here, you use the Rect class to manage rectangular areas corresponding to
images of a rocket and an asteroid. In particular, you create two instances of
the Rect class and store them with local variables named asteroid rectangle
and rocket rectangle. The precise locations of these rectangles are estab-
lished by using the topleft attribute from the Rect class. Then, you call the
colliderect method on rocket rectangle–note that asteroid rectangle
is an argument. Finally, you write an “if...else statement” that returns True
or False based on whether there was a collision or not.
The rocket.py file is complete.

14.4 Add Four Functions


Four more functions are needed.

14.4.1 Handling a Collision


A function will be called when the rocket collides with an asteroid.
To start, make a file named collide.py.
Then, add the following code to the top of the file.

import load

Next, outline a function named collide.

import load

def collide ( lives_image , asteroid ) :


pass

There are two parameters named lives image and asteroid.


Finally, implement the function.
126 Fill in the Gaps

import load

def collide ( lives_image , asteroid ) :


load . collision_sound . play ()
load . asteroids . remove ( asteroid )
load . lives = load . lives - 1
lives_image . display ( str ( load . lives ) )
14.4 Add Four Functions 127

First, you play a collision sound. Next, you remove an instance of the
Asteroid class from asteroids because an asteroid should disappear when
the user gets a point. Then, you decrease the number of lives by updating a
variable named lives from the load module. Finally, you display the updated
number of lives on the game’s window by calling the display method from
the Image class.
The collide.py file is complete.

14.4.2 Losing the Game


A function will be called when the game is over.
First, create a Python file named gmo.py.
Then, put two lines at the top.

import load
import booleans as bln

Next, outline a function named gmo. This name is intentionally short!

import load
import booleans as bln

def gmo ( window , score_image , lives_image ) :


pass

There are three parameters: window, score image, and lives image.
Lastly, implement the function.
128 Fill in the Gaps

import load
import booleans as bln

def gmo ( window , score_image , lives_image ) :


load . game_over_sound . play ()
window . blit ( load . metal_png ,(0 ,720) )
score_image . display ( str ( load . score ) )
lives_image . display ( str (0) )
load . asteroids = []
bln . button_pressed = True
bln . started_game = False
bln . game_over = True
14.4 Add Four Functions 129

First, you play a sound. Then, you add an image of a metal dashboard to
the game’s window. Next, you call the display method on score image to
display the score on the dashboard. Similarly, you use lives image to display
0 lives. Finally, you assign an empty list to asteroids and update three global
variables.
The gmo.py file is complete.

14.4.3 Increasing the Score


The user should get a point in a certain situation.
First, create a new file named score.py.
Then, put one line at the top.

import load

Next, outline a function named increase score.

import load

def increase_score ( asteroid , score_image ) :


pass

There are two parameters: asteroid and score image.


Here is the implemented function.
130 Fill in the Gaps

import load

def increase_score ( asteroid , score_image ) :


load . asteroids . remove ( asteroid )
load . score = load . score + 1
if load . score != 10:
load . point_sound . play ()
score_image . display ( str ( load . score ) )
14.4 Add Four Functions 131

First, you remove an instance of the Asteroid class from asteroids, which
stores a list. Then, you increase the user’s score by one. Next, you manage
a sound with an “if statement.” Finally, you display the updated score by
passing a string to the display method.
The score.py file is complete.

14.4.4 Winning the Game


The user should win the game after obtaining 10 points.
First, create a file named game win.py.
Then, put two lines at the top.

import load
import booleans as bln

Next, outline a function named win.

import load
import booleans as bln

def win ( window , score_image , lives_image ) :


pass

As you can see, this function has three parameters: window, score image,
and lives image.
Lastly, implement the function.
132 Fill in the Gaps

import load
import booleans as bln

def win ( window , score_image , lives_image ) :


load . game_win_sound . play ()
window . blit ( load . metal_png ,(0 ,720) )
score_image . display ( str ( load . score ) )
lives_image . display ( str ( load . lives ) )
load . asteroids = []
bln . button_pressed = True
bln . started_game = False
bln . game_won = True
load . score = -1
14.4 Add Four Functions 133

First, you play a sound. Next, you display the score and the number of
lives on the metal dashboard. Then, you assign an empty list to asteroids
and update three global variables. You also set the score to -1.
The game win.py file is complete.
134 Fill in the Gaps
Chapter 15

Complete the Project

In this chapter, you will use the code written in the last three chapters to
complete the project.

15.1 Update app.py

The remaining steps involve updating app.py, the first Python file you made
for this project.
To start, return to app.py. You should see the following four lines at the
top of the file.

import pygame
pygame . init ()
import load
import image

Below that, add the following lines.


136 Complete the Project

import rocket as rkt


import button
import booleans as bln
import start
import pause
import asteroid as ast
import collide
import gmo
import score
import game_win

Next, you should see the following lines because you have already written
them.

window = pygame . display . set_mode ((1280 ,790) )

window . blit ( load . background_png ,(0 ,0) )


window . blit ( load . metal_png ,(0 ,720) )
window . blit ( load . start_png ,(10 ,730) )

Recall that you created the game’s window with the set mode function.
You also added three images to the game’s window.
Next, you should see the following code.

p_1 = (1232 ,752)


p_2 = (1220 ,730)
score_image = image . Image ( window , p_1 , load . score_png , p_2 )
p_3 = (1172 ,752)
p_4 = (1160 ,730)
lives_image = image . Image ( window , p_3 , load . lives_png , p_4 )
score_image . display ( str ( load . score ) )
lives_image . display ( str ( load . lives ) )

Recall that you created two instances of the Image class and stored them in
variables named score image and lives image. You also called the display
method on these instances.
Next, add the following code.
15.1 Update app.py 137

rocket = rkt . Rocket ( window , load . rocket_png ,590 ,561)


rocket . draw ()

First, you create an instance of the Rocket class. Then, you call the draw
method to add an image of a rocket to the game’s window.
At this point, the initial configuration for the images is set. You should
see the following line of code.

pygame . display . update ()

This code causes images to appear on the game’s window.


Next, add the following lines.

clock_one = pygame . time . Clock ()


start_time_one = pygame . time . get_ticks ()
clock_two = pygame . time . Clock ()
start_time_two = pygame . time . get_ticks ()

First, you create a clock with the time module from the pygame library.
Then, you use a function named get ticks, which returns a time value in
milliseconds. You assign this value to a variable named start time one. You
write similar code for a second clock.
Next, add these two lines.

start_button = button . Button (10 ,730 , load . start_png )


pause_button = button . Button (10 ,730 , load . pause_png )

You use the button module to create two instances of the Button class. You
store these instances with variables named start button and pause button.
Next, you should see the following code.

running = True
while running :

This code marks the beginning of a “while loop.”


138 Complete the Project

The remaining code goes in the body of the “while loop”. Spaces and
indentations matter in Python, so be sure to indent correctly. In Python,
four spaces correspond to one indentation. In Visual Studio, if you highlight
code and press the “tab” key, the highlighted code automatically indents. To
un-indent, highlight the code and simultaneously press the “shift” and “tab”
keys.
In the first line of the “while loop,” add the following code. Indent with
four spaces.

window . blit ( load . background_png ,(0 ,0) )

Below that, add the following “if statements” to the “while loop.” Indent
the first line with four spaces and the second with eight spaces. Similarly,
indent the third line with four spaces and the fourth line with eight spaces.

if bln . game_over :
window . blit ( load . game_over_png ,(0 ,0) )
if bln . game_won :
window . blit ( load . game_win_png ,(0 ,0) )

In the first line, you check whether the game over variable is True. If it is,
you add an image to the window. Also, you check if the game won variable is
True. If so, you add a different image to the window.
The “while loop” completes iterations so quickly that multiple iterations
complete as the user performs one button tap. The button pressed variable
exists so that one button tap actually functions like a single tap. With this in
mind, add the following code to the body of the “while loop.” Indent the first
line with four spaces.
15.1 Update app.py 139

if ( not bln . started_game ) and ( not bln . button_pressed ) :


if start_button . left_click () :
start . start ( window )
elif ( bln . started_game ) and ( not bln . button_pressed ) :
if pause_button . left_click () :
pause . pause ( window )
elif pygame . mouse . get_pressed () [0] == False :
if ( not bln . game_over ) and ( not bln . game_won ) :
bln . button_pressed = False
else :
pass

If started game is False and button pressed is False, another “if state-
ment” is encountered. In particular, if the user left-clicked the start button,
you call the start function from the start module.
For the first elif, you check two variables. If started game is True and
button pressed is False, another “if statement” is encountered. If the user
left-clicked the pause button, you call the pause function from the pause
module.
For the second elif, you check if the left button on a mouse is not
pressed. If so, you check the game over and game won variables within an
“if statement.” If game over is False and game won is False, you reset the
button pressed variable to False. This reset ensures that a button can be
pressed more than once during the game.
Next, add the following line. You should indent this line with four spaces.

current_time = pygame . time . get_ticks ()

Here, you set a variable named current time to the value returned by the
get ticks function.
Next, add the following code to the “while loop.” Indent the first line with
four spaces.
140 Complete the Project

difference_one = current_time - start_time_one


if difference_one >= 1000 or len ( load . asteroids ) == 0:
start_time_one = current_time
if bln . started_game == True :
ast . create_asteroid ( window )
if current_time - start_time_two >= 10:
start_time_two = current_time
if bln . started_game == True :
for asteroid in load . asteroids :
asteroid . translate_down ()

In the first line, you subtract start time one from current time and
assign the difference to a variable named difference one. If this difference
is greater than or equal to 1000 milliseconds or the asteroids variable stores
an empty list, current time is assigned to start time one, and another “if
statement” is encountered. In particular, if started game is True, you call
the create asteroid function. In summary, you create an instance of the
Asteroid class every 1000 milliseconds if certain conditions are met.
Next, if current time minus start time two is greater than or equal to
10 milliseconds, current time is assigned to start time two, and another “if
statement” is encountered. If started game is True, a “for loop” runs. During
each iteration, you call the translate down method from the Asteroid class.
In short, you translate an image of an asteroid every 10 milliseconds if certain
conditions are met.
Now, ensure that you have the following code in the body of the “while
loop.” The first line should be indented with four spaces.

for event in pygame . event . get () :


if event . type == pygame . QUIT :
running = False

This code causes the game’s window to close if the user presses the close
button.
In this game, the user can move the rocket with the ‘A’ and ‘D’ keys.
To incorporate this keyboard input, add the following code to the “for loop.”
Ensure that the “if statements” involving pygame.QUIT and pygame.KEYDOWN
are indented in the same way.
15.1 Update app.py 141

if event . type == pygame . KEYDOWN and bln . started_game :


if event . key == pygame . K_a :
rocket . translate_left ()
elif event . key == pygame . K_d :
rocket . translate_right ()

The above code is for translating the rocket to the right and to the left. If
a key is pressed and started game is True, an “if...elif statement” is encoun-
tered. In particular, if the ‘A’ key was pressed, you call the translate left
method on the instance stored with rocket. After the word elif, you check
if the ‘D’ key was pressed. If so, you call the translate right method on
rocket.
Next, add the following “if statement” to the “while loop”. Indent the first
line with four spaces. This “if statement” should not be in the previous “for
loop.”

if ( not bln . game_over ) and ( not bln . game_won ) :


rocket . draw ()

If game over and game won are False, you call the draw method on rocket
to add an image of a rocket to the game’s window.
Next, add the following code to the body of the “while loop.” Indent the
first line with four spaces.

for asteroid in load . asteroids :


if asteroid . y < 649:
asteroid . draw ()
if rocket . collision ( asteroid ) :
if load . lives >= 2:
collide . collide ( lives_image , asteroid )
else :
gmo . gmo ( window , score_image , lives_image )
else :
score . increase_score ( asteroid , score_image )

There is a “for loop” to access each instance in the list stored by asteroids.
Within the body of this “for loop”, there is an “if...else statement.” If the
y coordinate of an asteroid’s image is less than 649, the asteroid can still
collide with the rocket. Otherwise, the asteroid’s image has reached the metal
142 Complete the Project

dashboard. In this case, the user gets a point.


Suppose the y coordinate of an asteroid’s image is less than 649. In this
case, the draw method is called on asteroid, and another “if statement” is
encountered. In particular, if the asteroid collided with the rocket, additional
code is executed. This code consists of an “if...else statement.” If the number
of lives is greater than or equal to 2, you call the collide function from the
collide module. Otherwise, you call the gmo function from the gmo module.
To be clear, the name gmo is short for game over.
Next, add the following “if statement” to the “while loop.” Indent the first
line with four spaces.

if load . score >= 10 and load . score != -1:


game_win . win ( window , score_image , lives_image )

If the user’s score is greater than or equal to 10 and the user’s score is not
-1, you call the win function from the game win module.
Lastly, add the following line to the “while loop.” Indent this line with four
spaces.

pygame . display . update ()

You call the update function so that the newest images appear on the
game’s window.
That’s all the code for the game. Congratulations!

15.2 Final Version of app.py


Here is the final version of app.py.
15.2 Final Version of app.py 143

import pygame
pygame . init ()
import load
import image

import rocket as rkt


import button
import booleans as bln
import start
import pause
import asteroid as ast
import collide
import gmo
import score
import game_win

window = pygame . display . set_mode ((1280 ,790) )

window . blit ( load . background_png ,(0 ,0) )


window . blit ( load . metal_png ,(0 ,720) )
window . blit ( load . start_png ,(10 ,730) )

p_1 = (1232 ,752)


p_2 = (1220 ,730)
score_image = image . Image ( window , p_1 , load . score_png , p_2 )
p_3 = (1172 ,752)
p_4 = (1160 ,730)
lives_image = image . Image ( window , p_3 , load . lives_png , p_4 )
score_image . display ( str ( load . score ) )
lives_image . display ( str ( load . lives ) )

rocket = rkt . Rocket ( window , load . rocket_png ,590 ,561)


rocket . draw ()

pygame . display . update ()

clock_one = pygame . time . Clock ()


start_time_one = pygame . time . get_ticks ()
clock_two = pygame . time . Clock ()
start_time_two = pygame . time . get_ticks ()

start_button = button . Button (10 ,730 , load . start_png )


pause_button = button . Button (10 ,730 , load . pause_png )

running = True
while running :
window . blit ( load . background_png ,(0 ,0) )
144 Complete the Project

if bln . game_over :
window . blit ( load . game_over_png ,(0 ,0) )
if bln . game_won :
window . blit ( load . game_win_png ,(0 ,0) )

if ( not bln . started_game ) and ( not bln . button_pressed ) :


if start_button . left_click () :
start . start ( window )
elif ( bln . started_game ) and ( not bln . button_pressed ) :
if pause_button . left_click () :
pause . pause ( window )
elif pygame . mouse . get_pressed () [0] == False :
if ( not bln . game_over ) and ( not bln . game_won ) :
bln . button_pressed = False
else :
pass

current_time = pygame . time . get_ticks ()

difference_one = current_time - start_time_one


if difference_one >= 1000 or len ( load . asteroids ) == 0:
start_time_one = current_time
if bln . started_game == True :
ast . create_asteroid ( window )
if current_time - start_time_two >= 10:
start_time_two = current_time
if bln . started_game == True :
for asteroid in load . asteroids :
asteroid . translate_down ()

for event in pygame . event . get () :


if event . type == pygame . QUIT :
running = False
if event . type == pygame . KEYDOWN and bln . started_game :
if event . key == pygame . K_a :
rocket . translate_left ()
elif event . key == pygame . K_d :
rocket . translate_right ()

if ( not bln . game_over ) and ( not bln . game_won ) :


rocket . draw ()

for asteroid in load . asteroids :


if asteroid . y < 649:
asteroid . draw ()
if rocket . collision ( asteroid ) :
if load . lives >= 2:
collide . collide ( lives_image , asteroid )
15.2 Final Version of app.py 145

else :
gmo . gmo ( window , score_image , lives_image )
else :
score . increase_score ( asteroid , score_image )

if load . score >= 10 and load . score != -1:


game_win . win ( window , score_image , lives_image )

pygame . display . update ()


146 Complete the Project

To play the game, run the app.py file1 . Good luck!

1
If you encounter errors that are difficult to fix, feel free to download the Python files at
the following location.
https://github.com/python-programming-made-simple/Game
Chapter 16

Conclusion

This book taught you the basics of Python and how to apply them. You started
by opening a shell on your computer. Then, you encountered examples that
solidified your understanding of programming concepts. You thoroughly inves-
tigated data types, functions, and object-oriented programming. Furthermore,
you learned how to utilize modules and libraries. In the final chapters, you
followed a tutorial for creating an interactive game based on a library. There
are more libraries out there. Now, you have the knowledge and tools to make
your own projects.
148 Conclusion
Chapter 17

Bibliography
150 Bibliography
Bibliography

[1] 3.12.2 documentation. URL: https://docs.python.org/3/.

[2] Built-in functions. URL: https://docs.python.org/3/library/functions.html.

[3] Built-in types. URL: https://docs.python.org/3/library/stdtypes.html.

[4] classes. URL: https://docs.python.org/3/tutorial/classes.html.

[5] cmath — Mathematical functions for complex numbers. URL: https://docs.


python.org/3/library/cmath.html.

[6] Data structures. URL: https://docs.python.org/3/tutorial/datastructures.


html.

[7] Data types. URL: https://docs.python.org/3/library/datatypes.html.

[8] Execute commands and run tools in Terminal on Mac.


URL: https://support.apple.com/guide/terminal/
execute-commands-and-run-tools-apdb66b5242-0d18-49fc-9c47-a2498b7c91d5/
mac.

[9] Homebrew. URL: https://brew.sh/.

[10] IBM documentation. URL: https://www.ibm.com/docs/en/zos/2.1.0?topic=


directories-working-directory.

[11] Installing Python modules. URL: https://docs.python.org/3/installing/index.


html.

[12] math — Mathematical functions. URL: https://docs.python.org/3/library/


math.html.

[13] More control flow tools. URL: https://docs.python.org/3/tutorial/


controlflow.html.

[14] NumPY Documentation. URL: https://numpy.org/doc/.


152 BIBLIOGRAPHY

[15] numpy.linspace — NumPy v1.26 Manual. URL: https://numpy.org/doc/


stable/reference/generated/numpy.linspace.html.

[16] pandas documentation — pandas 2.2.1 documentation. URL: https://pandas.


pydata.org/docs/.

[17] pip documentation v24.0. URL: https://pip.pypa.io/en/stable/.

[18] Programming FAQ. URL: https://docs.python.org/3/faq/programming.html.

[19] Programming FAQ. URL: https://docs.python.org/3/faq/programming.


html#what-are-the-rules-for-local-and-global-variables-in-python.

[20] Pygame Front Page — pygame v2.6.0 documentation. URL: https://www.


pygame.org/docs/.

[21] Python and Virtual Environments — Department of Computer Science Com-


puting Guide. URL: https://csguide.cs.princeton.edu/software/virtualenv#
system.

[22] Python Array Length. URL: https://www.w3schools.com/python/gloss


python array length.asp.

[23] Python conditions. URL: https://www.w3schools.com/python/python


conditions.asp.

[24] Python data Types. URL: https://www.w3schools.com/python/python


datatypes.asp.

[25] Python Data Types (With Examples). URL: https://www.programiz.com/


python-programming/variables-datatypes.

[26] Python Dictionaries. URL: https://www.w3schools.com/python/python


dictionaries.asp.

[27] Python lists. URL: https://www.w3schools.com/python/python lists.asp.

[28] Python Remove Array item. URL: https://www.w3schools.com/python/


gloss python array remove.asp.

[29] Python String Methods. URL: https://www.w3schools.com/python/python


ref string.asp.

[30] Python variables. URL: https://www.w3schools.com/python/python


variables.asp.

[31] random — Generate pseudo-random numbers. URL: https://docs.python.


org/3/library/random.html.
BIBLIOGRAPHY 153

[32] SciPy documentation — SciPy v1.12.0 Manual. URL: https://docs.scipy.org/


doc/scipy/.

[33] Unlocking the power of memory Address — Lenovo US. URL: https://www.
lenovo.com/us/en/glossary/memory-address/?orgRef=https%253A%252F%
252Fwww.google.com%252F.

[34] venv — Creation of virtual environments. URL: https://docs.python.org/3/


library/venv.html.

[35] Python – Instagram Engineering, 10 2019. URL: https://


instagram-engineering.com/tagged/python.

[36] Welcome to Python.org, 2 2024. URL: https://www.python.org/.

[37] baraltech. EASY way to use SOUNDS in Python/PyGame Projects, 5 2021.


URL: https://www.youtube.com/watch?v=3Yhhzflmxfs.

[38] Python Basics. Python Basics PyGame Clock Tick Method, 10 2018. URL:
https://www.youtube.com/watch?v=aX4DnBeXa-Y.

[39] buildwithpython. PyGame Tutorial - 6 - Keyboard Input Controls/


Key Pressed Event, 7 2019. URL: https://www.youtube.com/watch?v=
AvV6UxuzH5c.

[40] Clear Code. The ultimate introduction to Pygame, 7 2021. URL: https:
//www.youtube.com/watch?v=AY9MnQ4x3zk.

[41] Josef Cruz. A JR programmer asked me why Google and YouTube


use Python. 6 2022. URL: https://python.plainenglish.io/
a-jr-programmer-asked-me-why-google-and-youtube-use-python-f472baf1bab2.

[42] Spotify Engineering. How we use Python at Spotify - Spotify Engi-


neering, 1 2021. URL: https://engineering.atspotify.com/2013/03/
how-we-use-python-at-spotify/.

[43] freeCodeCamp.org. Harvard CS50’s Introduction to Programming with


Python – Full University Course, 5 2023. URL: https://www.youtube.com/
watch?v=nLRL NcnK-4.

[44] GfG. Logical Operators in Python with Examples, 12 2023. URL: https:
//www.geeksforgeeks.org/python-logical-operators/.

[45] GfG. Python if else statements conditional statements, 12 2023. URL: https:
//www.geeksforgeeks.org/python-if-else/.

[46] GfG. Python Initialize empty array of given length, 3 2023. URL: https:
//www.geeksforgeeks.org/python-initialize-empty-array-of-given-length/.
154 BIBLIOGRAPHY

[47] GfG. Python data Types, 1 2024. URL: https://www.geeksforgeeks.org/


python-data-types/.

[48] NeuralNine. Virtual Environments in Python - crash course, 6 2022. URL:


https://www.youtube.com/watch?v=IAvAlS0CuxI.

[49] NeuralNine. Clean New Projects with venv - Virtual Environments, 8 2023.
URL: https://www.youtube.com/watch?v=sUKgrSHSHtM.

[50] Max on Tech. Collisions in Pygame!, 8 2020. URL: https://www.youtube.


com/watch?v=6LF4k-uc75c.

[51] Python Programmer. How to install Python - the right way, 6 2022. URL:
https://www.youtube.com/watch?v=YKSpANU8jPE.

[52] Pygame. pygame/docs/reST/ref at main · pygame/pygame. URL: https:


//github.com/pygame/pygame/tree/main/docs/reST/ref.

[53] Real Python. Scripts, modules, packages, and libraries. URL: https:
//realpython.com/lessons/scripts-modules-packages-and-libraries/.

[54] Real Python. Python Modulo in practice: How to use the URL: https://
realpython.com/python-modulo-operator/.

[55] Real Python. Variables in Python, 12 2023. URL: https://realpython.com/


python-variables/.

[56] Real Python. Conditional statements in Python, 1 2024. URL: https://


realpython.com/python-conditional-statements/.

[57] Robinharwood. Windows commands, 4 2023. URL: https://learn.


microsoft.com/en-us/windows-server/administration/windows-commands/
windows-commands.

[58] Coding With Russ. PyGame Beginner tutorial in Python - Adding buttons, 5
2021. URL: https://www.youtube.com/watch?v=G8MYGDf 9ho.

[59] Coding With Russ. Creating and moving rectangles in PyGame - be-
ginner tutorial, 2 2023. URL: https://www.youtube.com/watch?v=
BwWHXN2rZHQ.

[60] Coding With Russ. Displaying text on the screen in PyGame - Beginner
tutorial, 2 2023. URL: https://www.youtube.com/watch?v=ndtFoWWBAoE.

[61] Coding With Russ. Pygame event Handler explained, 1 2023. URL: https:
//www.youtube.com/watch?v=KR2zP6yuWAs.
BIBLIOGRAPHY 155

[62] Corey Schafer. Python tutorial for beginners 1: Install and setup for
Mac and Windows, 5 2017. URL: https://www.youtube.com/watch?v=
YYXdXT2l-Gg.

[63] Corey Schafer. Python Tutorial: VENV (Mac Linux) - How to Use Virtual
Environments with the Built-In venv Module, 4 2019. URL: https://www.
youtube.com/watch?v=Kg1Yvry Ydk.

[64] Corey Schafer. Python Tutorial: VENV (Windows) - How to Use Virtual
Environments with the Built-In venv Module, 4 2019. URL: https://www.
youtube.com/watch?v=APOPm01BVrk.

[65] Kevin Stratvert. Python for Beginners Tutorial, 3 2021. URL: https://www.
youtube.com/watch?v=b093aqAZiPU.

[66] Tony Teaches Tech. 3 ways to install Python 3 on Mac, 11 2022. URL: https:
//www.youtube.com/watch?v=NmB1AwF3G3k.
156 BIBLIOGRAPHY
Chapter 18

Index
Index

abs, 51 color, 101


addition, 21 command, 5
algorithm, 81 Command Prompt, 6
and, 37 comment, 50
applications, 1 comparison operator, 31, 35
arbitrary, 50 complex, 17
argument, 49, 51, 61, 62 concatenation, 26, 52
example of, 96 condition, 40, 41
arithmetic operation, 21, 41 conditional statement, 38
as, 81, 83 control flow, 31
assign, 41 Control Panel, 7, 9
attribute, 53, 57, 58, 67
convention, 59 data, 15, 50, 53, 60
inherit, 65 data structure, 43
data type, 15
block of code, 49 bool, 19
body, 49, 121, 138 complex, 17
Boolean, 19 float, 16
Boolean expression, 33, 36, 38–40 int, 16
built-in classes, 63 NoneType, 19
int, 63 str, 18
str, 63 def, 50, 55
built-in data types, 15 dictionary, 45
bool, 19 add, 47
complex, 17 key, 45
float, 16 modify, 46
int, 16 value, 45
NoneType, 19 division, 24
str, 18
built-in functions, 51 element, 43, 45
abs, 51 elif, 40
input, 51 else, 39, 40
len, 140 empty list, 95, 129
print, 51 empty string, 29
built-in modules, 75 equal to, 31
math, 75 exponentiation, 26
random, 75 expression, 33
extension, 12
character, 27
child class, 65, 66, 69, 71, 72 False, 19
example of, 104 file, 12
class, 53, 82 float, 16
body of, 53 folder, 12, 75, 88
defining attributes, 53 for, 41
example of, 99 for loop, 41
init method, 54, 60 example of, 92
instance of, 55 dictionary, 46
method, 54 list, 43
name of, 53, 56, 63 tuple, 45
INDEX 159

from, 81 remove, 127, 131


function, 49, 54 local variable, 50
body of, 49 example of, 123
call, 51 logical and, 37
example of, 117 example of, 139
implement, 49 logical not, 35
input, 50 example of, 139
name of, 49 logical operator, 35
output, 50 logical or, 37
example of, 140
global variable, 117, 129 loop, 40
greater than, 32
greater than or equal to, 33 math, 75, 80
memory, 15, 20, 28, 57
has a, 54 memory address, 57
homebrew, 7, 9 method, 54, 61, 71, 72
call, 61, 72
if, 38 example of, 112
if statement, 38 inherit, 68, 71
example of, 131 name of, 63
if...elif...else statement, 39 overriding, 72
example of, 139 module, 75, 77, 80
if...else statement, 39 modulo, 25
example of, 125 multiplication, 23
imaginary unit, 17 mutable, 44, 46
immutable, 44
implement, 49, 121 None, 19
import, 80, 82, 83, 135 NoneType, 19
in, 41 not, 35, 36
indented code, 38, 138 not equal to, 32, 35
index, 27, 43 NumPy, 75, 83
infinite loop, 93 linspace, 84
inheritance, 65, 69 numpy.ndarray, 84
example of, 107, 109
init method, 54, 56, 60, 70 object, 55, 57
example of, 100 object-oriented programming, 53, 65
inherit, 68 operands, 21
input, 49, 51 operation, 21
instance, 55, 57, 61 operator, 21
attribute, 57 operator overloading, 27
create, 55, 57 or, 37
example of, 103 output, 49, 51, 52
integer, 16 overriding a method, 72
integrated development environment, 11
is a, 65 package, 75
iteration, 41, 92, 138, 140 pandas, 75
parameter, 49, 50, 55, 61, 62
key, 45 example of, 123, 125
keyword, 19, 31 parent class, 65, 67, 72
example of, 107
len, 29, 140 pass, 53, 127, 139
less than, 33 PATH, 10
less than or equal to, 34 path, 88
library, 1, 75, 76, 78, 79, 83, 89 pip, 76, 79, 83
list, 43 install, 76
append, 44, 123 version of, 76
example of, 95 pixel, 108
index, 43 print, 38, 51
length of, 140 program, 9
modify, 44 programming practice, 49, 54
160 INDEX

project, 12, 76, 88 subtraction, 22


prompt, 52 super, 70
pygame, 89 syntax error, 35
display module, 91
set mode function, 91 terminal, 6
update function, 103, 142 time, 137
event module, 92 True, 19
get function, 92 truth table, 36, 37
Font class, 100 tuple, 44
render method, 101 example of, 96, 101
font module, 100 index, 45
SysFont function, 100 type, 16, 63
image module, 95
load function, 95 user, 52
mixer module, 95 input, 52
Sound class, 95 output, 52
mouse module, 110
get pos function, 110 value, 45
get pressed, 139 variable, 15, 20, 34, 41, 53
get pressed function, 112 global, 117
Rect class, 110, 123 local, 50
collidepoint method, 111 storing an instance with, 56
colliderect method, 123 venv, 77
topleft attribute, 111 virtual environment, 76, 77
Sound class Visual Studio, 11, 88
play method, 119, 121, 127
Surface class, 95, 101, 110 while, 40
blit method, 95, 107 while loop, 40
get rect, 123 example of, 92
get rect method, 110 working directory, 88
time module
get ticks function, 137 zfill, 101
Python, 5
built-in classes, 63
built-in data types, 15
built-in functions, 51
built-in modules, 75
file, 12
run, 13, 146
install, 9
interpreter, 10, 21
script, 13
uninstall, 8
version of, 8

random, 75, 121


remainder, 25
requirements.txt, 79
return, 49, 50

self, 54, 56, 58, 61, 107


shell, 5, 13, 88
software, 7, 76
str, 103
string, 18, 20
concatenate, 27
index, 27
length, 28
slice, 29
string operation, 26

You might also like