Sanet - ST B0CZ4JHLCY
Sanet - ST B0CZ4JHLCY
Made Simple
Learn Progressively with Self-Contained Code
⋄⋄⋄
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.
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
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
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
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
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
16 Conclusion 147
17 Bibliography 149
18 Index 157
Chapter 1
Introduction
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.
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.
The process for opening a shell depends on the type of computer that you are
using.
6 How to Run Python Code
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.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.
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
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.1 Mac
Suppose you want to uninstall Python 3.9. To do this, run the following
command in the terminal.
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.1 Mac
On a Mac, run this command in the terminal.
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!
python3 .12
>>>
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.
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
https://visualstudio.microsoft.com/downloads/
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.
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.
Method 1
First, run the following command in a shell. Note that Visual Studio has a
built-in shell.
cd Desktop
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.
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
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.
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.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.
Then, run the Python file. You should see the following output.
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.
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.
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.
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.
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.
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.
The output comprises angle brackets, the word class, and str surrounded
by single quotes.
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?
The above code outputs angle brackets, the word class, and the word
bool surrounded by single quotes.
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?
The output indicates that the data type of the keyword None is 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
my_variable = 5
my_variable = 5
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.
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
>>> 2 + 3
The operands are the integers 2 and 3. The result of this arithmetic oper-
ation is 5, which is another integer.
>>> 2.0 + 3
5.0
>>> 2 + 3.0
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
1.0
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
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
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
>>> 1/2
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
2.0
>>> 10 / 5.0
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
>>> 8 % 6
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
‘ hello world ! ’
You can generate the same output by concatenating the following two
strings.
‘ 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.
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.
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 ’
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
Since an empty string contains no characters within the outer quotes, the
length of an empty string is 0.
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 ’
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.1 Equal To
You can compare two quantities with the == operator. What happens when
the operands are 10 and 9?
>>> 10 == 9
False
32 Control Flow
>>> 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
>>> 0 == -0
True
>>> 2 != 3
True
False
⋄⋄⋄
>>> 10 >= 10
True
>>> -5 < 0
True
>>> 7 <= 7
The left side equals the right side, and the Boolean expression evaluates to
True.
True
⋄⋄⋄
1. not
2. and
3. or
>>> 2 not = 3
SyntaxError
Here is how to use the “logical not” operator correctly. First, consider the
following variables and values.
False
You may have realized that the previous example had two Boolean expres-
sions.
1. 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.
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.
Figure 5.3: The truth table for the “logical and” operator.
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.
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.
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
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.”
x = 0
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.
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.
my_list = [ " A " , " B " , " C " , " D " , " E " ]
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 " ]
my_list = [ " A " , " B " , " C " , " D " , " E " ]
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 " ]
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
my_tuple = ( " A " , " B " , " C " , " D " , " E " )
my_tuple = ( " A " , " B " , " C " , " D " , " E " )
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 "
}
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 "
}
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 " ,
" Bob " : " B " ,
" Chris " : " C " ,
" David " : " D "
}
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.
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 .
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
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
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 is an example of how to use the input function to get input from the
user.
When the above code runs, the following prompt appears in the shell.
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
If you type the name Bob in the shell and press the Enter key, Python
displays the following text.
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
class MyClass :
pass
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.
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.
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.
Using a class entails creating an instance of that class. You can create more
than one instance of the same class.
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.
⋄⋄⋄
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 ()
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.
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
class Car :
color = " red "
make = " BMW "
def __init__ ( self ) :
print ( self . color )
def drive ( self ) :
print ( " driving ! " )
my_car = Car ()
red
The word self was used within the body of the init method to access
the data stored with an instance’s 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
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".
class Car :
def __init__ ( self , color , make ) :
self . color = color
self . make = make
def drive ( self ) :
print ( " driving ! " )
1. The attributes named color and make are not defined in the first two
lines of the class.
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
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 ! " )
After running this code, the following text is displayed in the shell.
Using this convention, the data stored by a given attribute differs from one
instance to another.
8.2 Using a Class 61
class Car :
def __init__ ( self , color , make ) :
self . color = color
self . make = make
def drive ( self ) :
print ( " A " , self . make , " is driving ! " )
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 ! " )
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 )
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.
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.
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
Inheritance
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 "
dolphin = Dolphin ()
print ( dolphin . habitat )
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.
class Mammal :
habitat = " ocean "
monkey = Monkey ()
mammal = Mammal ()
This code successfully customizes the data stored with the habitat at-
tribute for the child class without affecting the parent class.
class Mammal :
habitat = " ocean "
monkey = Monkey ()
mammal = Mammal ()
print ( monkey . fur_color )
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
Like the inheritance of attributes, a child class can inherit methods from a
parent class.
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 " )
monkey = Monkey ()
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
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.
class Mammal :
def __init__ ( self , habitat ) :
self . habitat = habitat
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
forest
30 inches
lake
9.2 Inheritance of Methods 71
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 ! " )
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.
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 " )
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
class Mammal :
def __init__ ( self , habitat ) :
self . habitat = habitat
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
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.
pip -- version
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.
cd Desktop
cd my_project
In the next section, you will create a virtual environment in the correct
location.
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.
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.
Mac
If you are using a Mac, you can activate a virtual environment as follows.
Windows
If you are using Windows, you can activate a virtual environment like this.
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
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.
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.
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.
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.
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.
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.
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
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.
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
Here, the custom name is mm. After running the code, the float 2.0 is
displayed.
82 Modules and Libraries
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 ( " * " )
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.
⋄⋄⋄
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
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.
As you can see, the init method for the Star class was called.
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
import numpy as np
84 Modules and Libraries
import numpy
a = 0
b = 10
N = 4
print ( a )
Make a Game
Chapter 11
Start a Project
11.2.1 Mac
pwd
11.2.2 Windows
cd
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
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
pygame . init ()
python app . py
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 ()
running = True
while running :
for event in pygame . event . get () :
if event . type == pygame . QUIT :
running = False
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.
import pygame
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.
⋄⋄⋄
import pygame
pygame . init ()
import load # add this line !
running = True
while running :
for event in pygame . event . get () :
if event . type == pygame . QUIT :
running = False
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.
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.”
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.”
import pygame
pygame . init ()
import load
window = pygame . display . set_mode ((1280 ,790) )
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.
Write Classes
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
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
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.
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.
Notice the use of attributes. These attributes are accessed with the word
self.
Now, use the blit method again.
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
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.
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
running = True
while running :
for event in pygame . event . get () :
if event . type == pygame . QUIT :
running = False
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
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.
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
import game_object
import game_object
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
import game_object
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
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.
import pygame
import pygame
class Button :
def __init__ ( self ,x ,y , image ) :
pass
def left_click ( self ) :
pass
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
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
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.
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.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.
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 load
import random
import game_object
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
import load
import random
import game_object
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.
import game_object
import game_object
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.
import load
import load
import load
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.
import load
import booleans as bln
import load
import booleans as bln
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
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.
import load
import load
import load
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.
import load
import booleans as bln
import load
import booleans as bln
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
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
In this chapter, you will use the code written in the last three chapters to
complete the project.
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
Next, you should see the following lines because you have already written
them.
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.
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
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.
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.
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 :
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.
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 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.
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
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.
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
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 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.
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
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.
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!
import pygame
pygame . init ()
import load
import image
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) )
else :
gmo . gmo ( window , score_image , lives_image )
else :
score . increase_score ( asteroid , score_image )
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
[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.
[38] Python Basics. Python Basics PyGame Clock Tick Method, 10 2018. URL:
https://www.youtube.com/watch?v=aX4DnBeXa-Y.
[40] Clear Code. The ultimate introduction to Pygame, 7 2021. URL: https:
//www.youtube.com/watch?v=AY9MnQ4x3zk.
[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
[49] NeuralNine. Clean New Projects with venv - Virtual Environments, 8 2023.
URL: https://www.youtube.com/watch?v=sUKgrSHSHtM.
[51] Python Programmer. How to install Python - the right way, 6 2022. URL:
https://www.youtube.com/watch?v=YKSpANU8jPE.
[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/.
[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