The Python Book 5th Edition Dan Peel PDF Download
The Python Book 5th Edition Dan Peel PDF Download
download
https://ebookmass.com/product/the-python-book-5th-edition-dan-
peel/
https://ebookmass.com/product/the-python-book-1st-edition-rob-
mastrodomenico/
https://ebookmass.com/product/starting-out-with-python-5th-
international-edition-tony-gaddis/
https://ebookmass.com/product/the-python-quiz-book-michael-driscoll/
https://ebookmass.com/product/dan-voodoo-guardians-book-eighteen-mary-
kennedy/
The Star Shepherd Dan Haring
https://ebookmass.com/product/the-star-shepherd-dan-haring/
https://ebookmass.com/product/clear-threat-disgardium-book-10-litrpg-
series-dan-sugralinov/
https://ebookmass.com/product/introduction-to-python-for-econometrics-
statistics-and-data-analysis-5th-edition-kevin-sheppard/
https://ebookmass.com/product/the-synagogue-of-satan-dan-fournier/
https://ebookmass.com/product/halo-saka-the-book-of-hope-tips-menata-
harapan-dan-impian-caritra-sari/
NEW Everything you need to start coding with Python in Linux
The
Python Over
400
essential tips
100% UNOFFICIAL
Edition
Digital
OVER 2 HOURS
OF VIDEO TUTORIALS
FIFTEENTH
EDITION
Python
Python is an incredibly versatile, expansive language that, due to its similarity to
everyday language, is surprisingly easy to learn even for inexperienced programmers. It
has seen a huge increase in popularity since the release and rise of the Raspberry Pi, for
which Python is the officially recognised programming language. In this new edition
of The Python Book, you’ll find plenty of creative projects to help you get to grips with
the combination of your Raspberry Pi and Python’s powerful functionality, plus lots
of tutorials that focus on Python’s effectiveness away from the tiny computer. You’ll
learn all about how to code with Python from a standing start with our comprehensive
masterclass, then go on to complete tutorials that will consolidate your skills and help
you become fluent in the language. You’ll learn how to make Python work for you
with tutorials on coding with Django, Flask, Pygame and even more useful third-party
frameworks. Get ready to become a true Python expert with the wealth of information
contained within these pages and the free video tuition on FileSilo.
The
Python
Future PLC Quay House, The Ambury, Bath, BA1 1UA
Editorial
Compiled by Dan Peel & Steve Dacombe
Senior Art Editor Andy Downes
Head of Art & Design Greg Whitaker
Editorial Director Jon White
Contributor
Jonni Bidwell
Advertising
Media packs are available on request
Commercial Director Clare Dove
International
Head of Print Licensing Rachel Shaw
[email protected]
www.futurecontenthub.com
Circulation
Head of Newstrade Tim Mathers
Production
Head of Production Mark Constance
Production Project Manager Matthew Eglinton
Advertising Production Manager Joanne Crosby
Digital Editions Controller Jason Hudson
Production Managers Keely Miller, Nola Cokely,
Vivienne Calvert, Fran Twentyman
Printed in the UK
Distributed by Marketforce, 5 Churchill Place, Canary Wharf, London, E14 5HU
www.marketforce.co.uk Tel: 0203 787 9001
The Python Book Fifteenth Edition (TCB5053)
© 2023 Future Publishing Limited
We are committed to only using magazine paper which is derived from responsibly managed,
certified forestry and chlorine-free manufacture. The paper in this bookazine was sourced
and produced from sustainable managed forests, conforming to strict environmental and
socioeconomic standards.
All contents © 2023 Future Publishing Limited or published under licence. All rights reserved.
No part of this magazine may be used, stored, transmitted or reproduced in any way without
the prior written permission of the publisher. Future Publishing Limited (company number
2008885) is registered in England and Wales. Registered office: Quay House, The Ambury,
Bath BA1 1UA. All information contained in this publication is for information only and is, as far
as we are aware, correct at the time of going to press. Future cannot accept any responsibility
for errors or inaccuracies in such information. You are advised to contact manufacturers and
retailers directly with regard to the price of products/services referred to in this publication. Apps
and websites mentioned in this publication are not under our control. We are not responsible for
their contents or any other changes or updates to them. This magazine is fully independent and
not affiliated in any way with the companies mentioned herein.
Python
8
Contents
Get started with Python
Master the basics the right way
62 Embedding Python in C
Use Python code within your usual C
Create with Python
104 Make a Pac-Man-style game
16 50 essential commands 50 Create your own version of the arcade classic
The commands you need to know
108 Revisit arcade classic Pong
Create your very own version of one
Python essentials gaming’s pioneers
26 50 Python tips 112 Program a Space Invaders clone
Essential knowledge for Python users Make the basic Pivaders game
Web development
Build, hack and move a robotic arm
Get started
with
Python Always wanted to have a go at
programming? No more excuses,
because Python is the perfect way to get started!
P
ython is a great programming language for libraries to create a windowed application, or you could
both beginners and experts. It is designed with try something a little more ambitious like an app such
code readability in mind, making it an excellent as creating one using Python’s Bluetooth and Input
choice for beginners who are still getting used to libraries to capture the input from a USB keyboard and
various programming concepts. relay the input events to an Android phone.
The language is popular and has plenty of libraries For this guide we’re going to be using Python 2.x since
available, allowing programmers to get a lot done with that is the version that is most likely to be installed on your
relatively little code. Linux distribution.
You can make all kinds of applications in Python: In the following tutorials, you’ll learn how to create
you could use the Pygame framework to write popular games using Python programming. We’ll also
simple 2D games, you could use the GTK show you how to add sound and AI to these games.
#!/usr/bin/env python3
hello_int = 21
The same principal is true of
Boolean values hello_bool = True
# This list now contains 5 strings. Notice that there are no spaces
# between these strings so if you were to join them up to make a sentence
# you’d have to add a space between each element.
hello_list = list()
hello_list.append(“Hello,”)
You could also create the hello_list.append(“this”)
same list in the following way
hello_list.append(“is”)
hello_list.append(“a”)
hello_list.append(“list”)
# The first line creates an empty list and the following lines use the append
# function of the list type to add elements to the list. This way of using a
# list isn’t really very useful when working with strings you know of in
# advance, but it can be useful when working with dynamic data such as user
# input. This list will overwrite the first list without any warning as we
# are using the same variable name as the previous list.
We might as well create a
dictionary while we’re at it. hello_dict = { “first_name” : “Liam”,
Notice how we’ve aligned the “last_name” : “Fraser”,
colons below to make the
code tidy “eye_colour” : “Blue” }
print(str(hello_tuple[0]))
# We can’t change the value of those elements like we just did with the list
# Notice the use of the str function above to explicitly convert the integer
# value inside the tuple to a string before printing it.
Remember that tuples are
immutable, although we can print(hello_dict[“first_name”] + “ “ + hello_dict[“last_name”] + “ has “ +
access the elements of them
like so hello_dict[“eye_colour”] + “ eyes.”)
if int_condition < 6:
sys.exit(“int_condition must be >= 6”)
else: “The ‘for‘ loop uses
print(“int_condition was >= 6 - continuing”)
The path that the code takes will depend on the value of
a local copy, so
the integer int_condition. The code in the ‘if’ block will only be
executed if the condition is true. The import statement is used
changes in the loop
to load the Python system library; the latter provides the exit
function, allowing you to exit the program, printing an error
won’t affect the list”
message. Notice that indentation (in this case four spaces per
$ ./construct.py
indent) is used to indicate which statement a block of code
How many integers? acd
belongs to.
You must enter an integer
‘If’ statements are probably the most commonly used control
structures. Other control structures include:
More about a $ ./construct.py
• ‘For’ statements, which allow you to iterate over items in
Python list How many integers? 3
collections, or to repeat a piece of code a certain number
Please enter integer 1: t
A Python list is similar to an of times;
You must enter an integer
array in other languages. A • ‘While’ statements, a loop that continues while the condition
Please enter integer 1: 5
list (or tuple) in Python can is true.
contain data of multiple
Please enter integer 2: 2
We’re going to write a program that accepts user input from the
types, which is not usually Please enter integer 3: 6
user to demonstrate how control structures work. We’re calling it
the case with arrays in other Using a for loop
construct.py.
languages. For this reason, 5
we recommend that you The ‘for’ loop is using a local copy of the current value, which
2
only store data of the same means any changes inside the loop won’t make any changes
6
type in a list. This should affecting the list. On the other hand however, the ‘while’ loop is
almost always be the case
Using a while loop
directly accessing elements in the list, so you could change the list
anyway due to the nature of 5
there should you want to do so. We will talk about variable scope in
the way data in a list would 2
some more detail later on. The output from the above program is
be processed. 6
as follows:
# We’re going to write a program that will ask the user to input an arbitrary
# number of integers, store them in a collection, and then demonstrate how the
# collection would be used with various control structures.
The number of integers we
want in the list
import sys # Used for the sys.exit function
ints = list()
These are used to keep track
of how many integers we
currently have count = 0
except:
print(“You must enter an integer”)
if isint == True:
# Add the integer to the collection
ints.append(new_int)
# Increment the count by 1
count += 1
By now, the user has given up or
we have a list filled with integers.
We can loop through these in a print(“Using a for loop”)
couple of ways. The first is with
a for loop for value in ints:
print(str(value))
#!/usr/bin/env python3
def modify_string_return(original):
original += “ that has been modified.”
# However, we can return our local copy to the caller. The function
# ends as soon as the return statement is used, regardless of where it
# is in the function.
We are now outside of return original
the scope of the modify_
string function, as we
have reduced the level
of indentation test_string = “This is a test string”
test_string = modify_string_return(test_string)
print(test_string)
However, we can call the # The function’s return value is stored in the variable test string,
function like this # overwriting the original and therefore changing the value that is
# printed.
If cont is set to True, then the variable will be created and we can access Happy programming!
it just fine. However, this is a bad way to do things. The correct way is to
initialise the variable outside of the scope of the ‘if’ statement.
#!/usr/bin/env python3
cont = False
var = 0
if cont:
var = 1234
if var != 0:
print(var)
The variable var is defined in a wider scope than the ‘if’ statement, and
can still be accessed by the ‘if’ statement. Any changes made to var inside
the ‘if’ statement are changing the variable defined in the larger scope.
This example doesn’t really do anything useful apart from illustrate the
potential problem, but the worst-case scenario has gone from the program
crashing to printing a zero. Even that doesn’t happen because we’ve added
an extra construct to test the value of var before printing it.
Coding style
It’s worth taking a little time to talk about coding style. It’s simple to write
tidy code. The key is consistency. For example, you should always name
your variables in the same manner. It doesn’t matter if you want to use
camelCase or use underscores as we have. One crucial thing is to use
self-documenting identifiers for variables. You shouldn’t have to guess
02 Reloading modules
When a module is first imported, any initialisation functions are run at that time. This may involve
creating data objects, or initiating connections. But, this is only done the first time within a given session.
Importing the same module again won’t re-execute any of the initialisation code. If you want to have this
code re-run, you need to use the reload command. The format is ‘reload(modulename)’. Something to keep
in mind is that the dictionary from the previous import isn’t dumped, but only written over. This means that
any definitions that have changed between the import and the reload are updated correctly. But if you
delete a definition, the old one will stick around and still be accessible. There may be other side effects, so
01 Importing modules
The strength of Python is its ability to be
always use with caution.
An enhanced shell
04 Executing a script
Importing a module does run the code
05 The default interactive shell is provided
through the command ‘python’, but is 06 Evaluating code
within the module file, but does it through the rather limited. An enhanced shell is provided by Sometimes, you may have chunks of
module maintenance code within the Python the command ‘ipython’. It provides a lot of extra code that are put together programmatically. If
engine. This maintenance code also deals with functionality to the code developer. A thorough these pieces of code are put together as a string,
running initialising code. If you only wish to history system is available, giving you access to you can execute the result with the command
take a Python script and execute the raw code not only commands from the current session, ‘eval(“code_string”)’. Any syntax errors within
within the current session, you can use the but also from previous sessions. There are also the code string are reported as exceptions. By
‘execfile(“filename.py”)’ command, where the magic commands that provide enhanced ways of default, this code is executed within the current
main option is a string containing the Python file interacting with the current Python session. For session, using the current globals and locals
to load and execute. By default, any definitions more complex interactions, you can create and use dictionaries. The ‘eval’ command can also take
are loaded into the locals and globals of the macros. You can also easily peek into the memory two other optional parameters, where you can
current session. You can optionally include of the Python session and decompile Python code. provide a different set of dictionaries for the
two extra parameters the execfile command. You can even create profiles that allow you to handle globals and locals. If there is only one additional
These two options are both dictionaries, one initialisation steps that you may need to do every time parameter, then it is assumed to be a globals
for a different set of locals and a different set of you use iPython. dictionary. You can optionally hand in a code
globals. If you only hand in one dictionary, it is object that is created with the compile command
assumed to be a globals dictionary. The return instead of the code string. The return value of this
value of this command is None. command is None.
07 Asserting values
At some point, we all need to debug
some piece of code we are trying to write. One
of the tools useful in this is the concept of an
assertion. The assert command takes a Python
08 Mapping functions
A common task that is done in modern
programs is to map a given computation
expression and checks to see if it is true. If so, to an entire list of elements. Python provides the
then execution continues as normal. If it is not command ‘map()’ to do just this. Map returns a list of
true, then an AssertionError is raised. This way,
you can check to make sure that invariants
within your code stay invariant. By doing so,
the results of the function applied to each element of
an iterable object. Map can actually take more than
one function and more than one iterable object. If it
09 Virtualenvs
Because of the potential complexity of
you can check assumptions made within your is given more than one function, then a list of tuples the Python environment, it is sometimes best to
code. You can optionally include a second is returned, with each element of the tuple containing set up a clean environment within which to install
parameter to the assert command. This second the results from each function. If there is more than only the modules you need for a given project. In
parameter is Python expression that is executed one iterable handed in, then map assumes that the this case, you can use the virtualenv command
if the assertion fails. Usually, this is some type of functions take more than one input parameter, so to initialise such an environment. If you create
detailed error message that gets printed out. Or, it will take them from the given iterables. This has a directory named ‘ENV’, you can create a new
you may want to include cleanup code that tries the implicit assumption that the iterables are all of environment with the command ‘virtualenv
to recover from the failed assertion. the same size, and that they are all necessary as ENV’. This will create the subdirectories bin, lib
parameters for the given function. and include, and populate them with an initial
environment. You can then start using this new
environment by sourcing the script ‘ENV/bin/
activate’, which will change several environment
“While not strictly commands, everyone needs to variables, such as the PATH. When you are done,
know how to deal with loops. The two main types you can source the script ‘ENV/bin/deactivate’
to reset your shell’s environment back to its
of loops are a fixed number of iterations loop (for) previous condition. In this way, you can have
environments that only have the modules you
and a conditional loop (while)” need for a given set of tasks.
10 Loops
While not strictly commands, everyone needs
to know how to deal with loops. The two main
types of loops are a fixed number of iterations loop (for) and
a conditional loop (while). In a for loop, you iterate over some
sequence of values, pulling them off the list one at a time
and putting them in a temporary variable. You continue until
either you have processed every element or you have hit a
break command. In a while loop, you continue going through
the loop as long as some test expression evaluates to True.
While loops can also be exited early by using the break
command, you can also skip pieces of code within either
loop by using a continue command to selectively stop this
12 Reductions
In many calculations, one of the
computations you need to do is a reduction
current iteration and move on to the next one.
operation. This is where you take some list of values
and reduce it down to a single value. In Python, you
can use the command ‘reduce(function, iterable)’ to
11 Filtering
Where the command map returns a result for every element in an iterable, filter only returns a
apply the reduction function to each pair of elements
in the list. For example, if you apply the summation
reduction operation to the list of the first five
result if the function returns a True value. This means that you can create a new list of elements where integers, you would get the result ((((1+2)+3)+4)+5).
only the elements that satisfy some condition are used. As an example, if your function checked that You can optionally add a third parameter to act as an
the values were numbers between 0 and 10, then it would create a new list with no negative numbers initialisation term. It is loaded before any elements
and no numbers above 10. This could be accomplished with a for loop, but this method is much from the iterable, and is returned as a default if the
cleaner. If the function provided to filter is ‘None’, then it is assumed to be the identity function. This iterable is actually empty. You can use a lambda
means that only those elements that evaluate to True are returned as part of the new list. There are function as the function parameter to reduce to keep
iterable versions of filter available in the itertools module. your code as tight as possible. In this case, remember
that it should only take two input parameters.
16 What is this?
Everything in Python is an object. You can
check to see what class this object is an instance
of with the command ‘isinstance(object, class)’.
This command returns a Boolean value.
17 Is it a subclass?
The command ‘issubclass(class1, class2)’
checks to see if class1 is a subclass of class2. If
class1 and class2 are the same, this is returned
as True.
18 Global objects
You can get a dictionary of the global
symbol table for the current module with the
command ‘globals()’.
19 Local objects
You can access an updated dictionary
of the current local symbol table by using the
command ‘locals()’.
14 Enumerating
Sometimes, we need to label the elements
of functions that can be used to do this conversion
process. The ones you are most likely to use is ‘abs’,
‘bin’, ‘bool’, ‘chr’, ‘complex’, ‘float’, ‘hex’, ‘int’, ‘long’,
23 Raising an exception
When you identify an error condition,
that reside within an iterable object with their
‘oct’, and ‘str’. For the number-based conversion you can use the ‘raise’ command to throw up an
indices so that they can be processed at some later exception. You can include an exception type and
functions, there is an order of precedence where
point. You could do this by explicitly looping through a value.
some types are a subset of others. For example,
each of the elements and building an enumerated
integers are “lower” than floats. When converting
list. The enumerate command does this in one line.
It takes an iterable object and creates a list of tuples
up, no changes in the ultimate value should happen. 24 Dealing with an exception
Exceptions can be caught in a try-except
When converting down, usually some amount of construction. If the code in the try block raises an
as the result. Each tuple has the 0-based index of
information is lost. For example, when converting exception, the code in the except block gets run.
the element, along with the element itself. You can
from float to integer, Python truncates the number
optionally start the indexing from some other value
towards zero.
by including an optional second parameter. As an
example, you could enumerate a list of names with 25 Static methods
You can create a statis method, similar
the command ‘list(enumerate(names, start=1))’. In to that in Java or C++, with the command
this example, we decided to start the indexing at 1 ‘staticmethod(function_name)’.
instead of 0.
31 With modules
The ‘with’ command provides the ability to
wrap a code block with methods defined
32 Printing
The most direct way of getting output
to the user is with the print command.
by a context manager. This can help clean up code This will send text out to the console window. If you
and make it easier to read what a given piece of are using version 2.X of Python, there are a couple
code is supposed to be doing months later. A classic of ways you can use the print command. The most
example of using ‘with’ is when dealing with files. common way had been simply call it as ‘print
You could use something like ‘with open(“myfile. “Some text”’. You can also use print with the same
txt”, “r”) as f:’. This will open the file and prepare it for syntax that you would use for any other function.
reading. You can then read the file in the code block So, the above example would look like ‘print(“Some
26 Ranges
You may need a list of numbers, maybe in
with ‘data=f.read()’. The best part of doing this is that
the file will automatically be closed when the code
text”)’. This is the only form available in version 3.X.
If you use the function syntax, you can add extra
a ‘for’ loop. The command ‘range()’ can create an block is exited, regardless of the reason. So, even if parameters that give you finer control over this
iterable list of integers. With one parameter, it the code block throws an exception, you don’t need to output. For example, you can give the parameter
goes from 0 to the given number. You can provide worry about closing the file as part of your exception ‘file=myfile.txt’ and get the output from the print
an optional start number, as well as a step size. handler. If you have a more complicated ‘with’ command being dumped into the given text file.
Negative numbers count down. example, you can create a context manager class to It also will accept any object that has some string
help out. representation available.
29 Sorted lists
You can use the command ‘sorted(list1)’
to sort the elements of a list. You can give it
a custom comparison function, and for more
complex elements you can include a key function
that pulls out a ranking property from each
element for comparison.
33 Memoryview
Sometimes, you need to access the raw data of some object, usually as a buffer of bytes. You
30 Summing items
Above, we saw the general reduction
can copy this data and put it into a bytearray, for example. But this means that you will be using extra
memory, and this might not be an option for large objects. The command ‘memoryview(object_name)’
function reduce. A specific type of reduction wraps the object handed in to the command and provides an interface to the raw bytes. It gives access
operation, summation, is common enough to to these bytes an element at a time. In many cases, elements are the size of one byte. But, depending
warrant the inclusion of a special case, the
on the object details, you could end up with elements that are larger than that. You can find out the size
command ‘sum(iterable_object)’. You can include
a second parameter here that will provide a of an element in bytes with the property ‘itemsize’. Once you have your memory view created, you can
starting value. access the individual elements as you would get elements from a list (mem_view[1], for example).
ebookmasss.com