The Python Book Dan Peel instant download
The Python Book Dan Peel instant download
https://ebookmeta.com/product/the-python-book-dan-peel/
https://ebookmeta.com/product/all-about-history-book-of-the-
medici-first-edition-2019-dan-peel-editor/
https://ebookmeta.com/product/ultimate-80s-retro-gaming-
collection-4th-edition-dan-peel/
https://ebookmeta.com/product/history-of-war-defining-battles-of-
world-war-ii-4th-edition-2023-dan-peel-editor/
https://ebookmeta.com/product/reliable-robot-localization-a-
constraint-programming-approach-over-dynamical-systems-1st-
edition-simon-rohou/
Intolerant Filthy Rich Kinky Book 2 1st Edition Elena
Dawne
https://ebookmeta.com/product/intolerant-filthy-rich-kinky-
book-2-1st-edition-elena-dawne/
https://ebookmeta.com/product/c-programming-for-the-pic-
microcontroller-demystify-coding-with-embedded-programming-
hubert-henry-ward/
https://ebookmeta.com/product/food-processing-advances-in-
thermal-technologies-kshirod-kumar-dash/
https://ebookmeta.com/product/coherence-the-science-of-
exceptional-leadership-and-performance-2nd-edition-watkins/
https://ebookmeta.com/product/shattered-fractured-1-1st-edition-
katelyn-beckett/
RNA Interference and CRISPR Technologies Mouldy Sioud
https://ebookmeta.com/product/rna-interference-and-crispr-
technologies-mouldy-sioud/
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
licensing@futurenet.com
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
6.
Heikki. Kas niin, johan nyt olet kovin syntiin paatunut! Enpä olisi
voinut luullakaan, sinun vielä niin pitkälle joutuneen. Nyt en enää
tahdokaan juurtaa sanojani sinuun, sillä kun himo on jo kerran niin
suureksi paisunut, että — —
(Heikki menee.)
KUUDES KOHTAUS.
Niilo yksinään.
Niilo. Sitä pahempi, että Heikki on oikeassa. Jopa alan hävetä. Eikä
olekaan mikään ihme, ettei Leena pidä minusta, kun näkee miten
narrimainen minä olen. Joka kerran kun menen puotiin, saadakseni
kohdata häntä, menee hän matkaansa ja jättää minun isänsä kanssa
puhelemaan. Näin jäätyäni pulaan, on minun täytynyt joka kerta
ostaa itselleni hattu, kun en ole rohennut oikeaa asiatani julkaista,
sillä enhän voi asiatta mennä vieraiden luo. Luultavasti nauraa Leena
minua siitä. Jos olisin miehuudella ja tarkoitukseni toteuttamiseen
turvautumalla itseäni käyttänyt, niin olisin varmaankin jo kauvan
aikaa sitten saanut tilaisuuden aukaista sydämeni hänelle,
joutumattani pilkan-alaiseksi näiden kaikkien hattujen ostamisesta.
Waan rakkaus on kummallinen sikiö; se syntyy sekä elää kahdella
tavalla samalla kertaa. Ajan huviksi se minussa syntyi, vaan kohtapa
poltin itseni, ikäänkuin perho, siinä liekissä, jonka ympärillä häärin.
Ihmekö siis, että Leena katsoo minuun samoilla silmin kuin ensi
alussa tietämättä, ettei rakkauteni enää olekaan pelkkää mairetta,
mutta sydämeni hartainta toivoa. Niin, niin! tästä silmänräpäyksestä
alkaen tahdon muuttaa tapani; ja vielä parempi olisi, jos minulle
onnistuisi sammuttaa se vähäinenkin lemmen liekki, jonka kenties
olen häneen sytyttänyt. Saakurin hatut! Pahuus vieköön, etten ole
voinut olla rauhoillani!
SEITSEMÄS KOHTAUS.
Niilo. Tikka.
Tikka. Kuulkaa herra, rohkenenko kysyä, joko olette saaneet
vekselinne ja olisiko teidän mahdollista auttaa minua rahanpulasta?
Niilo. En, hyvä isäntä, en toden todellakaan ole sitä vielä saanut.
Tikka. Ettekö? Sepä nyt vasta oli saakeli! Ties Jumala, mitä minun
tulee tehdä. Tänäin täytyy minun maksaa suuri rahasumma
tavaroista. Olenpa mennyt mies, jos ette minua pulasta päästä.
(Itkee.) Ah, herra Heimo! Perkele vieköön, miten väärin te olette
tehneet, kun olette saattaneet minun miesparan tämmöiseen
helvetinmoiseen piinaan.
Niilo. Mitä takausta minä voisin teille hankkia, koska olen umpi
vieras täällä kaupungissa? Paljoa helpompi on minun hankkia teille
rahaa, kuin takausta.
Niilo. Kyllä te saatte, sanon minä vielä kerran, vaan malttakaa toki
siksi, kunnes itse saan rahaa.
20
1.
Tikka.
2.
Niilo.
Tikka.
Oikein puhutten.
3.
Heikki (Niilolle).
Hattujoukon kummoisen
Söimme hintaan kalliisen!
Synti on se suur.
Saanko hälle sanoa:
"Kiitoksia ruuasta",
Waikk' ei kestäs juur.
4.
Hattujoukon kummoisen
Söimme hintaan kalliisen!
Synti on se suur.
Saamme teille sanoa:
Kiitoksia ruuasta.
Tikka.
Kiittämist' ei juur.
YHDEKSÄS KOHTAUS.
Tikka. Kyllä hän on täällä. Anna kirje minulle, niin minä vien sen
kiireemmiten hänelle.
(Sopanen tulee.)
Renki. Saan sanoa paljon terveisiä rouvalta ja tässä on teille kirje,
joka juuri nyt postin kanssa tuli.
KUUDES KOHTAUS.
Entiset. Wiljakainen. Miettinen. Ravintolanvieraita ja
palvelijoita. Miettisellä on vielä sanomalehti kädessä.
(Nousee.)
Kaikki. Ilostako?
Kaikki. Tuleeko?
(Menee.)
(Menee.)
YHDESTOISTA KOHTAUS.
Heimo. Niin vain! minun tulee siis palata takaisin. Waan saanko
kysyä, kuka se korkeasukuinen matkustavainen on, jollei hän vaan
kulje nimeänsä ilmoittamatta?
Tikka. Kyllä hän niin tekee, mutta meidän kesken puhuttu, hän on
komersiraati Wasili Petravitsa.
(Menee.)
(Aikoo mennä.)
KAHDESTOISTA KOHTAUS.
Heimo yksinään.
1.
2.
3.
Olen setä toisellainen,
Hyvin muistan, kun mä vainen
Jouduin lemmen pauloihin,
Pyörrypäisnä kuljeksin.
4.
KOLMASTOISTA KOHTAUS.
Hiitolahan sammoisiin
I mieliin, kieliin hoastoin,
Piruun pierkoa kaupihtiin,
I mutsuilt tienkaat roastoin.
Taloonmies,
Sorttah ties!
Pihkaaks pierkaan keksih;
Tuimiistuip' heän, Herrah Kies!
Taast niin tuliseksih.
2.
3.
4.
5.
Heimo.
6.
Wasili.
Heimo.
Wasili.
Walheet lie?
Heimo.
Tästä sie
Saat kakskymment' markkaa
Wasili.