Py101 Sample
Py101 Sample
2nd Edition
Michael Driscoll
This book is for sale at http://leanpub.com/py101
This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing
process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and
many iterations to get reader feedback, pivot until you have the right book and build traction once
you do.
Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Part I - The Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Part II - Intermediate Materials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Part III - Tutorials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Part IV - Python Packaging and Distribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Target Audience . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
Requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Book Source Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Reader Feedback . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Errata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Afterword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Ethan Furman
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Martin Breuss
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Acknowledgments
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Introduction
Welcome to the 2nd Edition of Python 101! The original Python 101 came out in the summer of
2014 and was written with Python 3.5 in mind. The 2nd Edition of this book has been completely
updated and rearranged for the latest version of Python, which at the time of writing is 3.8.
Some publishers / authors will only do minor updates when creating a new edition of a book. That
is not how I roll. I have personally gone through the entire book and updated every single chapter.
I have removed content that was either no longer relevant or could lead to confusion to readers. I
have also added several new chapters to the book that cover such things as using version control
and setting up projects.
Many programming books will only teach you the basics of the language. With Python 101, the
goal is to help you not only learn the basics of the language but to go beyond the basics and dig into
some intermediate level material. The reason for this is that you usually need to know more than
the basics to create something valuable.
Because of this, the book will be split up into the following four parts:
• Virtual environments
• Type hinting
• Threads and Processes
• Debugging
• Decorators
• Code profiling
• Basic testing
These topics cover some intermediate level Python and also help you learn some key software
development skills, like knowing how to debug your code, add basic unit tests, and use version
control.
By the end of this section, you should be able to confidently distribute your code all on your own!
Introduction 5
Target Audience
This book is written for people that have used other programming languages or taken some computer
science or related classes. While this book won’t handhold you through all the terminology, it will
help you learn how to use Python effectively. It also covers some intermediate level topics that most
beginner books do not.
Conventions
All technical books have their own conventions for how things are presented. In this book, new
topics will be in bold. When referring to Python related keywords or code in a sentence, they will
be in monospace.
Code blocks will look like this:
There will also be blocks of code that represent Python’s interactive interpreter, also known as a
REPL:
Introduction 6
Requirements
You will need the Python language to follow along in this book. See chapter 1 for installation details
or go get the official Python distribution for free at:
• http://python.org/download/
If you need anything beyond what comes with Python, the chapter will tell you how to install it.
• https://github.com/driscollis/python101code
Reader Feedback
If you enjoyed the book or have any other kind of feedback, I would love to hear from you. You can
contact me at the following:
Errata
I try my best not to publish errors in my writings, but it happens from time to time. If you happen
to see an error in this book, feel free to let me know by emailing me at the following:
* [email protected]
Now let’s get started!
Part I - The Python Language
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 1 - Installing Python
Depending on which operating system you are using, you may need to install the Python program-
ming language. This chapter will cover the primary ways to install Python.
First of all, there are several different versions of Python, which are called “distributions”. A
distribution is a word used to describe a collection of software. A Python distribution will include
the core Python language at a minimum and sometimes include extra 3rd party libraries.
The official version is called Python or CPython and you can get it from the following:
• https://www.python.org/
Another popular distribution of Python is called Anaconda and comes from the Anaconda company.
This variation of Python is focused on data science and includes many additional 3rd party packages
in addition to Python’s standard library. You can read more about it here:
• https://www.anaconda.com/
Anaconda is designed to use a command-line tool called conda for installing additional packages
whereas Python uses pip, although you can also use pip with Anaconda. Also note that the Anaconda
download is much larger than the official Python one is because it has so many extra packages
included with it.
If you are on a Windows PC and don’t have administrator privileges on your machine, then you
might want to check out WinPython, which can be run from a USB:
• https://winpython.github.io/
There are many other Python distributions to choose from. You can see a bunch more here:
• https://wiki.python.org/moin/PythonDistributions
This book is focused on Python 3. The current version at the time of writing is Python 3.8. It is
recommended that you use the official Python distribution rather than Anaconda, although the
examples in this book should work for both. Any examples that use a specific feature only found in
3.8 or newer will be noted as such.
There are 32-bit and 64-bit distributions of Python. If you are unsure what your computer uses, you
should opt for the 32-bit version if that is available. Newer Macs no longer support 32-bit, so in that
case you only have one choice.
Chapter 1 - Installing Python 9
Installing on Windows
The https://www.python.org/ website has a download section where you can download an installer
for Python.
After the installer is downloaded, double-click it and go through the installation wizard. Here is the
first screen you should see:
There is a checkbox in the wizard for adding Python to the path. If you don’t have an older version
of Python already installed or if you want to use the latest as your default Python, then I recommend
that you check that checkbox. It is unchecked by default, as shown in the image above.
If you install Python to your path, it will allow you to run Python from the command line
(cmd.exe) or Powershell by just typing python. If you install Python using the Windows Store, it
will automatically add Python to your path.
The next page of the installation wizard allows you to enable or disable optional features:
Chapter 1 - Installing Python 10
You can leave the defaults enabled, but if you are short on space, you should untick the “Python Test
Suite” option. The next page of the wizard will allow you to enable Advanced Options:
Chapter 1 - Installing Python 11
Here you can install Python for all users of the machine. You can also associate Python files with
Python, create shortcuts, add Python to your environment and more. Most of the time, the defaults
will be fine. However it’s a good idea to go ahead and check the “Precompile standard library” as
that can make Python run better on your machine.
When you press Next here, you will probably get a warning from Window’s User Access Control:
Chapter 1 - Installing Python 12
This is a verification step that asks if you really want to proceed with installing Python. Go ahead
and press Yes. Now Python is being installed:
Chapter 1 - Installing Python 13
Once the install finishes, you will see this final dialog:
Chapter 1 - Installing Python 14
You now have Python installed on your Windows machine! Try running Python by opening
cmd.exe:
You should see something like the above. To exit, you can press CTRL+D on Linux and Mac, CTRL+Z
on Windows, or type exit() on any platform and press Enter.
Chapter 1 - Installing Python 15
Installing on Mac
Macs usually come with Python pre-installed. However, if you want the latest version of Python,
then you may need to download Python.
The https://www.python.org/ website has a download section where you can also download a
Python installer for Mac. Once downloaded, you will need to double-click it to install Python. You
may need to tell your Mac to allow you to install Python as the system might bring up a dialog box
that warns you about installing programs downloaded from the internet.
Note that the App Store does not have Python in it, so using the Python website is the way to go.
Let’s take a moment to learn how to install Python on a Mac. Here’s the first thing you will see
when you double-click the downloaded pkg file:
This screen basically tells you what you are about to install and that you will need to install some
SSL certificates as well. Go ahead and press Continue:
Chapter 1 - Installing Python 16
This page gives you more information about the SSL certificate as well as general information
about using IDLE and Tkinter on a Mac. IDLE is Python’s built-in code editor. You will learn more
about that in the next chapter. Tkinter is a Python library that you can use to create cross-platform
graphical user interfaces.
Tkinter is the library that is used to create IDLE, the Python editor that comes with Python.
If you are interested, read through the information on this page. Otherwise, go ahead and Continue:
Chapter 1 - Installing Python 17
This is Python’s license agreement page. It also has a little bit of history about Python on it. Feel free
to check it out or skip it and press Continue:
Chapter 1 - Installing Python 18
This page allows you to choose which disk on your computer you want to install Python. I usually
use the default, but if you want you can change it to some other location.
Chapter 1 - Installing Python 19
This page allows you to choose which folder to install Python to, in contrast to the previous page
which lets you pick which disk to install to.
Chapter 1 - Installing Python 20
This page shows the installation as it happens. You can wait and watch Python get installed, or go
get something to drink. Either way, Python will be installed before too long.
Chapter 1 - Installing Python 21
Installing on Linux
Linux also usually comes with Python pre-installed, although it will likely not be the latest version
of Python. The Python website has source downloads and directions that you can use to build the
latest Python for your Linux distribution.
The source download is Python source code with some build scripts included that will allow you to
build and install Python on Linux.
For full instructions, you should read the dev guide:
• https://devguide.python.org/setup/
Sometimes you can also install a pre-built copy of the latest Python using your package manager.
One good source for Python on Linux is the “deadsnakes” PPA. You will need to use Google to find
it, but that makes it much easier to install another version of Python on Linux.
Chapter 1 - Installing Python 22
Android / iOS
You can also run Python on Android and iOS via downloadable applications. Pydroid is a popular
application for Android while Pythonista is one of the popular choices for iOS. Trying to write code
on a phone can be really problematic due to the on-screen keyboards. If you must go this route, you
may want to use a tablet.
• Jython - an implementation of Python written in Java that allows you to use Java code in
Python
• IronPython - an implementation of Python written in .NET
• PyPy - written in RPython, PyPy has a just-in-time (JIT) compiler that makes it much faster
than regular Python
The main reason for trying out these other implementations of Python is for speed or flexibility. For
example, if you are already familiar with .NET or Java, then you might find IronPython or Jython a
bit easier to jump into. Another reason to use Jython or IronPython is because you have pre-existing
code in Java or .NET that you still need to use with Python.
In the case of PyPy, I usually recommend it if you have a slow Python program and you need a
simple way to speed it up. Try running it with PyPy and you might be surprised at the performance
improvement. Note that none of these variants are completely compatible with all of Python’s 3rd
party packages, so if your program uses one it may not work with these variants.
Wrapping Up
Most of the time, installing Python is straight-forward and easy to do. It can get tricky when you
need to have multiple versions of Python installed on your machine at the same time, but if you are
just starting out I think you’ll find the installation process pretty painless.
Chapter 1 - Installing Python 23
Now that you have Python installed, you can congratulate yourself. You have started on a new
endeavor and you have just taken the first step! However, before you try running Python, you may
want to read the next chapter where you will learn about additional tools that will help you get the
most out of your Python adventure!
Chapter 2 - Python Editors
The Python programming language comes with its own built-in Integrated Development Environ-
ment (IDE) called IDLE. The name, IDLE, supposedly came from the actor, Eric Idle, who was a part
of the Monty Python troupe, which is what Python itself is named after.
IDLE comes with Python on Windows and some Linux variants. You may need to install IDLE
separately on your particular flavor of Linux or on Mac if you plan to use the Python that came
with the operating system. You should check out the Python website for full instructions on how to
do so as each operating system is different.
Here are some of the reasons that Integrated Development Environments are useful:
On that last point, breakpoints tell the debugger where to pause execution. Debugging is the process
of going through your code step-by-step to figure out how it works or to fix an issue with your code.
IDLE itself has other attributes that are useful, such as access to Python documentation, easy access
to the source code via the Class Browser, and much more. However, IDLE is not the only way to
code in Python. There are many useful IDEs out there. You can also use a text editor if you prefer.
Notepad, SublimeText, Vim, etc., are examples of text editors. Text editors do not have all the features
that a full-fledged IDE has, but tend to have the advantage of being simpler to use.
Here is a shortlist of IDEs that you can use to program in Python:
• PyCharm
• Wing Python IDE
• VS Code (also called Visual Studio Code)
• Spyder
• Eclipse with PyDev
PyCharm and WingIDE both have free and paid versions of their programs. The paid versions have
many more features, but if you are just starting out, their free offerings are quite nice. VS Code and
Spyder are free. VS Code can also be used for coding in many other languages. Note that to use
VS Code effectively with Python, you will need to install a Python extension. You can also use the
PyDev plugin for Eclipse to program in Python.
Chapter 2 - Python Editors 25
Other popular editors for Python include SublimeText, vim, emacs, and even Notepad++. These
editors may not be 100% up-to-date on the syntax of the language, but you can use them for multiple
programming languages.
But let’s back up a bit and talk about Python’s basic console, also known as the REPL, which stands
for Read Evaluate Print Loop.
Once you have the terminal open you can try typing python. You should see something like this:
Chapter 2 - Python Editors 26
If this doesn’t work and you get an “Unrecognized Command” or some other error, then Python may
not be installed or configured correctly. On Windows, you may need to add Python to your system’s
path or you can just type out the full path to Python in your command console. For example, if you
installed Python in C:\Python\Python38, then you can run it using cmd.exe like you did above, but
instead of typing python, you would type C:\Python\Python38\python.
If you need to get help in the REPL, you can type help():
Chapter 2 - Python Editors 27
You can type live Python code into the REPL and it will be immediately evaluated, which means the
code will run as soon as you press enter.
Here’s how you would print out “Hello World” and add some numbers in the REPL:
Chapter 2 - Python Editors 28
Python comes with its own code editor called IDLE. Let’s learn about that next!
This is a REPL. You can enter code here and it will be evaluated as soon as you press the Return or
Enter key.
If you want to actually write a full program, then you will need to open up the editor view by going
to File –> New.
You should now have the following dialog on your screen:
1 print('Hello World')
To run this code in IDLE, go to the Run menu and choose the first option labeled Run Module:
When you do this, IDLE will switch to the Shell and show you the output of your program, if there
is any:
Chapter 2 - Python Editors 31
You can also use the Run menu’s Check Module option to check your code for syntax errors.
If you’d rather look up how something works in the Python language, then go to the Help menu
and choose Python Docs or press F1 on your keyboard:
Chapter 2 - Python Editors 33
This will show you Python’s official documentation. Depending on your O/S this may load local
help files, or start a browser to show the official on-line help documents.
If you haven’t restarted the shell before, then your screen will look like this:
Module Browser
IDLE comes with a handy tool called the Module Browser. This tool can be found in the File menu.
When you open it, you will see the following:
Chapter 2 - Python Editors 35
Modules in Python are code that the Python core development team has created for you. You can
use the Module Browser to browse the source code of Python itself.
Try entering the following into the dialog above: os. Then press OK.
You should now see the following:
This allows you to browse the source code for os.py. You can double-click anything in the Module
Browser and it will jump to the beginning of where that code is defined in IDLE’s code editor.
Path Browser
Another useful tool that you can use in IDLE is the Path Browser. The Path Browser allows you
to see where Python is installed and also what paths Python uses to import modules from. You will
learn more about importing and modules later on in this book.
You can open it by going to File and then Path Browser:
Chapter 2 - Python Editors 36
The Path Browser is a good way to diagnose issues with importing modules. It can show you that
you might not have Python configured correctly. Or it might show you that you have installed a 3rd
party module in the wrong location.
PyCharm prefers that you work in a project rather than opening a simple file. Projects are typically
collections of related files or scripts. You can set up a new project here or open a pre-existing one.
Once you have gone through that process, your screen should look like this:
Chapter 2 - Python Editors 38
Give the file a name, such as hello.py. Now PyCharm should look like this:
Chapter 2 - Python Editors 39
1 print('Hello PyCharm')
To run your code, go to the Run menu and choose Run. PyCharm might ask you to set up a debug
configuration before running it. You can save the defaults and continue.
You should now see the following at the bottom of PyCharm:
PyCharm Features
PyCharm has tons of features. In fact, it has so many that you could write an entire book on them.
For the purposes of this book, you should know that PyCharm will give you suggestions about your
code based on PEP8, which is Python’s code style guide. You will learn more about that in the next
chapter. It will also highlight many other things about your code.
You can usually hover over any code that looks weird to you and a tooltip will appear that will
explain the issue or warning.
The debugger that ships with PyCharm is useful for figuring out why your code doesn’t work. You
can use it to walk through your code line-by-line.
PyCharm’s documentation is quite good, so if you get stuck, check their documentation.
1 print('Hello Wingware')
Hit OK and the code will run. You will see the output in the Debug I/O tab if there is any.
Note that Wing does not require you to create a project to run a single Python file. You can create
projects if you want to though.
Wing Features
Wing has an incredible debugger. However, you cannot use it to its full extent in the free versions of
the software. But there is a Source Assistant tab in the Personal edition that is very useful. It will
show you information about the functions / modules that you have loaded as you use them. This
makes learning new modules much easier.
Wing will also show you various issues with your code while you type, although PyCharm seems
to do more in this area than Wing does.
Both products have plugins and you can write your own for both IDEs as well.
Under Customize you can see there is an option for installing Python. If that isn’t there, you can
click on the Extensions button that is on the left and search for Python there:
Chapter 2 - Python Editors 44
Go ahead and install the Python extension so that VS Code will recognize Python correctly.
1 print('Hello VS Code')
Then right-click anywhere in the editor and select the Run Python File in Terminal selection. This
will cause your code to run and you will see the following:
Chapter 2 - Python Editors 45
Note: I didn’t have the PSReadline module installed when I ran this code which is why you see the
error in the console above.
VS Code Features
VS Code can run all kinds of different languages. However, for the purposes of Python, Microsoft
has a team of Python developers that are constantly improving this IDE and adding new features.
There are tons of extensions that you can install to enhance the editor’s functionality.
One of the coolest extensions that you can install is Live Share, which lets you do real-time
collaboration between developers. It basically shares your coding session with others. Since this
IDE is the newest of the bunch and its feature set is changing a lot, you will need to research it on
your own time.
Wrapping Up
There are lots of Python code editors to choose from. IDLE is nice in that it comes with Python and
is written in Python, so you can actually learn a lot just by looking at its source code. PyCharm and
VS Code are very popular right now. Wing IDE used to be more popular than it is today, but I think
it is still really great. All of these tools are good, but you should give them a try to see which one
works the best for you.
Chapter 3 - Documenting Your Code
Documenting your code early on is quite a bit more important than most new developers realize.
Documentation in software development refers to the idea of giving your variables, functions and
other identifiers descriptive names. It also refers to adding good comments. When you are immersed
in developing your latest creation, it is easy to create variables and functions with non-descriptive
names. A month or a year later, when you inevitably come back to your code, you will spend an
inordinate amount of time trying to figure out what your code does.
By making your code self-documenting (i.e. using descriptive names) and adding comments when
necessary, you will make your code more readable for yourself and for anyone else who may use
your code. This will make updating your code and refactoring your code easier too!
In this chapter you will learn about the following topics:
• Comments
• Docstrings
• PEP8 - The Python Style Guide
• Other Tools Useful for Documenting Your Code
In the code above, the first line demonstrates how to create a simple comment. When Python goes
to execute this code, it will see the # symbol and ignore all the text that follows it. In effect, Python
will skip that line and try to execute the second line.
This comment is marked as a “bad comment”. While it is good for demonstration purposes, it does
not describe the code that follows it at all. That is why it is not a good comment. Good comments
describe the code that follows. A good comment may describe the purpose for the Python script,
the code line or something else. Comments are your code’s documentation. If they don’t provide
information, then they should be removed.
You can also create in-line comments:
1 x = 10 # 10 is being assigned to x
Here you once again assign 10 to the variable x, but then you add two spaces and the # symbol, which
allows you to add a comment about the code. This is useful for when you might need to explain a
specific line of code. If you named your variable something descriptive, then you most likely won’t
need a comment at all.
Commenting Out
You will hear the term “commenting out code” fairly often. This is the practice of adding the # symbol
to the beginning of your code. This will effectively disable your code.
For example, you might have this line of code:
1 number_of_people = 10
1 # number_of_people = 10
You comment code out when you are trying out different solutions or when you’re debugging your
code, but you don’t want to delete the code. Python will ignore code that is commented out, allowing
you to try something else. Most Python code editors (and text editors) provide a way to highlight
multiple lines of code and comment out or uncomment out the entire block of code.
Chapter 3 - Documenting Your Code 48
Multiline Comments
Some programming languages, such as C++, provide the ability to create multi-line comments. The
Python style guide (PEP8) says that the pound sign is preferred. However, you can use triple quoted
strings as a multiline comment.
Here’s an example:
1 >>> '''This is a
2 multiline comment'''
3 >>> """This is also a
4 multiline comment"""
When you create triple quoted strings you may be creating a docstring.
Let’s find out what docstrings are and how you can use them!
1 """
2 This is a docstring
3 with multiple lines
4 """
Docstrings are ignored by Python. They cannot be executed. However, when you use a docstring as
the first statement of a module, function, etc, the docstring will become a special attribute that can
be accessed via __doc__. You will learn more about attributes and docstrings in the chapter about
classes.
Docstrings may be used for one-liners or for multi-line strings.
Here is an example of a one-liner:
Chapter 3 - Documenting Your Code 49
1 """This is a one-liner"""
1 def my_function():
2 """This is the function's docstring"""
3 pass
The code above shows how you can add a docstring to a function. You can learn more about functions
in chapter 14. A good docstring describes what the function is supposed to accomplish.
Note: While triple double-quotes are the recommended standard, triple single-quotes, single double-
quotes, and single single-quotes all work as well (but single double- and single single-quotes can only
contain one line, not multiple lines).
Now let’s learn about coding according to Python’s style guide.
You can run these tools against your code to help you find issues with your code. I have found Pylint
and PyFlakes / flake8 to be the most useful. Black is helpful if you are working in a team and you
want everyone’s code to follow the same format. Black can be added to your toolchain to format
your code for you.
The more advanced Python IDEs provide some of the checks that Pylint, etc. provide in real-time.
For example, PyCharm will automatically check for a lot of the issues that these tools will find.
WingIDE and VS Code provide some static code checking as well. You should check out the various
IDEs and see which one works the best for you.
Wrapping Up
Python comes with several different ways to document your code. You can use comments to explain
one or more lines of code. These should be used in moderation and where appropriate. You can also
use docstrings to document your modules, functions, methods, and classes.
You should also check out Python’s style guide that can be found in PEP8. This will help you develop
good Python coding practices. There are several other style guides for Python. For example, you
might want to look up Google’s style guide or possibly NumPy’s Python style guide. Sometimes
looking at different style guides will help you develop good practices as well.
Finally, you learned about several tools you can use to help you make your code better. If you have
the time, I encourage you to check out PyFlakes or Flake8 especially as they can be quite helpful in
pointing out common coding issues in your code.
Review Questions
1. How do you create a comment?
• Creating strings
• String methods
• String formatting
• String concatenation
• String slicing
Creating Strings
Here are some examples of creating strings:
1 name = 'Mike'
2 first_name = 'Mike'
3 last_name = "Driscoll"
4 triple = """multi-line
5 string"""
When you use triple quotes, you may use three double quotes at the beginning and end of the string
or three single quotes. Also, note that using triple quotes allows you to create multi-line strings. Any
whitespace within the string will also be included.
Here is an example of converting an integer to a string:
1 >>> number = 5
2 >>> str(number)
3 '5'
In Python, backslashes can be used to create escape sequences. Here are a couple of examples:
• \b - backspace
Chapter 4 - Working with Strings 52
• \n - line feed
• \r - ASCII carriage return
• \t - tab
There are several others that you can learn about if you read Python’s documentation.
You can also use backslashes to escape quotes:
If you did not have the backslash in the code above, you would receive a SyntaxError:
This occurs because the string ends at that second single quote. It is usually better to mix double
and single quotes to get around this issue:
In this case, you create the string using double quotes and put a single quote inside of it. This is
especially helpful when working with contractions, such as “don’t”, “can’t”, etc.
Now let’s move along and see what methods you can use with strings!
String Methods
In Python, everything is an object. You will learn how useful this can be in chapter 18 when you
learn about introspection. For now, just know that strings have methods (or functions) that you can
call on them.
Here are three examples:
Chapter 4 - Working with Strings 53
The method names give you a clue as to what they do. For example, .capitalize() will change the
first letter in the string to a capital letter.
To get a full listing of the methods and attributes that you can access, you can use Python’s built-in
dir() function:
1 >>> dir(name)
2 ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__',
3 '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
4 '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__',
5 '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__',
6 '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__',
7 '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize',
8 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find',
9 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal',
10 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace',
11 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans',
12 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit',
13 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title',
14 'translate', 'upper', 'zfill']
The first third of the listing are special methods that are sometimes called “dunder methods” (AKA
double-underscore methods) or “magic methods”. You can ignore these for now as they are used
more for intermediate and advanced use-cases. The items in the list above that don’t have double-
underscores at the beginning are the ones that you will probably use the most.
You will find that the .strip() and .split() methods are especially useful when parsing or
manipulating text.
You can use .strip() and its variants, .rstrip() and .lstrip() to strip off white space from the
string, including tab and new line characters. This is especially useful when you are reading in a
text file that you need to parse.
In fact, you will often end up stripping end-of-line characters from strings and then using .split()
on the result to parse out sub-strings.
Let’s do a little exercise where you will learn how to parse out the 2nd word in a string.
To start, here’s a string:
Chapter 4 - Working with Strings 54
Now to get the parts of a string, you can call .split(), like this:
1 >>> my_string.split()
2 ['This', 'is', 'a', 'string', 'of', 'words']
The result is a list of strings. Now normally you would assign this result to a variable, but for
demonstration purposes, you can skip that part.
Instead, since you now know that the result is a string, you can use list indexing to get the second
element:
Remember, in Python, lists elements start at 0 (zero), so when you tell it you want element 1 (one),
that is the second element in the list.
When doing string parsing for work, I personally have found that you can use the .strip() and
.split() methods pretty effectively to get almost any data that you need. Occasionally you will
find that you might also need to use Regular Expressions (regex), but most of the time these two
methods are enough.
String Formatting
String formatting or string substitution is where you have a string that you would like to insert into
another string. This is especially useful when you need to create a template, such as a form letter.
But you will use string substitution a lot for debugging output, printing to standard out and much
more.
Standard out (or stdout) is a term used for printing to the terminal. When you run your program
from the terminal and you see output from your program, that is because your program “prints” to
standard out or standard error (stderr).
Python has three different ways to accomplish string formatting:
This book will focus on f-strings the most and also use .format() from time-to-time. But it is good
to understand how all three work.
Let’s take a few moments to learn more about string formatting.
Chapter 4 - Working with Strings 55
In this code, you take the variable name and insert it into another string using the special %s syntax.
To make it work, you need to use % outside of the string followed by the string or variable that you
want to insert.
Here is a second example that shows that you can pass in an int into a string and have it
automatically converted for you:
1 >>> age = 18
2 >>> print('You must be at least %s to continue' % age)
3 You must be at least 18 to continue
This sort of thing is especially useful when you need to convert an object but don’t know what type
it is.
You can also do string formatting with multiple variables. In fact, there are two ways to do this.
Here’s the first one:
In this example, you create two variables and use %s and %i. The %i indicates that you are going to
pass an integer. To pass in multiple items, you use the percent sign followed by a tuple of the items
to insert.
You can make this clearer by using names, like this:
Chapter 4 - Working with Strings 56
When the argument on the right side of the % sign is a dictionary (or another mapping type), then
the parenthesized formats in the string must refer to the keys in the dictionary. In other words, if
you see %(name)s, then the dictionary to the right of the % must have a name key.
If you do not include all the keys that are required, you will receive an error:
For more information about using the printf-style string formatting, you should see the following
link:
https://docs.python.org/3/library/stdtypes.html#printf-style-string-formatting
Now let’s move on to using the .format() method.
1 >>> age = 18
2 >>> name = 'Mike'
3 >>> print('Hello {}. You must be at least {} to continue!'.format(
4 name, age))
5 Hello Mike. You must be at least 18 to continue!
This example uses positional arguments. Python looks for two instances of {} and will insert the
variables accordingly. If you do not pass in enough arguments, you will receive an error like this:
Chapter 4 - Working with Strings 57
This error indicates that you do not have enough items inside the .format() call.
You can also use named arguments in a similar way to the previous section:
1 >>> age = 18
2 >>> name = 'Mike'
3 >>> print('Hello {first_name}. You must be at least {age} to continue!'.format(
4 first_name=name, age=age))
5 Hello Mike. You must be at least 18 to continue!
Instead of passing a dictionary to .format(), you can pass in the parameters by name. In fact, if you
do try to pass in a dictionary, you will receive an error:
This looks a bit weird, but in Python when you see a double asterisk (**) used like this, it means
that you are passing named parameters to the function. So Python is converting the dictionary to
first_name=name, age=age for you.
You can also repeat a variable multiple times in the string when using .format():
Here you refer to {first_name} twice in the string and Python replaces both of them with the
first_name variable.
Because most things in Python start at 0 (zero), in this example you ended up passing the age to {1}
and the name to {0}.
A common coding style when working with .format() is to create a formatted string and save it to
a variable to be used later:
1 >>> age = 18
2 >>> first_name = 'Mike'
3 >>> greetings = 'Hello {first_name}. You must be at least {age} to continue!'
4 >>> greetings.format(first_name=first_name, age=age)
5 'Hello Mike. You must be at least 18 to continue!'
This allows you to reuse greetings and pass in updated values for first_name and age later on in
your program.
You can also specify the string width and alignment:
Left aligned is the default. The colon (:) tells Python that you are going to apply some kind of
formatting. In the first example, you are specifying that the string be left aligned and 20 characters
wide. The second example is also 20 characters wide, but it is right aligned. Finally the ^ tells Python
to center the string within the 20 characters.
If you want to pass in a variable like in the previous examples, here is how you would do that:
1 >>> '{example:^20}'.format(example='centered')
2 ' centered '
Note that the example must come before the : inside of the {}.
At this point, you should be pretty familiar with the way .format() works.
Let’s go ahead and move along to f-strings!
Chapter 4 - Working with Strings 59
Here you create the f-string by putting an “f” right before the single, double or triple quote that
begins your string. Then inside of the string, you use the curly braces, {}, to insert variables into
your string.
However, your curly braces must enclose something. If you create an f-string with empty braces,
you will get an error:
The f-string can do things that neither %s nor .format() can do, though. Because of the fact that
f-strings are evaluated at runtime, you can put any valid Python expression inside of them.
For example, you could increase the displayed value of the age variable:
1 >>> age = 20
2 >>> f'{age+2}'
3 '22'
One other thing that you can’t do is add a comment inside of an expression in an f-string:
In Python 3.8, f-strings added support for =, which will expand the text of the expression to include
the text of the expression plus the equal sign and then the evaluated expression. That sounds kind
of complicated, so let’s look at an example:
This example demonstrates that the text inside of the expression, username= is added to the output
followed by the actual value of username in quotes.
f-strings are very powerful and extremely useful. They will simplify your code quite a bit if you use
them wisely. You should definitely give them a try.
Let’s find out what else you can do with strings!
String Concatenation
Strings also allow concatenation, which is a fancy word for joining two strings into one.
To concatenate strings together, you can use the + sign:
Chapter 4 - Working with Strings 61
Oops! It looks like the strings merged in a weird way because you forgot to add a space to the end
of the first_string. You can change it like this:
Another way to merge strings is to use the .join() method. The .join() method accepts an iterable,
such as a list, of strings and joins them together.
This will make the strings join right next to each other, just like + did. However, you can put
something inside of the string that you are using for the join, and it will be inserted between each
string in the list:
More often than not, you can use an f-string rather than concatenation or .join() and the code will
be easier to follow.
String Slicing
Slicing in strings works in much the same way that it does for Python lists. Let’s take the string
“Mike”. The letter “M” is at position zero and the letter “e” is at position 3.
If you want to grab characters 0-3, you would use this syntax: my_string[0:4]
What that means is that you want the substring starting at position zero up to but not including
position 4.
Here are a few examples:
Chapter 4 - Working with Strings 62
The first example grabs the first four letters from the string and returns them. If you want to, you
can drop the zero as that is the default and use [:4] instead, which is what example two does.
You can also use negative position values. So [-4:] means that you want to start at the end of the
string and get the last four letters of the string. You will learn more about slicing in chapter 6, which
is about the list data type.
You should play around with slicing on your own and see what other slices you can come up with.
Wrapping Up
Python strings are powerful and useful. They can be created using single, double, or triple quotes.
Strings are objects, so they have methods. You also learned about string concatenation, string slicing,
and three different methods of string formatting.
The newest flavor of string formatting is the f-string. It is also the most powerful and the currently
preferred method for formatting strings.
Review Questions
1. What are 3 ways to create a string?
2. Run dir(""). This lists all the string methods you can use. Which of these methods will
capitalize each of the words in a sentence?
5. Use string slicing to get the substring, “is a”, out of the following string:
• int
• float
• complex
Python 2 also had the long numeric type, which was an integer able to represent values larger than
an int could. In Python 3, int and long were combined so that Python 3 only has int. You can create
an int by simply typing the number or by using int(). 2, 3, int(4), and int("5") are all integers.
If you are familiar with C++, you probably know that floating-point numbers are defined using the
double keyword. In Python, you can create a float by typing it or by using float(). 3.14, 5.0,
float(7.9), and float("8.1") are all floating point numbers.
A complex number has a real and an imaginary part. The real and imaginary parts are accessed using
attribute notation: .real and .imag, respectively. Complex numbers can be created by either typing
them or using complex(). 2+1j, 2-1j, 5j, complex(7+2j), complex("7+2j"), and complex(7, 2)‘ are
all complex numbers.
There are two other numeric types that are included with Python in its standard library. They are
as follows:
• decimal - for holding floating-point numbers that allow the user to define their precision
• fractions - rational numbers
You can import these libraries using Python’s import keyword, which you will learn about in chapter
16. You might also be interested in checking out Python’s round() keyword or its math module.
Let’s go ahead and learn a little bit more about how you can create and use numeric types in Python!
Integers
You can create an integer in two ways in Python. The most common way is to assign an integer to
a variable:
Chapter 5 - Numeric Types 65
1 my_integer = 3
The equals sign (=) is Python’s assignment operator. It “assigns” the value on the right to the variable
name on the left. So in the code above, you are assigning the value 3 to the variable my_integer.
The other way to create an integer is to use the int callable, like this:
1 my_integer = int(3)
Most of the time, you won’t use int() to create an integer. In fact, int() is usually used for converting
a string or other type to an integer. Another term for this is casting.
A little known feature about int() is that it takes an optional second argument for the base in which
the first argument is to be interpreted. In other words, you can tell Python to convert to base2, base8,
base16, etc.
Here’s an example:
1 >>> int('10', 2)
2 2
3 >>> int('101', 2)
4 5
The first argument has to be a string while the second argument is the base, which in this case is 2.
Now let’s move on and learn how to create a float!
Floats
A float in Python refers to a number that has a decimal point in it. For example, 2.0 is a float while
2 is an int.
You can create a float in Python like this:
1 my_float = 2.0
This code will assign the number, 2.0, to the variable my_float.
You can also create a float like this:
1 my_float = float(2.0)
Python’s float() built-in will convert an integer or even a string into a float if it can. Here’s an
example of converting a string to a float:
Chapter 5 - Numeric Types 66
1 my_float = float("2.0")
This code converts the string, “2.0”, to a float. You can also cast string or floats to int using the
int() built-in from the previous section.
Note: The float numeric type is inexact and may differ across platforms. You shouldn’t use the
float type when dealing with sensitive numeric types, such as money values, due to rounding
issues. Instead it is recommended that you use Python’s decimal module.
Complex Numbers
A complex number has a real and an imaginary part, which are each a floating-point number. Let’s
look at an example with a complex number object named comp to see how you can access each of
these parts by using comp.real and comp.imag to extract the real and imaginary parts, respectively,
from the number:
1 >>> comp = 1 + 2j
2 >>> type(comp)
3 <class 'complex'>
4 >>> comp.real
5 1.0
6 >>> comp.imag
7 2.0
In the code sample above, you created a complex number. To verify that it is a complex number, you
can use Python’s built-in type function on the variable. Then you extract the real and imag parts
from the complex number.
You can also use the complex() built-in callable to create a complex number:
Here you created a complex number in the interpreter, but you don’t assign the result to a variable.
Numeric Operations
All the numeric types, with the exception of complex, support a set of numeric operations.
Here is a list of the operations that you can do:
Chapter 5 - Numeric Types 67
Operation Result
a+b The sum of a and b
a-b The difference of a and b
a*b The product of a and b
a/b The quotient of a and b
a // b The floored quotient of a and b
a%b The remainder of a / b
-a a negated (multiply by -1)
+a a unchanged
abs(a) absolute value of a
int(a) a converted to integer
float(x) a converted to a floating-point number
complex(re, im) A complex number with real and imaginary
c.conjugate() The conjugate of the complex number c
divmod(a, b) The pair: (a // b, a % b)
pow(a, b) a to the power of b
a ** b a to the power of b
You should check out the full documentation for additional details about how numeric types work
(scroll down to the Numeric Types section):
• https://docs.python.org/3/library/stdtypes.html
Augmented Assignment
Python supports doing some types of arithmetic using a concept called Augmented Assignment.
This idea was first proposed in PEP 203:
• https://www.python.org/dev/peps/pep-0203/
The syntax allows you to do various arithmetic operations using the following operators:
+= -= *= /= %= **= <<= >>= &= ^= |=
This syntax is a shortcut for doing common arithmetic in Python. With it you can replace the
following code:
1 >>> x = 1
2 >>> x = x + 2
3 >>> x
4 3
with this:
Chapter 5 - Numeric Types 68
1 >>> x = 1
2 >>> x += 2
3 >>> x
4 3
Wrapping Up
In this chapter, you learned the basics of Python’s Numeric types. Here you learned a little about how
Python handles int, float, and complex number types. You can use these types for working with
most operations that involve numbers. However, if you are working with floating-point numbers
that need to be precise, you will want to check out Python’s decimal module. It is tailor-made for
working with that type of number.
Review Questions
1. What 3 numeric types does Python support without importing anything?
2. Which module should you use for money or other precise calculations?
• Creating Lists
• List Methods
• List Slicing
• List Copying
Creating Lists
There are several ways to create a list. You may construct a list in any of the following ways:
• Using a pair of square brackets with nothing inside creates an empty list: []
• Using square brackets with comma-separated items: [1, 2, 3]
• Using a list comprehension (see Chapter 13 for more information): [x for x in iterable]
• Using the list() function: list(iterable)
An iterable is a collection of items that can return its members one at a time; some iterables have
an order (i.e. sequences), and some do not. Lists themselves are sequences. Strings are sequences as
well. You can think of strings as a sequence of characters.
Let’s look at a few examples of creating a list so you can see it in action:
This first example is pretty straight-forward. Here you create a list with 3 numbers in it. Then you
print it out to verify that it contains what you think it should.
The next way to create a list is by using Python’s built-in list() function:
Chapter 6 - Learning About Lists 70
In this case, you pass a string of three letters to the list() function. It automatically iterates over
the characters in the string to create a list of three strings, where each string is a single character.
The last example to look at is how to create empty lists:
1 >>> empty_list = []
2 >>> empty_list
3 []
4 >>> another_empty_list = list()
5 >>> another_empty_list
6 []
The quickest way to create an empty list is by using the square brackets without putting anything
inside them. The second easiest way is to call list() without any arguments. The nice thing about
using list() in general is that you can use it to cast a compatible data type to a list, as you did
with the string “abc” in the example earlier.
List Methods
You haven’t learned about methods yet, but it is important to cover list methods now. Don’t worry.
You will be learning more about methods throughout this book and by the end you will understand
them quite well!
A Python list has several methods that you can call. A method allows you to do something to the
list.
Here is a listing of the methods you can use with a list:
• append()
• clear()
• copy()
• count()
• extend()
• index()
• insert()
• pop()
• remove()
• reverse()
• sort()
Chapter 6 - Learning About Lists 71
Most of these will be covered in the following sections. Let’s talk about the ones that aren’t covered
in a specific section first.
You can use count() to count the number of instances of the object that you passed in.
Here is an example:
Note that the reverse() method returns None. What that means is that if you try to assign the
reversed list to a new variable, you may end up with something unexpected:
1 >>> x = my_list.reverse()
2 >>> print(x)
3 None
Here you end up with None instead of the reversed list. That is what in-place means. The original
list is reversed, but the reverse() method itself doesn’t return anything.
Now let’s find out what you can do with the other list methods!
Chapter 6 - Learning About Lists 72
Adding to a List
There are three list methods that you can use to add to a list. They are as follows:
• append()
• extend()
• insert()
The append() method will add an item to the end of a pre-existing list:
First you create a list that is made up of four one-character strings. Then you append an integer to
the end of the list. Now the list should have 5 items in it with the 1 on the end.
You can use Python’s built-in len() function to check the number of items in a list:
1 >>> len(my_list)
2 5
So this tells you that you do in fact have five items in the list. But what if you wanted to add an
element somewhere other than the end of the list?
You can use insert() for that:
In the code above, you tell Python that you want to insert the string, “first”, into the 0 position, which
is the first position in the list.
There are two other ways to add items to a list. You can add an iterable to a list using extend():
Chapter 6 - Learning About Lists 73
Here you create two lists. Then you use my_list’s extend() method to add the items in other_list
to my_list.
The extend() method will iterate over the items in the passed in list and add each of them to the
list.
In this case, you create two lists and then combine them using Python’s + operator. Note that my_list
and other_list have not changed.
You can also use += with Python lists:
This is a somewhat simpler way to combine the two lists, but it does change the original list in the
same way that using the extend() method does.
Now let’s learn how to access and change elements within a list.
To access an item in a list, you need to use square braces and pass in the index of the item that you
wish to access. In the example above, you access the first and third elements.
Lists also support accessing items in reverse by using negative values:
1 >>> my_list[-1]
2 9
This example demonstrates that when you pass in -1, you get the last item in the list returned. Try
using some other values and see if you can get the first item using negative indexing.
If you try to use an index that does not exist in the list, you will get an IndexError:
1 >>> my_list[-5]
2 Traceback (most recent call last):
3 Python Shell, prompt 41, line 1
4 builtins.IndexError: list index out of range
• clear()
• pop()
• remove()
• del
You can use clear() to remove everything from the list. Let’s see how that works:
Chapter 6 - Learning About Lists 75
After calling clear(), the list is now empty. This can be useful when you have finished working
on the items in the list and you need to start over from scratch. Of course, you could also do this
instead of clear():
1 >> my_list = []
This will create a new empty list. If it is important for you to always use the same object, then
using clear() would be better. If that does not matter, then setting it to an empty list will work
well too.
If you would rather remove individual items, then you should check out pop() or remove(). Let’s
start with pop():
You can pass an index to pop() to remove the item with that specific index and return it. Or you can
call pop() without an argument, like in the example above, and it will default to removing the last
item in the list and returning it. pop() is the most flexible way of removing items from a list.
If the list is empty or you pass in an index that does not exist, pop() will throw an exception:
1 >>> my_list.pop(10)
2 Traceback (most recent call last):
3 Python Shell, prompt 50, line 1
4 builtins.IndexError: pop index out of range
remove() will delete the first instance of the passed in item. So in this case, you tell the list to
remove the first occurrence of the number 8.
If you tell remove() to delete an item that is not in the list, you will receive an exception:
Chapter 6 - Learning About Lists 76
1 >>> my_list.remove(4)
2 Traceback (most recent call last):
3 Python Shell, prompt 51, line 1
4 builtins.ValueError: list.remove(x): x not in list
You can also use Python’s built-in del keyword to delete items from a list:
You will receive an error if you try to remove an index that does not exist:
Sorting a List
Lists in Python can be sorted. You can use the built-in sort() method to sort a list in-place or you
can use Python’s sorted() function to return a new sorted list.
Let’s create a list and try sorting it:
Here you create a list with 6 integers in a pretty random order. To sort the list, you call its sort()
method, which will sort it in-place. Remember that in-place means that sort() does not return
anything.
A common misconception with Python is that if you call sort(), you can assign the now-sorted list
to a variable, like this:
Chapter 6 - Learning About Lists 77
However, when you do that, you will see that sort() doesn’t actually return the sorted list. It always
returns None.
Fortunately you can use Python’s built-in sorted() method for this:
If you use sorted(), it will return a new list, sorted ascending by default.
Both the sort() method and the sorted() function will also allow you to sort by a specified key
and you can tell them to sort ascending or descending by setting its reversed flag.
Let’s sort this list in descending order instead:
When you have a more complicated data structure, such as a nested list or a dictionary, you can
use sorted() to sort in special ways, such as by key or by value.
List Slicing
Python lists support the idea of slicing. Slicing a list is done by using square brackets and entering a
start and stop value. For example, if you had my_list[1:3], you would be saying that you want to
create a new list with the element starting at index 1 through index 3 but not including index 3.
Here is an example:
This slice returns index 1 (10) and index 2 (2) as a new list.
You can also use negative values to slice:
Chapter 6 - Learning About Lists 78
In this example, you didn’t specify an end value. That means you want to start at the second to last
item in the list, 23, and take it to the end of the list.
Let’s try another example where you specify only the end index:
In this example, you want to grab all the values starting at index 0 up to but not including index 3.
Copying a List
Occasionally you will want to copy a list. One simple way to copy your list is to use the copy
method:
This successfully creates a new list and assigns it to the variable, new_list.
However note that when you do this, you are creating what is known as a “shallow copy”. What that
means is that if you were to have mutable objects in your list, they can be changed and it will affect
both lists. For example, if you had a dictionary in your list and the dictionary was modified, both
lists will change, which may not be what you want. You will learn about dictionaries in chapter 8.
This example is telling Python to create a slice from the 0 (first) element to the last, which in effect
is the whole list.
Finally, you could also use Python’s list() function to copy a list:
No matter which method you choose though, whether you duplicate a list by using [:], copy() or
list(), all three will create a shallow copy. To avoid running into weird issues where changing one
list affects the copied list, you should use the deepcopy method from the copy module instead.
Wrapping Up
In this chapter, you learned all about Python’s wonderful list data type. You will be using lists
extensively when you are programming in Python.
You learned the following in this chapter:
• Creating Lists
• List Methods
• List Slicing
• List Copying
Review Questions
1. How do you create a list?
2. Create a list with 3 items and then use append() to add two more.
5. Create a list that looks like this: [4, 10, 2, 1, 23]. Use string slicing to get only the middle
3 items.
Chapter 7 - Learning About Tuples
Tuples are another sequence type in Python. Tuples consist of a number of values that are separated
by commas. A tuple is immutable whereas a list is not. Immutable means that the tuple has a fixed
value and cannot change. You cannot add or delete items in a tuple. Immutable objects are useful
when you need a constant hash value. The most popular example of a hash value in Python is the
key to a Python dictionary, which you will learn about in chapter 8.
In this chapter, you will learn how to:
• Create tuples
• Work with tuples
• Concatenate tuples
• Special case tuples
Creating Tuples
You can create tuples in several different ways. Let’s take a look:
1 >>> a_tuple = 4, 5
2 >>> type(a_tuple)
3 <class 'tuple'>
One of the simplest methods of creating a tuple is to have a sequence of values separated by commas.
Those values could be integers, lists, dictionaries, or any other object.
Depending on where in the code you are trying to create a tuple, just using commas might be
ambiguous; you can always use parentheses to make it explicit:
You can cast a list into a tuple using the tuple() function:
This example demonstrates how to convert or cast a Python list into a tuple.
• count()
• index()
You can use count() to find out how many elements match the value that you pass in:
In this case, you can find out how many times the integer 3 appears in the tuple.
You can use index() to find the first index of a value:
This example shows you that the number 2 is at index 1, which is the second item in the tuple.
Tuples are zero-indexed, meaning that the first element starts at zero.
You can use the indexing methodology that you learned about in the previous chapter to access
elements within a tuple:
Chapter 7 - Learning About Tuples 83
1 >>> a_tuple[0] = 8
2 Traceback (most recent call last):
3 Python Shell, prompt 92, line 1
4 TypeError: 'tuple' object does not support item assignment
Here you try to set the first element in the tuple to 8. However, this causes a TypeError to be raised
because tuples are immutable and cannot be changed.
Concatenating Tuples
Tuples can be joined together, which in programming is called “concatenation”. However, when you
do that, you will end up creating a new tuple:
Here you concatenate a second tuple to the first tuple. You can use Python’s id() function to see
that the variable, a_tuple, has changed. The id() function returns the id of the object. An object’s
ID is equivalent to an address in memory. The ID number changed after concatenating the second
tuple. That means that you have created a new object.
You can create an empty tuple by calling the tuple() function with no arguments or via assignment
when using an empty pair of parentheses.
Now let’s create a tuple with a single element:
1 >>> single = 2,
2 >>> len(single)
3 1
4 >>> type(single)
5 <class 'tuple'>
To create a tuple with a single element, you can assign a value with a following comma. Note the
trailing comma after the 2 in the example above.
While the parentheses are usually optional, I highly recommend them for single-item tuples as the
comma can be easy to miss.
Wrapping Up
The tuple is a fundamental data type in Python. It is used quite often and is certainly one that you
should be familiar with. You will be using tuples in other data types. You will also use tuples to
group related data, such as a name, address and country.
In this chapter, you learned how to create a tuple in three different ways. You also learned that
tuples are immutable. Finally, you learned how to concatenate tuples and create empty tuples. Now
you are ready to move on to the next chapter and learn all about dictionaries!
Review Questions
1. How do you create a tuple?
2. Can you show how to access the 3rd element in this tuple?
Chapter 7 - Learning About Tuples 85
3. Is it possible to modify a tuple after you create it? Why or why not?
• Creating dictionaries
• Accessing dictionaries
• Dictionary methods
• Modifying dictionaries
• Deleting items from your dictionary
Creating Dictionaries
You can create a dictionary in a couple of different ways. The most common method is by placing
a comma-separated list of key: value pairs within curly braces.
Let’s look at an example:
You can also use Python’s built-in dict() function to create a dictionary. dict() will accept a series
of keyword arguments (i.e. 1=’one’, 2=’two’, etc), a list of tuples, or another dictionary.
Here are a couple of examples:
Chapter 8 - Learning About Dictionaries 87
The first example uses dict() on a series of keyword arguments. You will learn more about these
when you learn about functions. You can think of keyword arguments as a series of keywords with
the equals sign between them and their value.
The second example shows you how to create a list that has 3 tuples inside of it. Then you pass that
list to dict() to convert it to a dictionary.
Accessing Dictionaries
Dictionaries’ claim to fame is that they are very fast. You can access any value in a dictionary via
the key. If the key is not found, you will receive a KeyError.
Let’s take a look at how to use a dictionary:
To get the value of first_name, you must use the following syntax: dictionary_name[key]
Now let’s try to get a key that doesn’t exist:
1 >>> sample_dict['address']
2 Traceback (most recent call last):
3 Python Shell, prompt 118, line 1
4 builtins.KeyError: 'address'
Well that didn’t work! You asked the dictionary to give you a value that wasn’t in the dictionary!
You can use Python’s in keyword to ask if a key is in the dictionary:
Chapter 8 - Learning About Dictionaries 88
You can also check to see if a key is not in a dictionary by using Python’s not keyword:
Another way to access keys in dictionaries is by using one of the dictionary methods. Let’s find out
more about dictionary methods now!
Dictionary Methods
As with most Python data types, dictionaries have special methods you can use. Let’s check out
some of the dictionary’s methods!
d.get(key[, default])
You can use the get() method to get a value. get() requires you to specify a key to look for. It
optionally allows you to return a default if the key is not found. The default for that value is None.
Let’s take a look:
1 >>> print(sample_dict.get('address'))
2 None
3 >>> print(sample_dict.get('address', 'Not Found'))
4 Not Found
The first example shows you what happens when you try to get() a key that doesn’t exist without
setting get’s default. In that case, it returns None. Then the second example shows you how to set
the default to the string “Not Found”.
d.clear()
The clear() method can be used to remove all the items from your dictionary.
Chapter 8 - Learning About Dictionaries 89
d.copy()
If you need to create a shallow copy of the dictionary, then the copy() method is for you:
If your dictionary has objects or dictionaries inside of it, then you may end up running into logic
errors as a result of using this method, because changing one dictionary will affect the other. In
this case you should use Python’s copy module, which has a deepcopy function that will create a
completely separate copy for you.
You may remember this issue being mentioned back in the chapter on lists. These are common
problems with creating “shallow” copies.
d.items()
The items() method will return a new view of the dictionary’s items:
This view object will change as the dictionary object itself changes.
d.keys()
If you need to get a view of the keys that are in a dictionary, then keys() is the method for you. As
a view object, it will provide you with a dynamic view of the dictionary’s keys. You can iterate over
a view and also check membership via the in keyword:
Chapter 8 - Learning About Dictionaries 90
d.values()
The values() method also returns a view object, but in this case it is a dynamic view of the
dictionary’s values:
d.pop(key[, default])
Do you need to remove a key from a dictionary? Then pop() is the method for you. The pop()
method takes a key and an option default string. If you don’t set the default and the key is not found,
a KeyError will be raised.
Here are some examples:
10 'James'
11 >>> sample_dict
12 {'last_name': 'Doe', 'email': '[email protected]'}
d.popitem()
The popitem() method is used to remove and return a (key, value) pair from the dictionary. The
pairs are returned in last-in first-out (LIFO) order, which means that the last item added will also be
the first one that is removed when you use this method. If called on an empty dictionary, you will
receive a KeyError.
d.update([other])
Update a dictionary with the (key, value) pairs from other, overwriting existing keys. The other
can be another dictionary, a list of tuples, etc.
update() will return None when called.
To add a new item to a dictionary, you can use the square braces to enter a new key and set it to a
value.
If you need to update a pre-existing key, you can do the following:
In this example, you set sample_dict['email'] to [email protected]. Whenever you set a pre-existing
key to a new value, you will overwrite the previous value.
You can also use the update() method from the previous section to modify your dictionary.
In this case, you tell Python to delete the key “email” from sample_dict
The other method for removing a key is to use the dictionary’s pop() method, which was mentioned
in the previous section:
When you use pop(), it will remove the key and return the value that is being removed.
Wrapping Up
The dictionary data type is extremely useful. You will find it handy to use for quick lookups of all
kinds of data. You can set the value of the key: value pair to any object in Python. So you could
store lists, tuples, and other objects as values in a dictionary.
You learned the following topics in this chapter:
• Creating dictionaries
• Accessing dictionaries
• Dictionary methods
• Modifying dictionaries
• Deleting items from your dictionary
It is fairly common to need a dictionary that will create a key when you try to access one that does
not exist. If you have such a need, you should check out Python’s collections module. It has a
defaultdict class that is made for exactly that use case.
Review Questions
1. How do you create a dictionary?
2. You have the following dictionary. How do you change the last_name field to ‘Smith’?
Chapter 8 - Learning About Dictionaries 94
3. Using the dictionary above, how would you remove the email field from the dictionary?
• Creating a set
• Accessing set members
• Changing items
• Adding items
• Removing items
• Deleting a set
Creating a Set
Creating a set is pretty straight-forward. You can create them by adding a series of comma-separated
objects inside of curly braces or you can pass a sequence to the built-in set() function.
Let’s look at an example:
Chapter 9 - Learning About Sets 96
A set uses the same curly braces that you used to create a dictionary. Note that instead of key:
value pairs, you have a series of values. When you print out the set, you can see that duplicates
were removed automatically.
Now let’s try creating a set using set():
In this example, you created a list and then cast it to a set using set(). If there had been any
duplicates in the list, they would have been removed.
Now let’s move along and see some of the things that you can do with this data type.
Sets do not allow you to use slicing or the like to access individual members of the set. Instead, you
need to iterate over a set. You can do that using a loop, such as a while loop or a for loop.
You won’t be covering loops until chapter 12, but here is the basic syntax for iterating over a
collection using a for loop:
Chapter 9 - Learning About Sets 97
This will loop over each item in the set one at a time and print it out.
You can access items in sets much faster than lists. A Python list will iterate over each item in a
list until it finds the item you are looking for. When you look for an item in a set, it acts much like
a dictionary and will find it immediately or not at all.
Changing Items
While both dict and set require hashable members, a set has no value to change. However, you
can add items to a set as well as remove them. Let’s find out how!
Adding Items
There are two ways to add items to a set:
• add()
• update()
That was easy! You were able to add an item to the set by passing it into the add() method.
If you’d like to add multiple items all at once, then you should use update() instead:
Chapter 9 - Learning About Sets 98
Note that update() will take any iterable you pass to it. So it could take, for example, a list, tuple
or another set.
Removing Items
You can remove items from sets in several different ways.
You can use:
• remove()
• discard()
• pop()
Using .remove()
The remove() method will attempt to remove the specified item from a set:
If you happen to ask the set to remove() an item that does not exist, you will receive an error:
Now let’s see how the closely related discard() method works!
Using .discard()
The discard() method works in almost exactly the same way as remove() in that it will remove the
specified item from the set:
Chapter 9 - Learning About Sets 99
The difference with discard() though is that it won’t throw an error if you try to remove an item
that doesn’t exist:
If you want to be able to catch an error when you attempt to remove an item that does not exist, use
remove(). If that doesn’t matter to you, then discard() might be a better choice.
Using .pop()
The pop() method will remove and return an arbitrary item from the set:
If your set is empty and you try to pop() an item out, you will receive an error:
This is very similar to the way that pop() works with the list data type, except that with a list,
it will raise an IndexError. Also lists are ordered while sets are not, so you can’t be sure what you
will be removing with pop() since sets are not ordered.
If you want to completely remove the set, then you can use Python’s del built-in:
Set Operations
Sets provide you with some common operations such as:
These operations are the most common ones that you will use when working with sets.
The union() method is actually kind of like the update() method that you learned about earlier, in
that it combines two or more sets together into a new set. However the difference is that it returns
a new set rather than updating the original set with new items:
In this example, you create two sets. Then you use union() on the first set to add the second set to it.
However union doesn’t update the set. It creates a new set. If you want to save the new set, then
you should do the following instead:
Chapter 9 - Learning About Sets 101
The intersection() method takes two sets and returns a new set that contains only the items that
are the same in both of the sets.
Let’s look at an example:
These two sets have only one item in common: the string “one”. So when you call intersection(),
it returns a new set with a single element in it. As with union(), if you want to save off this new
set, then you would want to do something like this:
The difference() method will return a new set with the elements in the set that are not in the other
set. This can be a bit confusing, so let’s look at a couple of examples:
When you call difference() on the first_set, it returns a set with “two” as its only element. This
is because “two” is the only string not found in the second_set. When you call difference() on the
second_set, it will return “four” because “four” is not in the first_set.
There are other methods that you can use with sets, but they are used pretty infrequently. You should
go check the documentation for full details on set methods should you need to use them.
Wrapping Up
Sets are a great data type that is used for pretty specific situations. You will find sets most useful for
de-duplicating lists or tuples or by using them to find differences between multiple lists.
In this chapter, you learned about the following:
Chapter 9 - Learning About Sets 102
• Creating a set
• Accessing set members
• Changing items
• Adding items
• Removing items
• Deleting a set
Any time you need to use a set-like operation, you should take a look at this data type. However, in
all likelihood, you will be using lists, dictionaries, and tuples much more often.
Review Questions
1. How do you create a set?
2. Using the following set, how would you check to see if it contains the string, “b”?
4. Remove the letter “c” from the following set using a set method:
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 11 - Conditional Statements
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Comparison Operators
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Nesting Conditionals
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Logical Operators
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Special Operators
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 11 - Conditional Statements 105
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 12 - Learning About Loops
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Using continue
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Nesting Loops
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 13 - Python Comprehensions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
List Comprehensions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Dictionary Comprehensions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Set Comprehensions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 13 - Python Comprehensions 109
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 14 - Exception Handling
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Handling Exceptions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Raising Exceptions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 15 - Working with Files
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Reading Files
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Writing Files
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Appending to Files
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 15 - Working with Files 113
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 16 - Importing
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Using import
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Importing Everything
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 17 - Functions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Creating a Function
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Calling a Function
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Passing Arguments
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Positional-only Parameters
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Scope
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 18 - Classes
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Class Creation
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Subclass Creation
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Polymorphism
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Part II - Beyond the Basics
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 19 - Introspection
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Getting help()
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Using callable()
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Using len()
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 19 - Introspection 121
Using locals()
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Using globals()
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 20 - Installing Packages with
pip
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Installing a Package
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Upgrading a Package
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Uninstalling Packages
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Alternatives to pip
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 21 - Python Virtual
Environments
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Other Tools
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 22 - Type Checking in Python
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Classes
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Decorators
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Aliasing
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Type Comments
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 23 - Creating Multiple
Threads
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Creating Threads
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Subclassing Thread
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 24 - Creating Multiple
Processes
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Subclassing Process
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 25 - Launching Subprocesses
with Python
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 25 - Launching Subprocesses with Python 132
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 26 - Debugging Your Code
with pdb
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Getting Help
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 27 - Learning About
Decorators
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Creating a Function
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Creating a Decorator
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Stacking Decorators
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 27 - Learning About Decorators 136
Python Properties
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 28 - Assignment Expressions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 29 - Profiling Your Code
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Other Profilers
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
line_profiler
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
memory_profiler
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 29 - Profiling Your Code 139
profilehooks
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
scalene
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
snakeviz
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 30 - An Introduction to
Testing
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 31 - Learning About the
Jupyter Notebook
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Creating a Notebook
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Running Cells
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Adding Content
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 31 - Learning About the Jupyter Notebook 143
Using Headings
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Adding a Listing
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Creating a Hyperlink
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Adding an Extension
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Part III - Practical Python
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 32 - How to Create a
Command-line Application with
argparse
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Parsing Arguments
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Adding Aliases
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 33 - How to Parse XML
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 34 - How to Parse JSON
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 34 - How to Parse JSON 150
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 35 - How to Scrape a Website
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Scraping a Website
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Downloading a File
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 36 - How to Work with CSV
files
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 37 - How to Work with a
Database Using sqlite3
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 38 - Working with an Excel
Document in Python
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 39 - How to Generate a PDF
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Installing ReportLab
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Creating a Table
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 39 - How to Generate a PDF 158
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 40 - How to Create Graphs
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Installing Matplotlib
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Adding Labels
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Creating a Legend
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 41 - How to Work with
Images in Python
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Installing Pillow
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Opening Images
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Cropping Images
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Using Filters
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Adding Borders
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 41 - How to Work with Images in Python 162
Resizing Images
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 42 - How to Create a
Graphical User Interface
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Installing wxPython
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Part IV - Distributing Your Code
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 43 - How to Create a Python
Package
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Creating a Module
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Creating a Package
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Creating setup.py
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 43 - How to Create a Python Package 167
Uploading to PyPI
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 44 - How to Create an Exe for
Windows
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Installing PyInstaller
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 45 - How to Create an
Installer for Windows
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Creating an Installer
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 46 - How to Create an “exe”
for Mac
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Installing PyInstaller
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Questions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Afterword
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Appendix A - Version Control
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Common Terminology
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Branch
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Changelist / Changeset
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Checkout
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Appendix A - Version Control 173
Clone
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Commit
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Diff
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Fork
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Head
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Initialize
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Mainline
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Merge
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Appendix A - Version Control 174
Pull / Push
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Pull Request
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Repository
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Resolve
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Stream
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Tag
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Trunk
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Appendix B - Version Control with Git
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Installing Git
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Installing on Windows
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Installing on MacOS
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Installing on Linux
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Configuring Git
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Creating a Project
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Appendix B - Version Control with Git 177
Ignoring Files
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Initializing a Repository
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Committing Files
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Changing a File
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Appendix B - Version Control with Git 178
Reverting a File
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Pushing to Github
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Wrapping Up
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Question Answer Key
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
2) Run dir(""). This lists all the string methods you can use. Which
of these methods will capitalize each of the words in a sentence?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
2) Create a list with 3 items and then use append() to add two more.
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
5) Create a list that looks like this: [4, 10, 2, 1, 23]. Use string
slicing to get only the middle 3 items.
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
2) Can you show how to access the 3rd element in this tuple?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Question Answer Key 183
3) Using the dictionary above, how would you remove the email
field from the dictionary?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
4) Remove the letter “c” from the following set using a set
method:
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Question Answer Key 184
4) How do you use logical operators to check more than one thing
at once?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 16 - Importing
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
2) How do you include cos from the math library in your own code?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 17 - Functions
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
3) Using the function from question 2, give the zip code a default
of 55555
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 18 - Classes
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
5) What is a subclass?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Chapter 19 - Introspection
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
1) What is introspection?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
Review Question Answer Key 191
1) What is pdb?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
3) What is a breakpoint?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
4) What is a callstack?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
1) What is a decorator?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
3) How do you get the root element using the ElementTree API?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
1) What is JSON?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
3) How do you write a row of CSV data using the csv module?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
1) What Python package can you use to work with Microsoft Excel
spreadsheets?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
1) How do you get the width and height of a photo using Pillow?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
1) What is a GUI?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.
1) What is a module?
This content is not available in the sample book. The book can be purchased on Leanpub at http:
//leanpub.com/py101.