0 ratings0% found this document useful (0 votes) 229 views180 pagesThe 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
| NEW | Everything you need to start coding with Python in Linux
wavatalele
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 rage
eaitaaic
Re eC oe eS Create with Python
rr aoe ey Use Python code within your usual C
i SO eee eer art
Peete teat yoann ees
Seeeeeu 108 Revisit arcade classic Pong
fee tare ee
eeu ne
eet
Peau
PT NS Sere UE ea ec
eens
32 Code rock, paper, scissors PCr eon)
nee eas " restr nets
ay K Mealy chia
Rone mae
earn ate eeeso eae Ca ee cen eb dba
he Aneto Picea’
Bers
Cale ae Pa Cr ee a cr EAA Ll irk leas
eset
Eerie tts a ,
SAS See Serpe Coe er
Persea
56 Bring graphics to games ,
repent ts Soar
eerie
90 Bug-sweep your code
Keep your software project safe
Dea ree)
Develop alight version ofcpin Python 3
2 SO Un aa
Penns areata eteDevelop with Python
resect)
Create dynamic templates
ast ee
Re)
Cee ets)
De oS ra)
recat tne
eT)
Feast reas
COT EE ence ad
aa
Penner
eee
ee ET eTaety
Penne ionomers
Teer og
Part 1 Embed four hacks into a toy
et
et toner as
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 file 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 onlyneeds 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 fle innano
Using tho key combination GAO, followed by Enter. Use HEX
toexitnano.
‘You can run the Hello World program by prefixing
its filename with J in this case you'd type:
Fioumeuingagepid
‘siorncharon en
ove
cele raetieas
feayeatbetecest
10 The Python Book
Variables and datatypes
Avarlabl isa name in source ode that is associated with an
fra in memory tt you can se fo store deta, wich a then
Called upon thoughout the code. The data can be one of many
types including
eres
eee ees
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 wil 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
‘Yusrfbin/env python’
‘We create a variable by writing the name ofthe variable we want folloned
4 by an equals sign, which Is followed by the value we want to store n 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
suatonmans hrllo_str="Hello World”
| hetlo_int = 21
Tresae pineal
Booker volute | hello_bool =True
We ete tiple nthe “helo tuple= (21,32)
ices ay
hello_l
Adal ints 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 therm 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
eee hhello_stappendi this")
hhello_listappend's")
hello_listappend(2")
holo list append list?)
{The ist 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 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 list 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":"Lam’
ates how weve atonad he “Tast_name® "Fraser,
Sarid PEM eye colour")
4 Lets access some elements inside our collections
44 Well start by changing the value of the last sting in our hello_list and
4¥add an exclamation markt the end, The"Ist tring is the Sth element
4 in the list. However, indexes in Python are zero-based, which means the
Notes tat here wilnow be 4 frst element has an index of
‘eprinetneclenent _____ printthello_st4))
hello lst] +="
‘The above lineis the same as
hhello_lst] = hello_ist(4} +"
printthello_lista)|
setae
‘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’ ++ hello. dct ast name’ +*has* +
fo eee helo_dit'ye. colour" +" eyes")
Lees crests sentence wing the
‘daainourhato oct
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 any 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
lessthan5 wouldleok 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
‘ranch
‘Also tore the tgers
‘yustfbin/erw python’
‘8 Wete going to write a program that will ask the user to input an arbitrary
+ numberof integers, store them in a collection, and then demonstrate how the
# 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
1 be wady 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
ints =isto
count =0
1 Keep asking for an integer until we have the required number
while count >>
here, from various
1g. Here is the collection of 50 gems to make your Python
‘onfiguration tools
romembortrat Python takes taba very sorausly
so yousrerecsungaryerorthatmentions
tabs. caect eta soacing
03,
in ova, Crs, and other statically Ope
languages, you must specty the data ype of
the funeton return value and each function
argument. Python & a djmamicaly typed
language, you never hae to ely spciy
the data typeof anything Based on what value
you assign, Python wil Kaan tack ofthe dts
‘ypeinernaty04 Python statements
Setomntn, ee 8 Slot ed rion
Sepunte etic: Mot of te cpl
progurmingingages acheeConsGriioe
toriodare to seperate suerts bd uy
Braet boqwetocosbace
O5 ==and = operators
Pithen as “efor comparaen and
Segment. Pytan does no suppor. ine
scoping the lee wn yu uly art
6 Concatenating strings
‘Yucsnuse'+ to conateratestings.
>>> prine(py'” thon’)
python
07 The__init__method
The _i_rntfodiaruveneon anc
Gfadasobtetrtted Therevodiovet
{oda tazton yeu nate dowith eur
Chet tent robodisandcgstoa
cenevaariner oF don
Example:
class Person
ef init__(self, nae):
selF.nane * none
ef sayti(sel)
print(‘Hello, my name is', self
ome)
b= Person(‘Inega')
p.saytiO
Output:
[-/srefpython $21 python initmathod. py
Hello, my nane is Inego
08 Modules
Te too yur bopens Tamper
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
GF minnaxta,b):
if ae:
clse:
return min, max
Module Usage
‘import my_function
ob
ay
09 Module defined names
3y-Function.minmax(25, 6.3)
“ha buttin function ‘it can be used to find
out which names a module dees, fret a
‘ertedlatofstrng,
>e> import ine
de> dir(time)
Tso.
+ package’_"7 ‘accept2dyear”,
“Bltzone’, “asctine', ‘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 Gi
traiate) of @ modula name by looking at
‘Example:
>>> import tine
>>> print(tine.clock.__doe_)
clock() => floating point nusber
This oxen return th CPU tine oral tine
‘See the start ofthe processor sce the fist
fall tock. This hae as much precision athe
systemroco
Passing arguments
11 toaPython script
Baton les you sees whsver you Fae
fostedtoasorpticalingt To oman
tne seco oobrdin woe art
‘nore sys
prinecsys. rev)
Loading modules or
12. commands at startuy
Yor can ond pdt! modes a
conmande a th ep of wy Fyn
cbt by sng to, sure, vee
SevTHoNSWTUP ou case enormert
Colao SHONSTARTUP too Tw
Cotto the retwcore bad pceoeey
mredubecreomrcs
Converting a strin;
13 todateobject =
: he function DateTia tcomver a
stringtoagstecoject
From DateTine inport DateTine
dateobj = Daterine(string)
>>> mylist = C‘span’, ‘han’, ‘eggs']
>>> print(+, *Jein(aylist))
am, han, eggs
>>> print( ‘Nat Jein(aylist))
span
bam
ees
Tab completion
15 in Python interpreter
jou can sb astocovitin nade Ban
errr by acing these ines 1. Yr
yer ie bro Pyne on
aarug
inport looser, restne
rene pre bin tab: comet’)
‘all ale Fyn comets paral ped
Tieton mefe an rule names whee
preset tees
16 documentation tool
You con pon up 8 goptica cease Br
toring th yon deouraaton whe he
cre
$ pydoe -—
‘onunlreed pte tpicagetrbistor
17 documentation server
cn tho eal nace, THs wl ge you ace
ling scone 1 ali yeh socom,
incite parymadlecroameratn
$ pyc “» “portNanber>
41g Python development
Tere re plenty of toda w Felp with yibon
oiopment Hereara fon mporantones:
WHE The Python buitin IDE with
‘utoconplation, firetin signe popup hel
eateasire,
TBR arctherentanced Python shel with
tebcomistonandothe estes
JBHGS & GU! Python IDE wth sxtocompetion
onset bultinshaland dbase
WINGO: Comerercial Python IDE with
freo ooce aalabie to opensource
dovlopersoveryere
Python Bock 27°Built-in
modules
Executing functions
at the time of Python
19 interpreter termination
Seumec Oyun erpeerermnaon
def sua)
rine cars)
ef message)
rine “Executing Now")
Snport atexit
atexit-register(sus)
‘atexit. register (message)
Executing Now
°
integer to binary,
20 hexadecimal and octal
Usebs
>>> bin(24)
*ob11000"
>>> hex(24)
“ont
>>> oct(24)
‘030
Convertin,
21 charset toUTF-8
ChaeetouTr
data decode(“input. charset. here”)
sreodeutts8)
Removing
22 duplicates from lists
Ty vert to enor leis fon © BE
jut ut erry seta to © Ky Cor
Settee
ere
der astinet()
a0
nopcetiten, (4,)len(), 1, 0)
Fees
28 The Python ook
23 Do-while loops
Src Btn fs 10 drive 0 GOT
tmrawuss Gah yu cor we olen
rrbeteteve neat
thite Tes
do sonethine)
{f condition:
ca
22, Detzeting system
A peton ms
atl tadetect th platfomonuhcnthaPton
ierrtrsuring Youcan ve 2st
tafiadou cure lator.
>>> import sys
>>> sys.platform
“tine?!
>>> ingort sys
>o> sysiplatform
‘darwin’
Disabling and enabling
25 garbage collection
Serine you ay wart enable oF dale
the gum colo’ at urine You can
>>> deport gc
>>> gc-enable
built-in function enable>
>o> 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 String]
Calculating maximum,
= i sum
out of any list or
27 iterable
Youcenusethefollsingbuit-infunctons.
Reruns he argestelomentinth at
Autusthesmalastlarentsthelst
ig function rate the sum of all
slementsintalst accepts ancptonal sacond
argument th valet str wth hen summing
ldetaste too
Representin
28 fractional numbers
oe TY
2, For complex number, a
Separate rmariioisused, called ath
import math
sath. acos(x): Return are cosine of ».
‘ath: cos(x): Returns cosine of x
sath factorial(x) + Returns x
factorial.
30 Working with arrays
defines eon
arrayCtypecode Cy initializerD)
Ge you hve ceed an aay cy
enaed tn partons
syarray.count Go: Returns the number
ieereeeeeetearetia
fyarray.extendGo: Aopends x at the
telet thaarray
sarray-reverse(): Reverse the order
of the array.
31 Sorting items
inort biseck
ect nor CLT ENED
waht)
ators ot be roveruyisharedothe
Tetotenyeisingen
bisect incor leftist, te, Tow
tng
Fears tm ito ttn soed oe fs
tens inte lt be rovertyisharedo the
ieraryectngetesUsit lar
3228 expresso -based
eed
1 search withaepor-based enpresson,
Checkout the eam beion.
>>> taport Fe
>o> 5s = "Kunal i 9 bad boy"
>o> if re.search(*K", 5): print
“tent” # char Literal
Hatch!
>o> if re.search(*[@A-21", 5): print
“watch!” # char class
# natch 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 ade
Satuargtebrzcompesin apsitm
bed conrese() For be?
aera
ban decompress): For br?
deconpresion
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 (conpressed_nessage)
print “deconpressed message:",
repr (decompressed message)
[E-/src/eython $2] python bz2-
‘example. py
original: “Kunal is 2 bad boy!
conpressed message: “BZAOIAYESY\Kc4\
HOFG\x98\x00\x0\x02\x15\x820\300\
HOO\x084%\x80 \x00"\A00\x0e\x64\e\
O30 \xb x65 \x25\xD 31191200
AFB \sbb\x92) \ue2\u84\86 2<\xC0"
deconpressed message: “Kunal is 2
bad boy’
Sanaa rete pial
aos beceaoe me cotigaetan
needed and superior lvelaofprforrance You
‘canusethermedide Salted narderto mvt
‘Sit catabaces,
>e> lnport salites
de> connection = salite.connect(“test
o)
55> curs = connection. cursor)
>>> curs.execute("' create table iten
+ Cid integer prinary key, iteano
text unique,
sconcade text, descr text, price
reat)""")
35 Workingwithzipfiles
‘oveoussthe media fie texkth
Zien
Zipfile.7ipFile(tilenane C, wade C,
compression C,alloweipe4]33)
afletatng oatletbecbect
Hipfile.closeO4
GoowterewetieYoumustal oe ttre
ccigyor pgrencr soa cr lok
town
Zipfile-extract(senbert, patht,
el)
Exrataerber rom te artnet ort
tring dren rember mato rare
fora oro osc Pat sce stot
flrarmorazoriocbect bt thera
satrarcyptdin
Using UNIX-style
wildgards to search
36 for filenames
You can use te mode Bou Tod al he
athnames mating a pttrn according the
‘dss ved ty the UNK sel and charactor
eer nt na
>>> import glob
>>> glob. glob('./£0-91.*")
[gif */2.tx0'7
>>> glob.glob(*-gif")
Cit", ‘card. gif)
>>> glob. glob("?-gi")
cai]
Performing basic file
operations (copy,
37 delete and rename)
You can use the mod hss perfor bk
fiocpraon at anh et Ts oso nets
wis our ropa esa owl wo nh
‘pov es heared pen soca on
shutil.cony(sresdst)
Caistor tothe decry
shutil_eopyode(sre, 6st)
Closteflopemisone tom sto dt
shutil mve(eres dst)
Nosa'tocr dross.
Bae TIS
Esnorels>
Fonrsraycop were dctnyét
shutil entree Gath Ly ignore errors
Fooeneroen)
Dattes snertredrecton,
Executing UNIX
com from
38 Python
The rot oles Pond = aod ya
mea rari tore
>>> import comands
>>> commands. getoutput(‘Is')
“oz2-exanple.py\test.py"
Reading environment
39 variables
Toucan oe the moase oF og SSG
dtr oman
>>> import os
>>> os.path 22> 0s.environ (LANG: ‘en
IN’, “TER: “xtern-color”, ‘SHELL’:
‘bin/bash’, “LESSCLOSE"
“usr /bin/lesspipe % *s",
"X06_SESSION COOKTE":
+ 925464459779 1cTO46S6354ad°56U0-
1257673132. 347986-1177792325",
SSHLVL?: 41", “SSHLTIV?: “/dew/
pts/2", PWD": “/home/kunal”,
LESSOPEN': | fusr/bin
lesspipe
a)
“posix’
33> of Linesen
a
The Python Book 294O Sending email
Toucan we the meile smepit'a canara
Using an SMTP Bele Mal artr Pretaco)
eee Scions pat)
Inport satplib
# Use your onn to and from email
aires
fFronacdér
“from@gnat. 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 = “frongnail.com’
password = soa
# The actual mail send
server = smtplib, MIPC‘satp.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
ote a fy tees
Pron. fo sah an
Canusstetaongton
feolib.FIPCGhost Cy user C, passwd
Ceacct C, timeouti]330)
‘Example:
host = “ftp.redhat.con"
Username = “anonynous”
password = “kunaldeaégnail.com”
Emort Ftplib
import urlib2
Fep_sery = Feplib,
FIP (host, usernane, password)
# download the file
4 = rL1ib2,urlopen (HFtB=//
Ftp. redhat. con/pub/redhat/Linux/
READHE")
# Print the file contents
rine (u.read())
Output:
5S 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
{ho wabbronso? edi pondos a carvaniont
vay 10 loch vonage ware, the deft
vet 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()
“e224b15434229ccBcb35010b0599
18ba1b20c8s?
4 shaz2s Digest
>>> hashlib.shaz24OMEG Classified
Inforwation €27")hexdigest()
*399102F741000022408448 275082907097
7259b460990008955¢2c0"
4 shad56 Digest
p> hashlib.sha256(MI6 Classified
Inforwation €07")-hexdigest()
*2fddes7354872672Fcb39725991689
basso7a7ebfac6t03e fdb33b1c19256"
4 shaza4 Digest
p> hashlib.shas84(°MI6 Classified
Information 027") texdigest()
*5c4914160F3dFEdie14dzecleTAbdab99
de12edc138anf7682000087438A9F540be
e005 c3433658063538720°
# shasi2 Digest
>>> hashlib.shaS12CMIG Classified
Information 027") hexdigest()
*aTQtac3dbo"6e234578482031d838 29025
2c822d1F4873449b850222edec8073b089077
‘seat TaadBeesf8bb18566140667 Fbaf7
peldeifFis2re0c 1322"
1905 Digest
>>> hashlib.mdBC°MI6 Classified
Information 807") .hexdigest()
"Bed Fe52ac 46F129992670c8267126"
Seedingrandom
44 numbers
You can ise te maa Yanda ees
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
4S values) files
les every pop r dain oan
trove Ung rear jocareaiond
wraceavfs
import csv
#reite stocks data as coma-
separated values
weiter = csv writer open( stocks.
csv", ‘wb’, butfering=0))
writer writerows(L
(COL0G", Google, Toe.” 505.28, 0.47,
9.09),
CMG0", Yahoo! Ines", 27.38, 0.33,
1.2,
CET, ‘CHET Networks, The.", 8.52,
0.13, “1.48)
D
¥ read stocks data, print status
messages
stocks = eav.reader(open('stocks.
csv", *rb))
State labels = (-1: ‘dom
“unchanged”, 1: “up')
for ticker, nane, price, change, pet
fn stocks:
labels fenp(Float (change), 0.0)1
print('8s 1s 3s (RSm)" X (none,
status, pet)?
Installing third-party
modules using setup
46 tools
etapa yon pelagic you
dounload bots etal opr an wet
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-
‘$p31¢-maryimux.2_5.x86 64.sanylinxd
¥86_64-nanylinux 2 12.385, 64
many ini 2010_285.64 wh (13748)
Installing collected packages:
simplejson
Successfully installed
simplejson-3.17.6
Processing dependencies for simplejson
Finished processing dependencies for
simplejson
47 Logging messages to
thesystemd journal
You can oe te modu ‘elt wits we
dystem log The use for rain 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
carerttet
inport syslog
syslog. syslog(‘nygeekann: started
Jogging’)
for a in Cia", *b', *e'1
'b = ‘myzeekapo: I found the letter
syslog. sysiog(b)
syslog.syslog(‘mygeekapp: the script
goes to sleep now, bye bye!)
Output:
8 python mylog.py
5 journaletl -b -e
Nov 8 17:22:34 ubuntu python313691:
rnygeekarp: started logging
Nov 8 17:22:34 ubuntu pythont311691:
imygeekapp: 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 pythont311681:
rnygeekarp: the script goes to sleep
now, bye, bye!
Third-party modules
Converting HTML,
48 documentsto PDF __
POF i @ vey ponder medue To POF
' suo pip install python-paF
Collecting pythor-pdF
Downloading python. pdf-0.39-p/36-rane=
ary.whl_ (16.8 18)
Installing collected packages: python=
pat
Successfully installed pythonrpef-0.38
Example:
>>> import yh
55> pa = pydlf generate pdf(‘ with open( test doe pf, no!) 35 F
write out Pa
o> Fuveite(odh)
Tho gonerste_pa function can tke @ whole
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
{eu con corto Tater tig tho Pon
“te mele
$ git clone git://github.con/bear/
python-tittar
S$ cd python-taitter
5 make dev
Example fetching followers ist):
>>> import twitter
4 Use you oun twitter account here
o> aytl = exter. Aoi (consumer.
p> Fedends © mytn-GetFriends()
>>> print Curate for u in friends)
[u'Matt Legend Gemell", u'jono wells,
[The HON Big Blog", u'tanish Mandal’,
iH", UIndLanvdeoSaner can”,
'Facetaron Hillegass’, u'ChacsCode",
Uinilestp", u’Frank Jesmings',.."2
Note that in order to usa 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 Tae Thewaaiore
tance ohne agit an PONS
with eter me bots yr teen et
CDenaP ey brea wrk See toe
eprom orton tenia
S pip install neve-python
‘Example:
Inport news_python
‘oxs = pens_python.Glabal kay="API-18¥")
ent
ews(auery"Linue", souree="ern")
print(PTitle: (news _content. title)"
URL: {news content. url)"
Penuthor: (oams_content.author)")
The Python Book 34Allow the Python seiot
toruninatermina,
and outside the IDE
Human inputin te form
fintogrsisused for
comparingmoves an
uitmately. 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: worsytnonorsownions
IDLE:
132 The Python BookPython essentials Ml
O17 Bese rere te ee ton
‘retonsiallneedfrthecode—theyre
stl pars ofthe standard Python lars, just
rotpartoftedetauterirmert
02 meitiaisar tere neces
here. Thattresverableswereusrgard
thal relationships detned. We also provide @
variables wocankesp sco oftregares
3 wetegnte recom by xtnrete
start ofeach round Theendofeachpay
session comes back threugh her, wheter we
warttoplayagsinorrot
The game i actualy contained ah
her, askrg forthe payrnput, geting
the computer input and passing these onto gt
thareadt. tthe endo! tha then asksife8
etoplay again
Payor rout dono re, We ge the
pljer 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 hone
show thareauts 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.
for not someone wants to play again.
Depending on thi rsponse, we go ackto the
startorend theme andlspay terest
‘ThePython Bock 33,BA python essentials
The breakdown
1 Srpetesarstn repute
Python interpreter here. This allows
Us to ru 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
Thames = ( rock: "Rock",
&
‘player_score = 0
computer_score = 0
OG terse nteterinogara
and the tot representations of each
move fr the restof te cod, When elle upon,
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.
Python modules
‘There are other meduls you can import with
basic Python. Some of the major ones are
‘shonn tothe ight. Tere are leo many more
‘thatareincldedas standard with Python,
34 The Python Book
rules = ( rock: scissors,
02 Vercimearresnoertsmedieson
top of the standard Python code £0
we ean use some extra functions toughout
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 eita nays tocar of
‘thevarabes redefined enduseconty
‘en 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 Wetgsrinsenenreveroaspecie
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 wersrneticcenes avrsiorar
can be used throughout the code to
oop rack of seres We need to start at 20
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 tirovesentreacunteerringt nea ithe funion
woe called start ts quite simple, prising our restr to the
Player end than starting awhile oop that wl allow usto kaon plying 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
‘eachstepabitmareasynthecode Thisiscaledupan fem the
star function and fit of all etermines the payer mave by alg upen
‘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
def starta
print ("Let's play @ 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 EAE Shek Oey tens ows se
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 17 ot
makes nove! of
‘=n integer bate cn and three fram the playe so the
‘le oop allows us to account forthe player making an
(07 for note information, Unsupported erry. Nexo 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 asa
10 Mesn.sazerns urd can up cae na
handiserrors other excoptions Woparsewhatthe
player entered turning into 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 recettotontctmanats thonhalfasecondaftethattoshowtheresuts, _ingorthet here (0,
pocaworgaatera wee
viyuoonsanrensgnmempc vor
suirgattyhaigecartiono trea
Tetris tan ene ae
‘eign’ Sap pasen een
Topi out what be campate wen, 4]. Hae woes eing te rs vo
wee using sting format The (} inthe st ear Using the global function
preted tert where were isarting 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):
print ("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
1422 cee <<
baccalytroughaprocessofeliination. | ie Ek shal Geog Optans Windows Hee
Ox ft check 9 se0f the move the plner rycnon 2.7.3 (oetault, sep 26 2012, 21/5118)
‘and computer used were the same, nhichisthe [Zee 4.512 on risen?
sioestpar. We putitinanifsttomentsothat | ype *copyrigne®, seredite™ of License ()* for nore information
ifts rum Bis pater section ofthe code ends aresraRt
ere. ether pris cur iomesage and gps back
‘othegamefunciontortenenste,
5 Mtertate woneedtotom secre
sit could sll bea win or aes WS
the ose, na start another statement. Here, a nove: 8
te use the rules Uist fom earler to 208 ithe yin’ understand that. Please enter 1, 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 are hast
We pint the losing message. ghe the
computer a pont and it immedataly ends the 0 Rock
‘eoutfuncton.cturingtothagamatuncion, [se gene.
36 The Python Book,17 Pecos en oa cle wan 4 Singscovanctonchynttevahaw AQ) hwo tontanceceresrrc ne
play. sgnn futon. Uno the reve should expecta response in kind. The villassume the player dos nt wart to
funetion aha huran input sokingthe payer statement checks to see if any of cur defined 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(lsefoperatrwhichean
Fychon 3.7.3 (detaote, asta be used in place ofthe sacon IF statement
(ce 4.9.2) on Limuna’ we employe. ts usualy used to keep cade
Hype Scopyrigne", ‘erect toa, but parfermsthe sare function.
2 play © gune of Rock, Paper, setssers 20 sree ete sa tron, ste
{ae fishes.emoveontatheresuts
Thissection cals the scores, which areintegers,
ancthenprintsthemindssdualyatertherames
Make a nove? 3 ofthe layers, Thisietheend te evs as fa
Oops! it dian'e understand that. Please et aera, Seana
wont parmanenty save the sores, But you can
have Pythen me ttoafleto keep ifyouwsh,
Hake «nove 27 in pat ton ee eve 0
be used in tivo ways. Fel, we can
freee it in the command ine nd i wl work
eopeter threw neck! fine Secondly, we can impert this int athe
He gine. . Python srt perbapsifyou antec adits
cota seu uke ve play apsiny z/n: ‘gamer acollecton. The way, twat execute
thetcode when being ported
‘The ython Bock 37