100% (1) 100% found this document useful (1 vote) 3K views 180 pages The Python Book - 16th Edition 2023
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here .
Available Formats
Download as PDF or read online on Scribd
Go to previous items Go to next items
Save The Python Book - 16th Edition 2023 For Later | NEW | Everything you need to start coding with Python in Linux
mvatalele
Book
$ 50 ESSENTIAL
PYTHON COMMANDS
Learn to use Python « Program games « Get creative with PiWelcome to
Python
Book
Python eanincrediby versatile expansivelanguagethat due totsimirtyto|
everdylanquage ssurpshaly sy "olean even forinexpetenced programmers
hasseen ahuge ncreaseln ponuarysinceheeleaseandiiseofthe RaspoeryP for
which Python theofficial recognise programming language nths newedtion
‘of TheythonBook yulind plenty ofcreativepojets to helpyou ge tors wth
combination of your Raspoerty land Python's powerulfunctonaltypluslets
‘of uoralsthatfocuson Python eectiveness away fromthe ry computer Youll
lea about how tocode with Python fom astanding tar with ourcomprehensie
masteras.then goontocomplete tuoi that vllensolidateyoursklsandhalp
ou become uentinthelanguage Youllean how tormake Python werkoc you
withtutoriakon coding with Django. Fak Pygeme andieven more seul thd party
framewerks Getready to become true Pythonexpert withthe wealth ofiformation
‘containedthin these pages4 L
FUTURE
4 rBe CMa)
re ane
Roe Ta oy
coco eT
eet
Ean
Pata se
Eee ed
piroeorn atin
Se ED auc
Dea creer aeons
Dae
Pesci ters
Ee ee Teac ted
episec-chesintens
SE ue Sud
et ate
aD
eaitsaic
Se LenS
Use Python code within your usual C
far Min eau
Se ee cre Cui cr
Koster eet red
See Tee Lea)
fee tar eee
en nae
See UE ea rca’
ies arenes
DC Ear eC Rat)
reorient
120 Create in Minecraft
cree
AWM alot
Cer era)
aero ert
Pare UU cr
Enhance Kodi with this tutorial
Seared)
pasetrertic ry
See)
freee
Se eT)
eee
Sere Sree)
Keep your software project safe
ea rere)
Develop alight version ofcpin Python 3
SO Una
Persea etdDevelop with Python
resect)
Create dynamic templates
aes eet
CR ea)
Cee ets)
De ons ra)
enor
eT
Fess reas
Cn EE Merce aad
a
eee
Ere
ee ETT
Perret isnoneeteny
Teer og
Part 1s Embed four hacks into a toy
eet
et toner rs
DedHello World
Let's get stuck in, and what better way than with the
programmers bestfriend, the ‘Hello World’ application! Start
by opening a terminal. its current working directory wil be your
hhome directory. I's probably a good idea to make a directory for
the files well be creating inthis tutorial rather than having them
loose in your home directory. You can create a directory called
Python using the command ‘You'll then want to
change into that directory using the command
‘The next step isto create an empty file using the command
“touch followed by the filename. Our expert used the command
‘The final and most important part of
setting up the fil ie making it executable, This allowe us to un
Code inside the hello_worldpy file. We do this withthe command
‘Now that we have our file set up, we
‘can go ahead and open it up in nano, or any text editor of your
choice. Geditis a great editor with syntax highlighting support
that should be available on any distribution. Youll be able to
intallitusing your package manager ifyou don't have i already.
(ur Hello World program is very simple, i only needs two tines.
‘Thefirstline begins witha ‘shebang’ (the symbol #!— also known
as a hashbang) followed by the path to the Python interpreter.
The program loader uses thisline towork out what the est of the
lines need to be interpreted with. If you're running this in an IDE
lke DLE, you don't necessariynoed todo this.
The code thats actualy read by the Python interpreter is only
2 single tne. Were passing the value Hello World to the print
function by placing tin brackets immediately efter we've called
the print function. Helo Word is enclosed in quotation marks to
indicate that tis teal value and should not be interpreted as
source code. As expected, the prntfuntion in Python prints any
value that gets passed tit from the console.
‘You can save the changes youve just made tothe fie innano
Using the key combination GHD, followed by Enter. Use GHAR
toexitnano.
‘You_can run the Hello World program by prefixing
its filename with J in this case you'd type:
Vioummeuingageriad
‘siorncharon en
ove
cele raetieas
feayeatbetecest
10 The Python Book
Variables and datatypes
Available sa name in source code that is associated with an
fra in memory tt you can vse fo store data, wich a then
Called upon thoughout the code. The data can be one of many
types including
rey
eee eres
As wel as these main data types, there are sequence types:
(technically, astringis a sequence type but is commonly used
we've classed tas
A tuple would be used for something like a co-ordinate,
Containing anx and y value stored as a single variable, whereas
8 list is typically used to store larger collections. The data
stored in @ tuple is immutable because you aren't able to
change values of individual elements in a tuple. However, you
ceandosoinalist.
it will also be useful to know about Python's dictionary
‘ype. A dictionary is a mapped data type. It stores data in
key-value pairs. This means that you access values stored in
the dictionary using that value’s corresponding key, which is
different to how you would do it with alist na ist, you would
access an element of the list using that element's index (a
‘number representing the element's position inthe list.
Let's work on a program we can use to demonstrate how to
use variables and different data types. it's worth noting at
this point that you don’t always have to specify data types
in Python, Feat free to create thi fle in any editor you lke,
Everything will work jst fine as long as you remember to make
‘the file executable. We're going to call ours
“A variable is a name
in source code that is
associated with an area in
memory that you can use to
store data”Get started with Python Ml
‘Yusrbin/env python3
‘We create a variable by writing the name ofthe variable we want followed
4 by an equals sign, which Is followed by the value we want to store in the
Megervonsbieesied hate ine # variable. For example, the following line creates a variable called
wrt fea of hence {hello str, containing the string Hello World
‘uatonmas hrllo_str="Hello World”
[ hetlo_int = 21
Tresae pineal
Booker volute { hello_bool =True
We cate stile the (helo tuple= (21,32)
isn ay
hello_l
Anda in ts way U
(PHellog this "sa "ist")
{This list now contains 5 strings. Notice that there are no spaces,
4 between these strings so if you were to join ther up to make a sentence
4 yould have to add a space between each element.
hhello_lst=list)
hello_listappend(“Hello’)
Youcout aio create the
ee hhello_stappendi this")
hhello_listappend's")
hello_listappend(2")
holo list append list?)
4 The ist line creates an empty list and the following lines use the append
# function of the Iist type to add elements tothe list. This way of using a
‘list ist really very useful when working with strings you know of in
4 advance, butt can be useful when working with dynamic data such as user
4 input. This lst will overwrite the first list without any warning as we
4 are using the same variable name as the previous list
Wemight swell ceatea
(Seton whe were tt hello dict = ("fist_name':"Liam’
ates how weve atonad he “Tast_name® "Fraser,
Sarid PMS eye colour’"Bue")
4 Lets access some elements inside our collections
44 Well start by changing the value of the last sting in our hello_list and
‘add an exclamation mark to the end, The"Ist string is the Sth element
4 in the list. However, indexes in Python are zero-based, which means the
Notes tat here wilnow be 4 first element has an index of
epineteclenent ___ printthello_st4))
hello lst] +="
The above lineis the same as
hhello_lst4] = hello_tistf4} +"
printthello lista)
seis eth
‘planing any tetin
TEeoteaane “Any text in a Python file that follows a #
Scere
Siecowe” character will be ignored”
camer nyourcoeprintstrhello_tuple(O}))
# We can't change the value of those elements like we just did withthe lis
4 Notice the use ofthe str function above to explicitly convert the integer
4 value inside the tuple toa string before printing it
fernenbertatiis ae
beabtopitnntcen rinthello_ dct firstname’ ++ ello. dct ast name'l+*has* +
tones helo_dit'ye. colour" +" eyes")
Lees crests sentence wing the
‘nainourhato ocr
hello_dict(last_name”),
hhello_dict!"eye_colour')
Ati way of ing tis
‘nou betbuse Pyar
Sina erate
Control structures
In programming, a contol strvetueis ary king of statement that
canchango the path that the code exacuton takes. For example. a
‘contol structure that decided to endthe program fa number was
leasthan5 would look somethingtke tis:
‘The path thatthe code takes wil depend on the value of
he integer int-condtion, The code in the block wit ony be
twecutes if the coniton is tue, The import statment ie used
to loed the Python system library; the later provides the ext
function, alloning you to ext the program, prising an error
message. Notice that indentation (in this ease feur spaces per
inden) is used to indieate which statement a block of code
belongsta
“statements are probably the most commonly wed control
structures. Otherconte structures include:
‘Fee statements, which allow you to iterate over items in
collections, or to repeat @ piece of code a certain number
otis:
‘tile statements, a loop that continues wile the coniton
‘Were going to write a program that accepts user input fom the
user to demonstrate how contre structures work We'e calling it
The fer loop i using a local copy ofthe current value, which
‘means any changes inside the loop won't make ary changes
affecting the Uist. On the other hand however, the “whl” op Is
weclyaccesing elements in thelist, you could changothe lit
there should you want todo o, We wltakabout variable spin
n¢ mare deal ater on. The output from the ove program is
allo:
12 The Python Book
print("(0}(1) has 2} eyes*formatthello_dict"rst_name"L
“The ‘for’ loop uses
a local copy, so
changes in the loop
won't affect the list”‘The numberofinteger we
srancntheet
Also tore the gers
‘yustfbin/erw python
'#Wete going to write a program that will ask the usertt input an arbitrary
+ numberof integers, store them in a collection, and then demonstrate how the
4 collection would be used with vatious control structures,
Import sys # Used forthe sys.exit function
target i
= raw_input("How many integers?)
1 By now, the variable target int contains a string representation of
' whatever the user typed. We need to try and corwert that to an integer but
4 be weady to-# deal with the eror fit’ not, Otherwise the program will
crash,
except Valuetror:
sysexit("You must enter an integer")
‘hese aust ee tack
thon many mteges ve
fe above suceeds thn nt
ow the werhas en up oF
ee favea lt fed apes.
‘Wecanigopthowahtheseina
hiplevoys Thefts
Sereop
1 Lints =isto
{count =0
+ Keep asking for an integer until we have the required number
hile count < target_int:
‘new _Int= raw_input("Please enter integer (0: "format(count + 1))
isint = False
print("You must enter an integer")
4# Only cary on if we have an integer. f not, weil ]oop again
f Notice below! use==, which s different from =. The single equalsisan
‘assignment operator whereas the double equalsis a comparison operator.
ifisint == True:
4 Add the integer to the collection
ints append(new_int)
‘Increment the count by 1
count += 1
pint"Using a for loop")
for value in ints:
print(strivalue})
04)
G4
BEEZ!
,e7
Uy
“The Python Book 13‘Youcan dtine tats # Or with a while loop:
cenaeoetae print(“Using a while loop")
Tinton witout passing # We already have the total above, but knowing the len function is very
“anyarales through # useful
al Youd this puting total = lenCints)
“anequassignater
{i ‘count
Prtcenieye while count < total:
print (str(intsfcount))
count += 1
Functions and variable scope
Functions are used in programming to break processes down into smaller that they wl have in the scape ofthe function regardless of what
chunks. This often makes code much easier tread. Functions can alo be the variable thats paseed to the function is called, Lats see thie
Feusable designed ina certain way. Functions can have variables passed inaction,
‘totem, Variables in Python are aways passed by value, hich means that Theoutpu rom the program opposites as follows:
copy of tho variable is pasced tothe fneton thats only vain tho cope
Wiles dewt Hee tate chee atneaaes wewiant FUNCTIONS are used in
tinedivotecin ayant taentraet imeem POGraMMiIng to break
conmae The utes grentotheveattesininee badetwartsemnee POTOCESSES Own in”
Juse/bin/eny python?
4 Below is a function called modify_string, which accepts a variable
f that will be called original in the scope of the function. Anything
# indented with 4 spaces under the function definition is in the
4 scope.
def modify_string(original):
original +=" that has been modified.”
# At the moment, only the local copy of this string has been modified
def modify_string_return(original): |
original += * that has been modified. |
# However, we can return cur local copy to the caller. The function
4 ends as’ soon as the return statenent is used, regardless of where it
4 As in the function.
return original
Weare now outside of
‘he acape ofthe most
$trngonction ob,
OFindentaton 1 [Rest.string = “This is a test string”
‘The os sing wort be modify_string(test_string)
changed inthis code [> prinectest_string)
test_string = modify_string_return(test_string)
print(test_string)
4 The function’s return value is stored in the variable test string,
¥ overeriting the original and therefore changing the value that is
# printed
However wecan cathe
‘V4 The Python Book‘Scope is an important thing to get the hang of, ctheriseitcan get you
into some bed habits Let's wit a quick rogram to demonstrate thi. I's
ping to have a Boolean variable called com, which wil decide @ umber
wil be assigned to a varabo in an statement. However, tho variable
hasnt been defined anywhere part frominthe scope ofthe i statement,
Well fish off by ying prt thevariabl
Inthe section of code above, Python wll anwar the integer oa sting
before printing However, i's abways a good idea to expt convert
things to strings ~ especialy when it comes to concatonating strings
together Ifyou try to use the + operator on a string and an ntger, there
wil be an eror because its ot explicit clear what needs to happen
‘The + operator would ususly ad two integers together. Having sid that,
Python's string formatter that we demonstrated aries leaner way of
jonaby _ fMembertat Python takes taba erysrously
tne andthe araweria radiate so yousrerecsungaryerorthatmentions
01 Pythonscripts fen cnt arabe 8
ytmacbistentteconmandine S$ bythan 03,
sarees Bereta Pe ene a
Berntcletecxawn cmp ta scat
FumningPython ESP yw ta ieee ot gate
oo ream Fre lnaploprgaepecsases Cia cl nc cae
ion eter or “license” for more information. the data type of anything. Based on what value
26 The Python Book04 Python statements
Setoertn, ee 8 Slot end rion
Sepunte etic: Mot of te cpl
progurmingingages acheeConsGriioe
toriodare to seperate suerts bd uy
Braet boqwetocosebace
05 ==and = operators
Pithen as “efor comparcen and
Sapient. Pytan does no suppor. ine
scoping the lee wn yu uly art
06 Concatenating strings
‘Yucanus'+ to coneateratstings.
>>> print(‘py'” thon’)
python
07 The__init__method
Thi rntfediaruveneon anc
Gfadasobtetrted Therevodiovet
{oda tazton yeu nate dowith eur
Chet tent robodisandcgstoa
cenevaariner oF don
Example:
class Person
def _init_(self, nae):
self name * none
ef sayHi(sel
print(‘Hello, my name is', self
om)
= Person(‘Inega')
p.saytiO
Output:
[-/srefpython $:1 python initmathod.py
Hello, my name is Inego
08 Modules
Te too yur bopens awe & Tey
Soa a sews ou pat aoe
{etn crifon ino Ho on wr em
Srerosie tat canbe mtd Wo oer
Seven on propeme Thee Hos mut hae 8
4 file ny_function.py
ef minnaxta,b):
if ae,
clse:
return min, max
Module Usage
‘import. my_function
ob
ay
09 Module defined names
3y-Funetion.minmax(25, 6.3)
The buttin function ‘it! can be used to find
out which names a module dees, fret a
‘ered ofstrng,
>e> import tine
>e> dir(time)
Tso.
+ package’_"| ‘accept2dyear",
“Bltzone’, “asctime', ‘clock’,
‘etine’, ‘daylight’, “gatine’,
‘Tocaltine’, ‘nktime’, ‘sleep',
‘steftine’, “strptine’, ‘struct
tine’, ‘tine’, “timezone”, ‘tznane",
stzset')
Module internal
10 documentation
You can see the internal documentation Ui
traiate) of @ modula name by looking at
Example:
>>> import tine
>>> print(tine.clock.__doe_)
clock() => floating point nusber
This oxen return th CPU tine ral tine
‘See the start ofthe processor sce the fist
fall tock. This hae as much precision athe
systemroco
Passing arguments
11 toa Python script
Baton les you sees have you Taw
fastedtoasorpticalingt To man
tre eco oobrdin tee art
‘nore sys
prinecsys. rev)
Loading modules or
12 commands at startuy
Yor can tnd pdt oddest
conmande a tw eto. of wy Pym
cbt by sng to, sure, vee
SevTHoNSWTUP ou case enormert
Colao SHONSTARTUP too Tw
Cotto the retwcore bad pceoeey
mredubecreomrcs
Converting a strin;
13 fodateobject =
E the function DteTina tcorvera
stringtoagetecoject.
From DateTine inport Daterine
dateobj = DateTime string)
>>> mylist = C‘span’, ‘han’, ‘eggs']
>>> print(+, 'Jein(aylist))
am, han, eggs
>>> prine(‘\at Jein(aylist))
span
am
ees
Tab completion
15 in Python interpreter
joucan ede aso corinne Ban
errr ty acing these ines 1. Yr
yer ie bro Pyne on
aarp
inportelooleter,restne
rene parse bin tabs: cnet’)
‘all ale Python comets paral ped
Tieton mohe andre names whee
preset tees
16 documentation tool
You con pon up 8 gotica cease
texching th yon decantation whe he
crmert
$ pydoe -E
‘ouunlreed pte tpicagetrtisto nr
17 documentation server
cn tho eal nace, THs wl ge you ace
ling scone 1 ali yeh socom,
incite parymadlecroameratn
5 pyc -» “portNanber>
4g Python development
Tere re plenty of toda w help with yibon
oiopment Hereara fon mparantoes:
THB tre Python buitin IDE with
‘utoconplation, firetin signe popup hel
satieasire,
IBBBBH,arctherentanced Python shel with
teb-compstonandothe estes
IBGE 1 GU! Pytnon IDE wth suzocompetion
rset bultinshaland dbase
RBI Comerercial Pytnen IE with
feo once aalabie to open-source
dovlopersoveryere
Python Bock 27°Built-in
modules
Executing functions
at the time of Python
19 interpreter termination
SeumectOyror erpetrermnaon
dF sunt)
rine 4¥5)
ef message)
rine(“Executing Now")
nport atexit
atexit-register(sus)
‘texit. register(nessage)
Executing Now
°
integer to binary,
20 hexatiecimaland octal
Usebs
>>> bin(24)
*ob11000"
>>> hex(24)
“oxts
>>> oct(24)
‘o30"
Convertin,
21 charset toUTF-8
Chaeatoutr
data decode “input. charset. here”)
seodecutts8)
Removing
22 duplicates from lists
Tyr vert to eno leas fom © EE
jut ut erry sete to © Ky Cor
Settee
ere
er astinet()
a0
sop cetiten, (4,)len(), 1,
Tecan
28 The Python ook
23 Do-while loops
Ere Btn fs 10 dre o GO
txratuss Goh yu cor eo long
reeves oat
thite Tes
do soethine)
1 condition:
i
22, Detzeting system
Boke ms
atl tadetect th platfomonuhcnthaPton
ierrtrsuring Youcan ve 2st
taint ecurent lator.
>>> inport sys
>>> sys.platforn
“tinue
>>> import sys
>o> sysiplatform
‘darwin’
Disabling and enabling
25 garbage collection
Serotnes you ay wart enable of dale
the gum cola’ at urine You can
>>> deport gc
>>> gc-enable
built-in function enable>
>e> ge.disable
“built-in function disable>
Using C-based
modules for better
26 performance
rrduis Using tees rol
theo snieartpe bree
Pickle instead of Pickle, cStringIO
{instead of StringIO|
Calculating maximum,
= i sum
out of any list or
27 iterable
Youcenusethefollingbuit-infunctons.
Rexenstheargestelomentinth ak
utunsthosmalastlamentithelst
ig function rate the sum of all
slementsintalst accepts ancptonal sacond
argument th valet str wth hen summing
ldetaste too
Representin
28 fractional numbers
ae RET
ra, For complex numbers, a
Separate mre is used, called ath
import math
sath acos(x): Return arc cosine of ».
rath: cos(x): Returns cosine of x
rath factorial(x) + Returns x
factorial
30 Working with arrays
defines eon
arrayCtypecode Cy initializer)
Gea you hve Seated an aay by
enaed ta pasion
sarray.count Go: Returns the number
Sioeesreeeeeetoaretca
ayarray.extendGo): Aopends x at the
feet thearray
svarray-reverse(): Reverse the order
ot the array.
31 Sorting items
Inport biseck
ect nor (La CTENICY
hight)
tonite ot be roveruyisheredothe
Teotenyeisingen
blaectinsort lef t(ist, stem C, Tow
tne
Farts tm ito ttn sored oe ta s
ttensinte ot be rovertyisharedothe
ieraryectngetesUsit lar
i expresso -based
ered
1 search withaepor-based enpresson,
Checkout the eam boon.
>>> taport Fe
>e> s = "Kunal i 9 bad boy"
>o> if re.seareh(*K", 5): print
“aateht” char Literal
Hatch!
>o> if re.search(*[@A-21", 5): print
“Watch!” # char class
# aatch either at-sign or capital
letter
Match!
>>> if re.search("\¢", 5): print
“Watch!” # digits class
Working with ina
‘compression
33 format
oon usted WT om eawe
Satuaretebizeompesin assim
bed conrese() For be?
aes
ban decopress() + For br?
decompression
File: be2-example.py
inport 622
MESSAGE = "Kunal {9 9 bad boy"
compressed message = bz2.
compress (HESSACE)
deconpressed_nessage = bz2.
‘deconpress (conpressed message)
print “original:", repr HESSAGE)
print “compressed message:
Fepr (compressed message)
print “deconpressed message:",
repr (decompressed message)
[-/src/ython $1 python bz2-
‘example. py
original: “Kunal is 2 bad boy!
conpressed message: “BZAOIAYESV\Kc4\
HOFG\x98\x00\x00\302\x15\x800\300\
xO0\x094%\x80 \x00"\A00\x0e\K6A\e\
O20 a ub \nd6=\x25\xD3\x191x00\
FB \sbb\x92) \ee2\x84\¥86 2<\xc0"
deconpressed message: “Kunal is 3
bad boy’
Sienna ne panied
abou becesone me cotigaetan
needed and superior lvelaofprforrance You
‘canusethermedide Salted narderto mvt
‘Site catabases,
>e> lnport sqlites
de> connection = salite.connect(“test
o")
55> curs = connection. cursor()
>>> curs.execute(*' create table iten
+ Cid integer prinary key, iteano
text unique
scancade text, descr text, price
real")
35 Workingwithzipfiles
‘oveouesthe edie fie tvexkth
Zoties
Zipfile.2ipFile(tilenane C, wade C,
onpression C,alloweipe4]13)
afletating oatletbecbect
Bipfile,closeO4
GoowtearewetieYoumustal oe ttre
ccaigyor prgrencr svat cr lk
town
Zip ile-extract(senbert, patht,
el)
Exrata erber rom te cine tote ort
tengo rember mst bots rare
fora oro osc Pat sce stot
flrarmorazoriocbect bt thera
satrarcyptdin
Using UNIX-style
wildgards to search
36 for filenames
You can use te ode You fod al te
athnames mating a pttrn according the
‘dss ved ty the UNK sel and charactor
eer ncn
>>> import glob
>>> glob. glab(*./f0-9].*")
[gif */2.tx0'7
>o> glob.glob(#.gif")
U.git", ‘card. gif)
>e> glob. glob("?7-gi")
Cait]
Performing basic file
operations (copy,
37 delete and rename)
You cans the ox hts perforn bse
fiocpraon at ahh eet Ts aso nets
wis our ropa esa owl wo nh
‘pov es heared pen soca on
Shutil.cony(sresdst)
Cristo tothe decry
shutil.eopymode(sre, 6st)
Clos teflopemisons tom sco dt
shutil mve(eresdst)
Novsa‘tocrdrstrytodst
Bee PTT
Eisnorell>
Farscape dectnyét
shutil entree Gath Ly ignore errors
Peoesereen)
Dates nertredecton,
Executing UNIX
com from
38 Python
The rot oleae Pond ato ya
ra nares core
>>> import comands
>>> commands. getoutput(‘Is')
“bz2-exanple.py\test py"
Reading environment
39 variables
Tovcaoethe moaie OF ogi SIG
atarret oman
>>> import os
>>> os.path 22> 0s.environ ("LANG': ‘en
IN’, “TER: “xtern-color”, ‘SHELL’:
“bin/bash”, “LESSCLOSE"
“Jusr/bin/lesspipe % *5",
"X06_SESSION_COOKTE":
+ 925464459779 1cTO46S6354ad°56U0-
1257673132. 347986-1177792325",
SSHLVL?: ‘1°, “SILTY: “/dew/
pts/2", *PWO': “/home/kunal”,
“LESSOPEN': | fusr/bin
lesspipe
a)
“posix’
33> of Linesen
ne
The Python Book 294O Sending email
Yovcan woth mele smept's canara
Using an STP Bele Mal artr Pretaco)
pe Seon pat)
Import satplib
# Use your onn to and from email
adiress
Fronacsr
“fromegnat. con’
toadérs. = “todgnail.con’
sg = ‘T an a Python geek. Here is
the proof.”
# Credentials
1 Use your ann credentials and
enable ‘less secure appe’ in Grail
usernane = “fromgnail com’
password = “woe
The actual mail send
server = smtplib, MIP(‘sntp.gmail.
ccom:587")
# Google Nail uses secure
connection for SHTP connections
server.starttls()
server. Login(usernane, password)
server sendaail(Fronaddr, teaddrs,
a)
server. quit()
Accessing
41 FTP server
Tote a fy tees dn
Pron. fo sah an
Canusstelaongtnon
feolib.FiPCGhost Cy user C, passwd
Cwacct C, timeoutiI330)
‘Example:
host = “ftp.redhat.con"
Username = “anonynous”
password = “kunaldeaégnail.com”
Emort Ftplib
import urilib2
Fep_sery = Feplib,
FIP (host, usernane, password)
# Download the file
4 = UPL1ib2.urlopen (HFtB=//
Ftp. redhat. con/pub/redhat/Linux/
README")
# Print the file contents
rine (u.read())
Output:
5 python Fepelient.py
30 The Python Book
tse versonsof es HatLinuxhave been mowed
{tp:/farchive.download-redhat.com/pub/
redhatnas!
Launching a web
with the default wet
42 browser
The wabbronso? wedi ponds 8 rvaiont
vay 10 loch vonage ware, the deft
wet broncer
>>> Inport webbrowser
>>> webbrowser .open(‘http://google.
co.uk")
True
Creating secure
43 hashes”
he ash’ motule swears @ platrors oF
>>> import hashlib
4 shat Digest
>>> hashlib,shal(°MI6 Classified
Information 027") hexdigest()
“224b15434229ccBcb35010b0599
1aboib20c8s?
4 shaz2s Digest
>>> hashlib.shaz24OMEG Classified
Information @27") hexdigest()
*399102F7410000022408448 275082907087
7959b460990008955¢2c0"
4 shad56 Digest
p> hashlib.sha236(MI6 Classified
Inforwation 007") hexdigest()
* 2fddes73 5487267 2Feb39725991689
basso7a7ebftc6403e fdb33b1c198256"
4 sha384 Digest
>>> hashlib.shas84(°MI6 Classified
Information 027") texdigest()
*S5c4914160F03dFedie14dzecleTAbdab09
de1a2edc13anf7682000087438As9FS40be
e050 c3d33658063538720°
4 shasi2 Digest
>>> hashlib.shaS12CMI Classified
Information @27")-hexdigest()
*aT@4ac3dbo" 6823457848203 1d8a029025
2c822diF4973449b8050222edec8073b08077
‘seatTaadBeet fbb 18566140667Fba47
peldelfFis2Fe0c71322"
4905 Digest
>>> hashlib.miBC°MI6 Classified
Information 807") .hexdigest()
*BeDFe52ac 45F129992670c82647126"
Seedingrandom
44 numbers
Yor anise te mani Vandana
2 vee arty of random mura. The mest
Sng one is vacomswed I ritaines
the bese random rer gener. Wx
omits Neve curr isto ie ed
rey eas ed tee
Seonteratentamehise fret eared
Working with CSV
5 (comma-separated
45 values) files
SV flee vey pear dain
trove Ung rear jocaeatond
wraccaviie
import csv
#reite stocks data as coma
separated values
writer = csv writer open( stocks.
csv", ‘wb, butfering=20))
weiter writerows(L
(CGL0G", “Google, Toe.” 505.28, 0.47,
9.09),
CMG0", Yahoo! Tne.", 27.38, 0.33,
1.2,
COT, ‘CHET Networks, The.", 8.52,
-0.13, “1.48)
»
¥ read stocks data, print status
messages
stocks = csv. reader (open ‘stocks.
csv", *rb))
State labels = (-1: ‘dom
“unchangee”, 1: “up)
for ticker, nane, price, change, pet
sn stocks:
labels fenp(Float (change), 0.0)
print('8s 1s 35 (BS)" X (none,
status, pet)?
Installing third-party
modules using setup
4G tools
etal yon pelagic you
oul bots etal eproean wietl
postage vere
Yau a tall thi pry modi using
the Po pctag maregs Use te caer
Septet ytd ft tal Por
aljca ofleolanosepoatoee—
5 pip install simplejson
Collecting simplejson
Downloading sinpleson-3.17.6-ep810-
‘ep31e-mary Linux 2.5. x86 64.sanylinox_
*86_64-nanylinux 2 12.385. 64
Imanylinix 2010_285.64.whl_ (13748)
Installing collected packages:
simplejson
Successfully installed
simplejson-3.17.6
Processing dependencies for simplejson
Finishes processing dependencies for
simplejson
47 Logging messages to
thesystemd journal
Tou can sete modu ‘eat wits oe
dystem log The use for rang pres,
ences estore youprogra mh
‘rpg modal aso trac tO UNK
Dinky Urey routes, est atten to
Csvojstonds jal ogre ond we uses
paral eormandiobocetatThe-band-2
teh pp tothe atest jaa ets forthe
carte!
inport syslog
syslog.syslog(‘nygeekanp: started
Jogging’)
for a in Cia", *b', *e'1
'b = ‘mygeckapo: I found the letter
syslog-sysiog(b)
syslog.syslog(‘mygeekapp: the script
goes to sleep now, bye,bye!")
Output
5 python mylog.py
5 journaletl -b -e
Nov. 8 17:22:36 ubuntu python313691:
rygeekarp: started logging
Nov 8 17:22:34 ubuntu pythont311691:
iygeekapp: T found the letter a
Nov. 8 17:22:34 ubuntu python 31169]:
inygeekapp: T found the letter b
Nov. 8 17:22:34 ubuntu python(311691:
imygeekapp: T found the letter c
Nov 8 17:22:34 ubuntu python(311691:
rnygeekarp: the script goes to sleep
now, bye, bye!
Third-party modules
Converting HTML,
48 documentsto PDF __
TOF i @ vey ponder mode To POF
' suo pip install python-paF
Collecting pythor-pdF
Downloading python. pdf-€.39-py36-rone=
ary.whl_ (16.8 18)
Installing collected packages: python=
at
Successfully installed pythonpuf-0.38
Example:
>>> import yh
55> pdf = pydlf generate pdf(‘ with open( test doce, no!) 35 f
write out Pa
>o> Fuveite(odh)
Tho gonerste_pef function can tke @ whale
lot of opdonal arguments, eneing everthing
‘rom OF and quality stings to margin sizos.
See the documentation at htns/pypiore?
roet/python pa or moreinformaton
Uncethe hood Py uses the wlrtmept
lary to do the conersion. And if you want
you can pass any ofthe more ecatie options
for that brary to Pya too. Oe problem with
lakitmitopt is peed. can only generate one
acurent por process, so if you have lets of
decurent thay are goneratod an by one, each
ina separate process which kes time start
ancena
Ta work around this, ite posse to
asynchroraus VO to spawn mute px
andparallie POF output ThePydf mediohas
‘8 dass “async for handling this usecase
Dain, see the documentation fr more details
onthis.
49 Using Twitter API
{ou con corto Tater tig tho Pyhon
“te mele
5 git clone git://github.con/bear/
python-taittar
S$ ed python-taitter
5 rake dev
Example fetching followers ist):
>>> import twitter
4 Use you oun twitter account here
o> aytl = en tter. AB (consumer.
p> Feends © mytnl-GetFriends()
>>> print Cu.nane for u in friends)
[u'Matt Legend Gemell", u'jono wells,
[The MON Big Blog", u'tanish Mandal’,
iH”, uIndLanvdeoSaner can”,
'Facetaron Hillegass’, u'ChaosCode',
Uinilestp", u’Frank Jetmings',.."2
Note that in order to use most features of
Python Titer youllaeedtogorerateanAocess
“Token and AP ay or your twtr account. You
find instructions for doing this a hps/ax
‘wittercom/asutvoveniewenpliceton-cwner
‘ecoese-toene . Thi ll ve you the 4 mage
rumbersfor twitter Ap
Fetching the latest
50 news
‘bvcen vse were Taae howard
tance op hence agit an PONS
with eter me bots yr teen et
CDenaP ey brea wrk See toe
pone cron tenia
S pip install neve-python
‘Example:
Inport news_pytion
‘exs = nens_python.Glabal (kay="AP1-46¥")
eine
ews(uery="Linux", souree="ern")
print PTitle: (news content. title)"
URL: {news content. url)"
Penuthor: (oans_content.asthor)")
The Python Book 34Allow the Python seiot
toruninatermina,
and outside the IDE
Human inputin te form
fintogrsisused for
comparingmoves an
uitimately. playing the game
Usedeductionto
determine ono of
tree outcomes
Loop the code over
againand start
fromthe beginning
Appendtointeger
veriables to keep track
of scores andmore
Code a game of
rock, paper, scissors
Learn how to do some basic Python coding by following
our breakdown of a simple rock, paper, scissors game
This tutorial will guide you through making, 25) enough to adapt and expand a
Resources
Python 3: wvorpytnonorsownions
IDLE:
132 The Python BookPython essentials Ml
1 Reset rere te ee ton
‘retonsiallneedfrthecode—theyre
stl pars ofthe standard Python leva, just
rotpartoftedetauterirmert
02 miter re nec
here. Thattresverableswereusrgard
thelr relationships dened. We alse provide @
variables wocankesp sco oftregares
3 wetegnte recom by axtnrete
start ofeach round Theendeachpay
session comes back through her, wheter We
warttoplayagsinorrot
The game i actualy contared ah
her, askrg forthe payrnput, geting
the computer input and passing these onto ge
thareadt. tthe endo! tha then asksife8
etoplay again
Payor rout dono re, We ge the
lye informatio on how to ay ie
partcular version of tre game and then alow
{heir eheice to beused inherent stp, We also
have something in pace in case they enter an
imaldeption
Therearea ew tings ingen hen we
show thareauta Fret wereputtngina
delayto de soma torsion appending avaible
to ome printed wet, an then comping whet
tho player and computer di. Though an if
statement, wm choode what outer,
ndhowtoupdatethescoes
Wo ro skort input on hater
0 o.
or not someone wants Yo play agin.
Depending on thei rsponse, we go ackto the
startorend theme andlspay terest
‘ThePython Bock 33,BA Python essentials
The breakdown
1 Srpetesarzth noah ote
Python interpreter here. This allows
Us to run the program inside a terminal or
otherwise outside of a Python-speciic IDE
Tae IDLE, Note tat wet aleo using Python 2
rather than Python 2for ths partiouar scrip,
which needs to be specified inthe code to
make sure it calls ugon the correct version
fromthesyster.
a
# Linux User & Developer presents: Rock, Paper, Scissors: The Video Gane|
‘import random|
import time
Gat
paper = 2
scissors = 3
‘names = ( rock: "Rock",
&
‘player_score = 0
computer_score = 0
OG terse rteterinagara
and the tot representations of each
move fr the restof the cod, When elle pon,
furseret wl print renames of any ofthe tee
‘moves,mariytotl theplayerhonthecomputar
‘moved. These names ae only equated to these
varabies when they are needed ~ this way the
ruber ssid to each of hem ia maintains
vets ned.
Eins
‘There are other meduls you can import with
basic Python. Some of the major ones are
‘shonn tothe ight. There are also many more
‘thatareincldedas standard with Python,
34 The Python Book
rules = ( rock: scissors,
O2 Yersinenrresnoertsmedieson
top of the standard Python code £0
we ean use some extra functions taughout
the code. Well use the random modus to
‘determine what movethecomputer vill ho,
‘andthe tme module ta pause the runing of
the codo at hey points. The tm module can
‘als be used to tise dates and times, ther
tadisplaythemor otnerwse.
‘scissors:
‘Scissors
OB see esta nate tocar of
‘thevarabes redefined enduseconty
‘hen needed, the ues are done in such away
‘that whan comparing the resus, ou variables
{are momentarily madi. Further dow nthe
code wel explain propery whar’s happening,
but basicaly after determining whether or
rot there ati, well see ifthe computers
rove woud hae lett the player move the
computer move equsls te losing throw tothe
playersmove youin
3 Wetgssicsenenreveo aspects
umber so that once a election ie
‘made by the player during ta game iil be
‘equated to that speci variable. Tris makes
‘he code slightly easier later on, a8 we won't
‘ee to parse ary tect for this parteular
function fyouso wish, youcanaddaddtional
moves andithswillstarther,
“Scissors” J)
paper
OG Wersrneticces avr ar
can be used throughout the code to
wp track of seres We need to start at 270
ow so that it exists, cherwise i we defined
itin a function, would ony exist inside that
function. The code ads pot tothe computer
orployerdenerdingentieoutcomed! heroun,
although we have no scving fer id games in
‘is particular version07 troveseinreacuneerringt nea thie funion
woe callod start ts quite simple, priting our restr to the
Player end than starting awhile oop that wl allow usto keep peying the
fameas many times as weuish, The pas statement ais thos oop
tostoponcesee finshed andoaudbo used toperermanumbarofather
tasksifsonished. vedo stopolayingthe game, thescorefunctonsthen
called upon ~ wel over nhatthat does when we gttoit
‘ive kapt the game function fay sole so we cn breakdown
‘eachstepabitmareeasyinthecode Thisiscaledupan fem the
star function. and fit of ll etermines the payer mavey alg user
‘the mows tunton bso. Once that’s sorted, ses the computer move
ute the random module's andi funtion t get an integer baton one
and tre 1,3. thon passes the player and computor move, stored as
‘togercnothereaultfuncton which we usta findheouteams
der start(y
print ("Let's play 2 game of Rock,
while game():
pass
scores()
‘game () =
player = move()
computer = random.randint (1, 3)
result (player, computer)
return play_again()
Paper, Scissors."
def move ():
while Tru
print()
try?
player = int (player)
if player in (1,2,3
return player
except ValueError:
pass
[Be Est Shek Oeuy tens dows
print ("Oops! I didn't understand that. Please enter 1, 2 or 3
layer = rav_input ("Rock = 1\nPaper = 2\nScissors = 3\nMake a move: }*)
awhile oop. The whole point of mave ist obtain
|). 22 7 07 ot
me's nove! 3
‘=n integer bate cn and thee fram the playe so the
‘le oop allows us to account forthe player making an
(0+ for nore information, Unsupported erry. Next, wo are setting the player vase
tobe created from te playa'sinput with raw. input. Weve
‘soprnted instruction arto goaong ith The-\ weve
Used inthe text ad a ine break: this way the instructions
copear esas
10 Mesn.sezernt urd can up coe na
handiserrors other excoptions Woparsewhatthe
player entered turringit nto an integer using int). We use
theif sttementtacheckiftis either, 2,er3~ifti, move
returns this valve back up tothe game function. throm
paVluetrrer ne use except to dorothing printsanerer
‘eseage an the whit loop starts ogi. Ths wil happen
Lunti.an acceptable moveis mace.
‘The Python Bock 35
acede by the umber cf secardsin the bracketa. lookup whattho txtversinfthomoveiscalled
lWe\e put #one-socond pause beeen courts, fom the names we set eater on, ard then to
1 recesses thonhalfasecondaftethattoshowtheresuts, _ingorthet here (0,
pocaworgaatera wee
viyroonsanrensgnmcemmc vers
suirgat hahaa carton trea
Tetris tan ene ae
‘eingted Sap pasen een
Topi out what be campate ven, 4]. Hae wees eng te rs vo
wee using sting format The (} inthe st ear Using the global function
preted tert where were isating the move, allows fr the varabe tebe changed and used
‘hich wo have previously defined ae numbers, outside of the varabl,eapecial after wel
UUsngnameslomputer weretalingthecodeto eopendedanumbertacnectthei sores.
‘def result (player, computer):
peint (*1...9)
Eime.sleep(1)
peint ("2
if rules(player] =~ computer:
print ("Your victory has been assured. *)}
player_score += 1
Print ("the computer laughs as you realise you have been defeated.")
computer_score += 1
ese
baccalytroughaprocessofcliination. | ie Ek shel Osby Optns Windows Hep
Ox fret check 9 S08 the move the plner rycnon 2.7.3 (oetault, sep 26 2012, 21/5119)
‘ad computer used were the same, which isthe |2ee 4.312], on risen?
siroestpar. Wo putitinanifsttomentsothat |ype Acopyrigne®, seredite” oF ‘License ()* for nore information
ifts rum Bis pater section ofthe code ends cnesraRt
ere. ether pris cur iomesage and gps back
‘othegamefunciontortenenste,
5 Mtrtate.woneediotomtecrg
sit could sll bea win or aes WS
the ose, ma start another statement. Here, a nove: 8
te use the rules Uist fom earler to 208 ithe YGldn't understand that. Please enter 2, 2 oF 2
lesing move to the payers move isthe same
as the computers Mats he case, we Bit
the message saying £0, and ad3 one to the
lye scorevarable rom before
1G terest te ae hast
We pint the losing message. ghe the
computer a pont and it immedataly ends the 1 Rock
feoutfunctonetuningtothagamatuncion, [se gene. I
36 The Python Book,17 Pecos en oe cle won | Singscovancntonchynttevehaw AQ) votonatanceceresrc ne
play. senn funtion ko the reve should expecta response in kind, The villassume the player dos nt wart to
funeton aha huran input sokingthe payer statement checks to see if any cur detined play agin. Well pie a gondbye message, arc
‘ftrey woud play agen va atertmeseage postveresponseshavebeenertered As Python that wil and this funcen. Th wil also cause
taithran rout nithtneompla'yn uagestion doesnt differentiate betwen uaper or mer the gam funetontomeweorta the rex ection
anattomptoaiot anaupectedrosponsn. case, weVomade sure that tacceptsbothyand androtrestar.
‘this tthe case etumes postive respons
‘ogame, hichuil steritagan
return answer
def scores():
global player_scor
print "HIGH SCORES"
print "Player: ", player_score
print "Compute: computer_score
computer_score
IFalschastheELF(lseoperatrwhichcan
Tython 3-7-3 (detaste, ETT be used in place ofthe sacond IF statement
(ce 4.9.2) on Limuna’ we employe. t's usualy used to keep cade
Hype tcopyrigne", ‘ered toa, but parfermsthe sare function.
2 play © gune of Rock, Paper, seissers 20 sree otto sa ttn, st
{ae fishes.emoveontatheresuts
Thissecion cals the scores, which areinteger,
ancthenprintsthemindssdualyatertherames
Make a nove? 3 ofthe layers, Thisietheend te evs as fa
Oops! didn'e understand that. Please et aera, Seana
wont parmanenty save the sores, But you can
have Pythen me ttoafleto keep ifyouwsh,
ake «nove 21 eins pt ton ee eve 0
be used in tivo ways. Fel, we can
freee it in the command ine nd it wil ore
eeapster these Bock! fine Secondly, we can impert this int athe
He gene . Python srt perbapsifyou antec adits
eta ge 2uke ve play apsiny ria: ‘gamer acollecton. The way, twat execute
thetcode when being ported
‘The ython Bock 37{ctor et oe ort co ‘iertiniw pres Code listing
[ete
ee apin proving abl 20 s
ontop se of
‘ur very basic raphis imolve ASO
arefthe games stages, printed ot
stereeytm
Programagame _
of Hangman
Learn how to do some more Python coding by following our
breakdown of a simple Hangman game
‘One ofthe best ways to got to know Python is
by bulang lots of simple projects so you can
understandabit more about the programming
language. This time round, wee looking 2
ul up th
Python 3 wamovtoneryoweioes Hangman stit doesnt require
IDLE: wenythonargise set of modules, but it's @ ite more advancer
38 The Python BookThe actu! game starts here, ith 2 whe lop 10
on essentials Ml
Pytl
et you continually play the game until you decide. [er searto: Code listing continued
orn oanenongevepem FE ae on i eee
7
ot amen
‘The game rules are decided here, a wal a the
‘stp forthe word ana keeping rack of tise ard
Inconectanewers
cn ound ofthe gre played here, aking for
ning thentalingjout youaracorect or not
Inprnesoutthe graphicandchangs ayvarables
‘hat need to be updated spec ncrect 28
caret guesses
Alter es ound, theca checisifyouve wen ot
lestyet~thevaineonstion big tat you guessed
‘he worderlosngtyouve mode guesses
The human input forthe game takos the latter
tara tums into something the code can ue. 6
Vere n te prvous Bick of cage and then
referred backtoifyouve entered an unsupported
raeadyused character
‘The same clas as last tine, wich allows you to
alec whether rot you wish ay again
‘pen quitng the game, scores ae gen forthe
duration ofthe play session Wealsoendtneserot
tithtneif_-rame. code before
OLE automaticaly hghightsthecodeto
make roeding your work tat it bit ase.
tals allows youto change these colousand
‘ighlghtingin OLE Preferences, ncace
youre cle blndoarejustused oa ifernt
Colour scherain gaara
rly = Cyr mage peng)
sors action
erties rood
Selec
‘eters rit
laters rang eis esau
‘efter eter)
Feedage re Aeterna:
Peete aie
variate sae ete
frst inserter)
enor ten erat)
ms
harper ean)
eee elon
Promos lettre)
Frome nord ae
16 ehtay me
ie at
Frame nord snare
Sige =
retusa
feo
Inter = roc ito gs ot cor mtery ser”)
Iineratag
to
a sno
Fe ary he gy se 9
ram ou very mh Frying ve. See You ret te")
cpr sar, computa acre
re (er Se
(Chane payer soe)
Fit Combuer! © Santer co
per
‘ThePython Bock 39Isee ASCIL
Hera actose-p ofthe seven
ager we veuredforHangran's
traphie. You canchangs them
yursalfbutyouneedomake
Surethequotemers area
‘thecorectpacesothatthear
‘sooneisereda text strngtobe
pentadout
40 The Python Book
[ay #!/usr/bin/env python3
Gf ron random import *
player_score = 0
‘computer_score = 0
def hangednanChangman):
graphic = [
GF cer starto:
Although we've moved some otheralesto
‘the'game function youcanalnaysputthem
‘backhereandcalluponthem using the bal
variable, as we would do with the sores For
thewords, jou could alsa reateaseporate
fla andimporthem ke therardom module.
print(Let's play a game of Linux Hangnan.”)
while game():
pass
scores()
1 ates sna in or san
to the Python interpreter Ths allows us to
rancho program inside ternal or therwise outside
of a Pythen-speciic IDE tke IDLE. Nowe thet wate
aso using Pythan 3 fr tis partes, as ts
Installed by defaut on most Linu Syston ard wi
thoreFreaneurscarastaty.
2 Wir irertcane vars mot soy
dferenty tis time, imperting the acta
names ofthe funetions fom random rather than just
tha module eal. This lon us tous tha functions
without haveg syntax tke rendomfunction. The
storie imports all tho funetent from random,
though you can sith that for specie names of
ny of rand function, Wel be using tha random
funetiontoselectawordfortheplayerto guess.
OB sorceress rota ana tan
be used throughout the code to Keep track
‘of ecores, Wa need to tar i at 26a now oo that
‘ists otherwise fwedetinedit ina function, would
‘only est inie that function. The cod adds. point
tothe computer or layer depending onthe outoome
ofthe round
OG eis tic: a ta sian
{SOI hangr@ man stages. Were stong
thoce ina fureton as a lito separate sting objets
s0 ve can call upon them passingon the numberof
incoract guess to. There are coven gape inal,
lin te per-and-paoor orion. We also irlude the
print command with he funtion, sowhen scale it
wlcorpletlyhandle te selection and cpa ofthe
hanging man wth the rstone beng ined ater the
fet ttre guessed
OB ascii etal tn oe
code, with the function wee cal str
Ice quite simple, sxining aur greeting t te player
and then staring while oog that wil alow us to heep
laying the gareas many esas ve wish. The pass
Statoment allows the while loop to stap once wee
finished, and could be used to perform 3 numbercer gomeg:
dictionary = [
word
word_length = len(word)
clue
of ses =e
letters_tried
guesses = 0
letters_right = 0
letters_wrong = @
nu”,"kernel”,"Linux”,"nageia”,”
choice(dictionary)
word_length * [“"]
global computer_score, player_score
gf while (letters.wrong != tries) and (*join(clue)
word)
letter=guess_letter()
if len(letter}
and” letter-isalpha():
if letters_tried.find(letter) !=
Print(“You've already picked”, letter)
of othr task f so wished do stop playing the
ma, the score function then call upon wl go
‘vernhat that coos when we gettat
OG Wteaes art ot we se
in the gama! funtion this time around, 05
thors nt as mich that needs to be sot un. You can
spite up further # yu wish, using the style of ce
from last issue ft would make the code cesner
foryou orhelp you understand the buling Blocks &
bitmoc,
7 Te ere ese ty awh nr
for the player to guess. Weve got a small
selection of words ina ist hee However, these can be
imported via HTML or expanded upon. Choie is used
toseact random element fromthe li hon comes
from the random module wa imported. Final, we
ascecan hw log the ring ofthe word to GUESS,
and then create the cue variable wth a number of
undarsceres ofthat ant This is used today the
‘eras bulsitup from guesses.
OG Besztespteniesanste nit
variables to Keep track of during the game
There can only be si incorrect guesses before the
hanging man i uly aw, orn our esse dave,
0 wo sot the is variable to sic Mel keep track of
the letters hough laters red torake sure thatrot
‘only wl he player brow, but asa the code fer when
it checking against laters aeady played. ral
we creste erpty variables forthe numer of euacses
‘made, letters corect and eters incorrect. rake
‘he code elghty eater He alzo import the global
scoreshers,
Wore stating a white loop t perform the
Player selection and chock hm status ofthe
gna Thsloep continues unt th player wins ores
Ista by check al the ties have been used up
by soning ators wong rot equal tots. AS each
‘by wl only aad one port to wrong it wll ener go
bovesic it then concatanate ut and sees the
‘same asthe word the comeuter selected, Itoh these
Statements are tue goes ontothe return,
1O ates faction nate ang 0
input letter and give i the variable ota
We check what i ruins by frst of all making se
it only a singe letter, with enter, then by
Using isalphato sof t's one of the 26 eters ofthe
alphabet. these condions are satisfied, we start
‘naw if statomert to make sure ts a new gues,
‘and tal the payer its already been chosen 80 they
an start again fal thi is acceptable, we move on
tothe next section ofthe cod to se fs a correct
escort
i:
yenguin” ubuntu’
Whi DLE witkep rackof tho
indertsin tecode,yeureusing
_testedtorto wits some Python,
youllnav to make sreyoure
Usngthem correct Pythons
‘verysorttvetowhatheroraot
indents aroused correcty anit
doesn reaebiy a wel
“The Pton Book 41TN
‘Tha codeinatitgartofthe
‘ene fucton we stated onthe
prevouspage, so make eure your
Indertatonsareinalgnent| |
youre not using an. youpln
{ospitthiscodeup, we'dsugzest
‘starting withtnowerdelecton
adress,
Bir letters_wrong
se:
a letters_tried = letters_tried + letter
first_index-word.find(letter)
if first_index
letters_wrong 41
print@Sorry,",letter,"isn’t what we're looking for.”
else:
print’Congratulationsetten"is correct.” FB
for i in range(word_length):
if letter wordLi]:
clueti} = letter
ie
hangedman(Letters_wrong) |
|
|
else:
rint(“Choose another.’
print (“ "join(clue))
print (‘Guesses: ”, letters tried)
trie
print(Game Over.”)
print(The word was”,word)
computer_score += 1
break
-Join(clue) == word:
print(‘You Win!)
print(The word was”,word)
player_score += 1
break
if
return play_again()
—_—&i
AA tsar a id acetin
the Fist ting ve do is adit 10 the ist
of letere tiled. Ths Ie done simpy by ade,
the stings togthar Wo an use the fied
commando search the ard sth forte tr
lente ohio vl then return a umber ofthe
agement oftheleter inte sing, does
Fd the eter returns 1 wai. ich we vse
inthe nar statement to ee ithe stro
Variable 1. sa, it adds one ta the number of
leters_wrong and then prints a message 1 lt
thepiyerknow rat tssanioorect UES,
AD tnsegt ew ost en
incerect. than we can only assume
Ie is caroct. Trough ths simple prooess of
{42 The Python Book
limination, wa fst printout a message ta let ran graphic a stands, by cling the graphic
theplayerknow thattheyve been suscessuland in the lst that corresponds tothe number of
thenmakearecordott ‘rcomect guesses thet have Don made. We then
pint how tho cue cura lok, with a space
1Q Weewrstosia sation hoes bevean eh chee hen it re
we can update the clu withthe corect numberof guesses thathavebeen made.
later wee added. Neuse te ange futon to
tate rdeton mary nese vsh ota He wo check ef the ge
cer th cue by using the word lergth variable cer again, fret f all compar the
We ten check to ee whic eter inthe word eters_arong f0 the numberof vs hats
hs boon guested corecty and change that tus, we pint a message that the game has
pacficpertfthe ca tobe that ter o\tcan ended andrew the mysteryatthe iden nord
be pimed out fer th playerto eee and for us to Waincreas the compuzers enore andra the
check nhetherornatthegameisove. cop. The next ep checks to se if te Tul ue
concatenatedisthesameasthecrigna vard—if
1G teeeibecgnaitessoanty arg tatsthecas npertbvin message ef
the player to choose again ifthe drat wordardaddone pootatheplaer sorbate
err a supported input Before we go onto the breaking the laop agin. Ths can also be dorw
rest ound of chotes, we pine aUt the hangre with fSandels to wad using eke,Oder guess_tettero:
print,
letter = raw_input(“Take a guess at our mystery word:”)
letter.strip()
letter: lower()
print()
return letter
q def play_again():
if answer in (“y", “Y", “yes”, “Yes”, “OF course!”):
af answer = raw_input(“Would you like to play again? y/n: “)
return answer
a else:
def scores(:
global player_score, computer_score
print(“HIGH SCORES”)
print(“Player: ”, player_score)
print(“Computer: ”,
af ;
startQ
16 ies aero sen ety
calling upon return again. which we wi
thonpassalithe ayuptothestartfunction once
iestevane,
17 Bein eo frtion tat of
all pine out @ raw input message.
‘noe the player enter the ete, the function
arses fo be used wth the rest ofthe code
Fraty, sips used to remove ary whitespace
from the input gen a we've et given it ay
foua parameters. We then convert it ino
lower-case letters, 3s Python wil nt be able
to correctly compare an upper-case character
wth alover-eacealtematve, Ws then print tho
Election fr the record and return feup to the
game functon,
18 eseszeet mame tonite
ask he payer if they wish to try again
The play_again function takes a human input
with 0 simple message and then analyses the
inputse itknowswhat tosend back
‘computer_score)
19 Sire sous anon ot yr io ne
have shoud expecta response in kind
The if statement chocks to s9e if any of our
defined postive responses have been entered
Since Python dferertatas between upper and
loner caso, woe made sure it acopts bath
Yard If thie tha case return a postive
Fesponae ogame, which wilstartitagain.
20 resort n eects soos,
we wil assume. the player dose
ok want to lay again. Well print a goodbye
‘message and that wil end this funtion. The
‘nl aso cause the star furetion to mae onto
thenectesctonandnat tar.
DA Sn ny back te st
function, ater game Fries we move
lontothereeults.Tissectionisquiteserala i
calls the scores, which are integers, and then
pints them indus after te names ofthe
Players This ie the ond ofthe sero, a8 for 98
‘he player isconcemed. Curent. the coda il
print(“Thank you very much for playing our game. See you next time!”)
‘Now tat you'vefnishedwith the code ty
‘otmakeyeuronn changes? nreac the
wordeoutt create ferent, selectable word
categories; or oven et people gessthafull
‘wor ouhawe alleen Sots inthe
‘umentcede and astnanths tori
rot permanent save the score, but you ean
have P/thonriteitoaietokeepif yous,
DD. i0 int part te cose aon fo
the script to be used in two ways
Fray, we can exgcute it inthe commard ine
‘nd tll wrk fine. Seconds, we can import
Unis into anether Python sori, perhaps i
you wanted to adit asa gamete acollecton,
‘is wa wl not execute the code when
boingimported
“The Python Book 43Play poker dice using Python
Put on your poker face and get ready to gamble as you hone
your programming skill with a bit of poker dice
Resources
Python 3:menpythonertownioas
IDLE: senonoratte
TheStart
Here were dong ome minor setups so we con
fet or code to run with some extra madls nt
(rotuded with th bases
TheRules
\Were setting nas foreach sera so they con
‘be propa tented to the player ~ much more
intovatrg thar rors
TheScore
‘Aainwe've gat smebasc variables setup owe
Cankee aor ofthe gamesifwa want
TheSeript
‘Theguchandied here pacsing te ployer onto
Benetuncteno typ endhnaingte
We acess the fll gum loop via hee, aed the
function that alls us to play again if wee
ssinctined
Theinitatnad is deat, soo speak atte start
the throws funetion. Thi uncon handles al he
econ makngin the gare, while pasingef he
‘doe rola toanather function
atone eine
Weve az gota special inci so we caninform
eralls'= tputwon any de o you want £0 row agai °)
TheDecision|
There are two rounds inthis version of poker
‘om an you can esac how mary ei you wish
torellinthissmall he oop tat make sre
Yyourealsosingacorectrumber
“44 The Python Book
‘So you've learnt how to program rock, paper,
sclssors and guessed your way to victory at
hangman, tow fs time to head Las Vega
and lay cur cards eg. Or nti case, tut
ico, a8 wo continue wth aur Python game
tutors and inode yout somepoker de
again using ome of the lssons we've
yy Ibert. cluding. random number
tion, lst creation. and. meication,
human put. rule setirg,ecorng ard more
But wll algo be dng soe new sls tes
Sore
sts
i gan
scot
>
TE eee:
LO peneotee
Fret in 23049)
tutorial Namalynelbacrestingand appending
let with random rumbers, and using functions
‘multiple mes none block of code to ct down
onbioa.
gin, we recommend using IDLE, and wate
using Python 210 ensure company with @
vider arty of stro, including te Raspbery
'. So, wehopeluk's@ adyoryou and thatthe
‘ds are ever in your favour ~ just keep those
fingers crossad that you dont ola snake eyes
(waarecedrgin Python, after all!
Code listing
Driven’ ploy» wane of Linu Pte Des.
rire The copter wil ela yu tron your 5 ce)
roster)TheRe-roll,
Wore dong the second sot of ros and staring
the ond ofthe game hare by caling onthe same
function ab before, but woe also aware that
choosing evlsmeansthecndofthagame
TheDice
Here mee findingout which ice the player wants
to rerol, and also raking sre that thay enter
abd nue, Jt 80 ey Kron theyre dong
“omething we printaomething forever tre
‘Second Hand
‘We change and dela the new dee hand to ond
the game gain, we make suze to tal the player
‘hat th ctalhand theyhave le
TheRolls
“The function we ruse to rol or Vite ie
Season wt, coat Code listing continued
2 eeaeereD
incite: mse” of 2 ace to ral: *)
election
ir atacion in 2.438:
pt did't nderstrd that, Flees enter 1, 2, 3, €or 89
cersion i)" sleet
nied ee changed ce election)
leeaice chargestieratine 1) = replacement
sexsi)
FE eaectesicey
ince masta
eau = region
sig simplo whl lop. This allows us to keep "af ripe faery
thavodebase smaller pp ler ncn,
Sie nee abe
‘The Analysis Gleriterationi = ronda eicetnnters)
‘There are eight prone typee of harden poker eurn te
dee, and we ean ue a ie tog t work aut all et
bitdnect them witnouteneckingagainat al 2776
‘outcomes — infact, we only special have to
cheaktortwo
‘The Question
‘arse ly agar urction that parses player
Inputsoweenestartorendthe sgt
TheEnd
‘Sorat are depajed ath end ofthe ait and
‘the very fal part alls us to import tino
cterPrthon siptsasamedlo
‘Spltingupsctensiuofurction makesit
ier tonot only perform them mutipls times
butreducetheamuntofcade Onlnrger
projets is ean acwithapeed
SS cerca forbs, ei in robin
Street = hogs)
Seutme > Bae)
18 dice = strane o en
Nar ee
co de hat
ate hart
strain
turn Mang card
play aganos
Teo Yels you ike to lay oe? ys")
ber" toe," coro)
int Thank yeu very mich for paying or ane Se you est tie!"
sore)
ES acs, cote se
Fineoyer poe score)
Fnteconpor’ fete tar)
‘ThePython Bock 48#l/usr/bin/eny python3
{import random
Aa
names = { nine: “9”,
player_score = @
conputer_score = @
Be stro:
Drint@Lat’s play a gone
while gameQ:
pass
seores()
Of
return play.again()
01
‘Ag before, we use this ine to enter the
path tthe Python interpreter. Thi alls us 2
Fn the araram side & terminal or atherwise
‘outside of Python-spectic DE te OLE. Note
thatwerealsousingPython’ forthisseret
02 rete
Asean mporietherondomradue
foro etre oreo ot te oun
functonsowecan verte dosina wo fais
tore rede ard ese arly en
tart sayer nathan howe
03
Write wet using random numbers for
thodoe rol ules we assign the cere cards
to each number, the payer wort know what
theyve rolled and what eonstiacs a batter
hand, Vie set each card to a number and then
equate nat these should be printed out 8s
04s"
‘Ae usual, we have the empty scores
for the payer and computer so we can update
46 The Python Book
ten: “10%, jack:
from itertools import groupby
of Linux Poker Dice.”)
help you throw your 5 dice")
these as we go. Whi it's not epactclly used
in this version of the code, its easy enough
te expand on it and add your own simple
computer el oriited Aor bata
5 irre ne rcne prc be
cosinor tan pe ost
‘Ste tars ante opal aly
orybe great mnytnes va
Termbsaren slowest sep
reo uve fh fe so pin fe
fu unc titanic
06 ="
Uke cur Rock, Paper, Slesors code,
dat game pawnstherestof the gameortocther
funetone, th ts main function alloving us to
hoop ropeating the game by paacingthe payor
througntotnepiay_again function.
o7 me
Fer our fist thom, wa want to hav ve
random dic. WeVe seta variable hee to pass
onto ourthroning function, alowing uso reuse
queen: “9, king: “",
“There ae a few variables that
pve pnts uct th
ia weve been eae
penn
we want them 1, 5 rot the
best code conduct. The names
ofthe variabes dont epecicaly
matter ~ it jst best to label
‘them nay you understand or
bugtxingandotherstoreed
ace: “AY 3
It later with a eitterent number that the player
chooses, We gat Five random numbers na st
‘retuned rom the funeton, and weer itusing
Sorttomale ta bitmorereadate forte player
Andalsolatoronforthehanatunction
Dicedlsplay
Wi print ot asc dice, umberingthom
0 the player knows which dee is whic, ad
‘also ghirg tthe name we stat the ear ofthe
Serpe. Were ding this with atop that repeats
‘eal the number of times ab the doe ict
long uss the rengxencioe) argvment. The
Fe ineresced each tun, end it pnts out tht
spsctierumceroftha dia ist.
Currenthand
‘ie want to tnd the toe of hand the
player has mltpiotmos ur tho game so st,
‘spect funebontofind out We poss the series
ofdcewehaveontathisfuncten onder.
10 teneein
Before we can thraw the doe for the
s200ed round, we need to krow which eee thedef throws0:
roll_nuber = 5
dice = roll(roll_nunber) Watch the indentations again as
dice.sort() tae apt the else funein. The
for i in rangeClen(dice)): folioning page's codes on the
ine“Dlce"s 1," namesLlice! tne tse ro rer
aaelmmaiaiadad reac ice_rerolls and dice_changes in
result = hand¢dice) =
print(You currently have", result)
while True:
rerolls = input("How many dice do you want to throw again? “)
trys
AF rerolls in (1,2,3,4,5):
break
except Valuetrror:
pass
print(“Oops! I didn’t understand that. Please enter 1, 2, 3, 4 or 5.
if rerolls == 0:
print(You finish with”, result)
else:
rollnunber = rerolls
dice-rerolls = roll(rol1_nunber)
dice changes = range(rerol1s) The big if funtion atthe end of
print(Enter the number of a dice to reroll: “) throw doesrt have mary Une
iterations breaks between sections = you
vuhile iterations < rerolls: canadtheceas muchasyouwant
iterations = iterations + 1 to break up the code ino small
while True: chunks vival aiding buen.
selection = input
try:
if selection in (,2,3,4,5):
break
except Valuetrror:
pass
GB mintoopst 1 aish’t understand that. Please enter 1, 2, 3, 4 oF 5.”
dice! changesTiterations-1] = selection ~ 1
DringC'You have changed dice”, selection)
doer varistoalagin Nesta isang of isto long fon carts. ho 4. Pare
‘them how mary revels they want tod, which userwantstore-rolzero tines, then that moans
We ask the player to ter the numbers
‘allows ust race a custom wil oop to ask heyehappy withthar hand, anditmustbethe of tha dice ty wish to ral. By sting an
"the user whieh coe ta change that estes the endothe game We print amessage to ndcate erations variable, we can have te while op
conectnumboroftimes, ‘his and ply thee hancagan. last the ene number of mesa we wart
Wie also have to make sue i's @ number ral by comparng it othe rll arabe ie
vain he ee ft gar vic why 2p There We check each input to msko sure i's a cubar
Jae check using the ty function, and pint out Heros where we start the second roll thatcanbeused, nda the vaidchoicesto the
amessago which tls the user fardhow ty and theerdof the game, usnga lngelse tothe dce_crargos lst, We use eaten here as
ifstaterent welust started erst ofall make Pythons bag atOratherthan |. elo print
Surets set ourvarabes- wdateg ll_rumbar out a shor maasage oo re player knows the
to pase onto the ol fureten with the roll selection was oveosetl
11 oes
Cheer ening neve ben tyngto do meer oso an can tt ae
inthese tutorials is pint outhow logis can cut the eactlngthoftharawcotcrels wo who a
$0
players. Thisistheendefthe srg asfarasthe when boingron cect,
player concerned. Curent, he cade wil 9
‘ermanenty sa¥8 the scores, Bt you ean have a
Python wrtsittoafletokeepityouwish,
‘ThePython Bock 4