FCM Speciale: Python, volume 2
description
Transcript of FCM Speciale: Python, volume 2
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 1/42
f u l l c i r c l e m a g a z i n e n . 3 1
1 " "
i n d i c e ^
f u l l c i r c l e
P R O G R A M M A R E
I N P Y T H O N
V O L U M E 2
L A R I V I S T A I N D I P E N D E N T E P E R L A C O M U N I T À L I N U X U B U N T U
E D I Z I O N E S P E C I A L E S E R I E P R O G R A M M A Z I O N E
F u l l C i r c l e M a g a z i n e n o n è a f f i l i a t a n é s o s t e n u t a d a C a n o n i c a l L t d .
E
E
D
D
I
I
Z
Z
I
I
O
O
N
N
E
E
S
S
P
P
E
E
C
C
I
I
A
A
L
L
E
E
S
S
E
E
R
R
I
I
E
E
P
P
R
R
O
O
G
G
R
R
A
A
M
M
M
M
A
A
Z
Z
I
I
O
O
N
N
E
E
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 2/42
F u l l C i r c l e
L A R I V I S T A I N D I P E N D E N T E P E R L A C O M U N I T À L I N U X U B U N T U
C o s ' è F u l l C i r c l e
F u l l C i r c l e è u n a r i v i s t a g r a t u i t a e
i n d i p e n d e n t e , d e d i c a t a a l l a f a m i g l i a
U b u n t u d e i s i s t e m i o p e r a t i v i L i n u x .
O g n i m e s e p u b b l i c a u t i l i a r t i c o l i
t e c n i c i e a r t i c o l i i n v i a t i d a i l e t t o r i .
F u l l C i r c l e h a a n c h e u n p o d c a s t d i
s u p p o r t o , i l F u l l C i r c l e P o d c a s t , c o n g l i
s t e s s i a r g o m e n t i d e l l a r i v i s t a e a l t r e
i n t e r e s s a n t i n o t i z i e .
S i p r e g a d i n o t a r e c h e q u e s t a
e d i z i o n e s p e c i a l e v i e n e f o r n i t a s e n z a
a l c u n a g a r a n z i a : n é c h i h a c o n t r i b u i t o
n é l a r i v i s t a F u l l C i r c l e h a n n o a l c u n a
r e s p o n s a b i l i t à c i r c a p e r d i t e d i d a t i o
d a n n i c h e p o s s a n o d e r i v a r e a i
c o m p u t e r o a l l e a p p a r e c c h i a t u r e d e i
l e t t o r i d a l l ' a p p l i c a z i o n e d i q u a n t o
p u b b l i c a t o .
C o m e c o n t a t t a r c i
S i t o w e b :
h t t p : / / w w w . f u l l c i r c l e m a g a z i n e . o r g /
F o r u m :
h t t p : / / u b u n t u f o r u m s . o r g / f o r u m d i s p l
a y . p h p ? f = 2 7 0
I R C :
# f u l l c i r c l e m a g a z i n e s u
c h a t . f r e e n o d e . n e t
G r u p p o e d i t o r i a l e
C a p o r e d a t t o r e : R o n n i e T u c k e r
( a k a : R o n n i e T u c k e r )
r o n n i e @ f u l l c i r c l e m a g a z i n e . o r g
W e b m a s t e r : R o b K e r f i a
( a k a : a d m i n / l i n u x g e e k e r y -
a d m i n @ f u l l c i r c l e m a g a z i n e . o r g
P o d c a s t e r : R o b i n C a t l i n g
( a k a R o b i n C a t l i n g )
p o d c a s t @ f u l l c i r c l e m a g a z i n e . o r g
M a n a g e r d e l l e c o m u n i c a z i o n i :
R o b e r t C l i p s h a m
( a k a : m r m o n d a y ) -
m r m o n d a y @ f u l l c i r c l e m a g a z i n e . o r g
E c c o a v o i u n a l t r o S p e c i a l e m o n o t e m a t i c o !
C o m e r i c h i e s t o d a i n o s t r i l e t t o r i , s t i a m o a s s e m b l a n d o i n e d i z i o n i d e d i c a t e
a l c u n i d e g l i a r t i c o l i p u b b l i c a t i i n s e r i e .
Q u e l l a c h e a v e t e d a v a n t i è l a r i s t a m p a d e l l a s e r i e P r o g r a m m a r e i n P y t h o n ,
p a r t i 9 - 1 6 , p u b b l i c a t a n e i n u m e r i 3 5 - 4 2 : n i e n t e d i s p e c i a l e , g i u s t o q u e l l o c h e
a b b i a m o g i à p u b b l i c a t o .
V i c h i e d i a m o , p e r ò , d i b a d a r e a l l a d a t a d i p u b b l i c a z i o n e : l e v e r s i o n i a t t u a l i d i
h a r d w a r e e s o f t w a r e p o t r e b b e r o e s s e r e d i v e r s e r i s p e t t o a d a l l o r a .
C o n t r o l l a t e i l v o s t r o h a r d w a r e e i l v o s t r o s o f t w a r e p r i m a d i p r o v a r e q u a n t o
d e s c r i t t o n e l l e g u i d e d i q u e s t e e d i z i o n i s p e c i a l i . P o t r e s t e a v e r e v e r s i o n i p i ù
r e c e n t i d e l s o f t w a r e i n s t a l l a t o o d i s p o n i b i l e n e i r e p o s i t o r y d e l l e v o s t r e
d i s t r i b u z i o n i .
B u o n d i v e r t i m e n t o !
F u l l C i r c l e M a g a z i n e
G l i a r t i c o l i c o n t e n u t i i n q u e s t a r i v i s t a s o n o s t a t i r i l a s c i a t i s o t t o l a l i c e n z a C r e a t i v e C o m m o n s A t t r i b u z i o n e - N o n c o m m e r c i a l e - C o n d i v i d i a l l o s t e s s o m o d o
3 . 0 . C i ò s i g n i f i c a c h e p o t e t e a d a t t a r e , c o p i a r e , d i s t r i b u i r e e i n v i a r e g l i a r t i c o l i m a s o l o s o t t o l e s e g u e n t i c o n d i z i o n i : d o v e t e a t t r i b u i r e i l l a v o r o a l l ' a u t o r e
o r i g i n a l e i n u n a q u a l c h e f o r m a ( a l m e n o u n n o m e , u n ' e m a i l o u n i n d i r i z z o I n t e r n e t ) e a q u e s t a r i v i s t a c o l s u o n o m e ( " F u l l C i r c l e M a g a z i n e " ) e c o n s u o
i n d i r i z z o I n t e r n e t w w w . f u l l c i r c l e m a g a z i n e . o r g ( m a n o n a t t r i b u i r e i l / g l i a r t i c o l o / i i n a l c u n m o d o c h e l a s c i i n t e n d e r e c h e g l i a u t o r i e l a r i v i s t a a b b i a n o e s p l i c i t a m e n t e a u t o r i z z a t o v o i
o l ' u s o c h e f a t e d e l l ' o p e r a ) . S e a l t e r a t e , t r a s f o r m a t e o c r e a t e u n ' o p e r a s u q u e s t o l a v o r o d o v e t e d i s t r i b u i r e i l l a v o r o r i s u l t a n t e c o n l a s t e s s a l i c e n z a o u n a s i m i l e o c o m p a t i b i l e .
F u l l C i r c l e m a g a z i n e è c o m p l e t a m e n t e i n d i p e n d e n t e d a C a n o n i c a l , l o s p o n s o r d e i p r o g e t t i d i U b u n t u , e i p u n t i d i v i s t a e l e o p i n i o n i e s p r e s s e n e l l a r i v i s t a n o n
s o n o i n a l c u n m o d o d a a t t r i b u i r e o a p p r o v a t i d a C a n o n i c a l .
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 3/42
gvmm djsdmf nbhb{jof $46 43Õ lqglfh a
KRZ0WRVfulwwr gd Juhj Zdowhuv
Surjudppduh Lq S|wkrq 0 Sduwh <
YHGL DQFKH=IFP&5:067 0 S|wkrq Sduwl 4 0 ;
YDOLGR SHU=
GLVSRVLWLYL=
Vh vrpljoldwh d ph/dyuhwh qhl yrvwulfrpsxwhu xqd sduwhghood yrvwud pxvlfd
suhihulwd lq irupdwr ps61Txdqgr vl kdqqr phqr gl 41333
iloh Ê slxwwrvwr idfloh ulfrugduhfrvd vl srvvlhgh h gryh1 Lr/g*dowud sduwh/ qh kr prowl gl slÛ1Lq xqd ylwd suhfhghqwh hur xq GMh kr frqyhuwlwr od pdjjlru sduwhghood pld pxvlfd glyhuvl dqql id1Lo sureohpd sulqflsdoh fkhgryhwwl diiurqwduh ix or vsd}lr vx
glvfr1 Rud lo sureohpd slÛjudqgh Ê ulfrugduh frvd kr hgryh vl wuryd1
Lq txhvwd h qhood survvlpdoh}lrqh yhguhpr gl fuhduh xqfdwdorjr shu l qrvwul PS61 Flvriihuphuhpr dqfkh vx dofxqlqxryl frqfhwwl s|wkrq qhoulylvlwduh oh qrvwuh frqrvfhq}hghl gdwdedvh1
Sulpr/ xq iloh PS6 sxÔfrqvhuyduh lqirupd}lrql vx vh
vwhvvr1 Lo wlwror ghood fdq}rqh/o*doexp/ o*duwlvwd h dowuhlqirupd}lrql1 Txhvwh vrqrfrqwhqxwh qhl wdj LG6 h vrqrulihulwh frph phwdgdwl1 Doo*lql}lroh lqirupd}lrql fkh srwhydqrhvvhuh frqvhuydwh hudqrolplwdwh1 Ruljlqduldphqwh hudqrfrqvhuydwh dood ilqh gho iloh lqxq eorffr gl 45; e|wh1 D fdxvd
ghooh glphqvlrql gl txhvwreorffr hud srvvleloh vdoyduh 63fdudwwhul shu lo wlwror/ lo qrphghoo*duwlvwd/ h frvÎ yld1 Shu prowliloh pxvlfdol hud vxiilflhqwh pd+h txhvwd Ê xqd ghooh plhfdq}rql suhihulwh gl vhpsuh,txdqgr qh dyhwh xqd frq lo
wlwror %Forzqv +Wkh Ghplvh ri wkh Hxurshdq Flufxv zlwk Qr
Wkdqnv wr Ihoolql,%/ srwhwhvdoyduh vror l sulpl 63 fdudwwhul1
Txhvwr hud iuxvwudqwh shu prowl1FrvÎ/ or %vwdqgdug% LG6 glyhqqhqrwr frph LG6y4 h ix fuhdwr xqqxryr irupdwr fkldpdwr/deedvwdq}d lqfuhglelophqwh/LG6y51 Lo qxryr irupdwrshuphwwhyd gl frqvhuyduhlqirupd}lrql yduldelol lqoxqjkh}}d doo*lql}lr gho iloh/phqwuh lo yhffklr LG6y4 uhvwdyd
dood ilqh frvÎ gd wruqduh xwlohshu l ohwwrul slÛ yhffkl1 Rjjl lofrqwhqlwruh shu phwdgdwl sxÔfrqwhqhuh ilqr d 589PE1O*lghdoh shu oh vwd}lrql udglr hshu l sd}}rlgl frph ph1Qhoo*LG6y5 fldvfxq juxssr gllqirupd}lrql Ê frqwhqxwr lqiudph h fldvfxq iudph kd xqlghqwlilfdwlyr1 Lq xqd yhuvlrqh
lql}ldoh gl LG6y5 o*lghqwlilfdwlyrhud oxqjr wuh fdudwwhul1 Odyhuvlrqh rglhuqd +LG6y517, qhxvd xqr gl txdwwur1
Doo*lql}lr hud srvvleloh dsuluhlo iloh lq prgdolw elqduld hfhufduh oh lqirupd}lrql fkh
yrohydpr/ pd ulfklhghyd prowrodyrur shufkË qrq hudqrglvsrqlelol oleuhulh vwdqgdug1Rjjl deeldpr qxphurvh
oleuhulh fkh or idqqr do srvwrqrvwur1 Shu lo qrvwur surjhwwr qhxvhuhpr xqd fkldpdwdPxwdjhq1 Gryuhwh dqgduh lqV|qdswlf h lqvwdooduh s|wkrq0pxwdjhq1 Vh yrohwh/ srwhwhiduh xqd ulfhufd shu %LG6%1 Yldffrujhuhwh fkh fl vrqr <3sdffkhwwl +lq nduplf,/ h vhgljlwdwh %S|wkrq% qho fdpsr gl
ulfhufd udslgd wuryhuhwh ;sdffkhwwl1 Fl vrqr sur h frqwurshu rjqxqr gl hvvl pd/ shu loqrvwur surjhwwr/ suryhuhprPxwdjhq1 Vhqwlwhyl olehul glsuryduh jol dowul shu hvwhqghuhoh yrvwuh frqrvfhq}h1
Rud fkh dyhwh lqvwdoodwrPxwdjhq/ lql}lhuhpr d vfulyhuh
lo frglfh1
Dyyldwh xq qxryr surjhwwr hfkldpdwhor %pFdw%1 Lql}lhuhprfrq l ydul lpsruw1
from mutagen.mp3 import MP3
FDWHJRULH=
Vyloxssr
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 4/42
gvmm djsdmf nbhb{jof $46 44Õ lqglfh a
SURJUDPPDUH LQ S\WKRQ 0 SDUWH <
import os
from os.path importjoin,getsize,exists
import sys
import apsw
Shu od pdjjlru sduwh ol dyhwhylvwl lq suhfhghq}d1 Txlqgl/yrjoldpr fuhduh oh lqwhvwd}lrqlghooh qrvwuh ixq}lrql1
def MakeDataBase():pass
def S2HMS(t):pass
def WalkThePath(musicpath):passdef error(message):
passdef main():
passdef usage():
pass
Dkkk111xqd frvd qxryd1 Ruddeeldpr xqd ixq}lrqh pdlq hxqd ixq}lrqh xvdjh1 D frvd
vhuyrqrB Djjlxqjldprtxdofrv*dowur sulpd glglvfxwhuqh1
if __name__ == '__main__': main()
Frvd gldyror Ê txhvwrB Vl
wudwwd gl xq wuxffr shu xvduh loqrvwur iloh vld frph xqsurjudppd d vh vwdqwh vld frphprgxor ulxwlol}}deloh lpsruwdwr lqxq*dowud dssolfd}lrqh1 Lq sudwlfdglfh %VH txhvwr iloh Ê losurjudppd sulqflsdoh/ gryuhprhvhjxluh od urxwlqh pdlqdowulphqwl or xvhuhpr frph xqprgxor gl vxssruwr h oh ixq}lrqlvdudqqr fkldpdwh gluhwwdphqwhgd xq dowur surjudppd%1
Txlqgl/ duulffkluhpr odixq}lrqh xvdjh1 Vrwwr f*Ê o*lqwhurfrglfh shu od urxwlqh1
Txl fuhhuhpr xq phvvdjjlrgd prvwuduh doo*xwhqwh fkhdyylhu lo qrvwur surjudppdvhq}d xq sdudphwur qhfhvvdulrshu shuphwwhuqh xq xvr
vwdqgdorqh1 Qrwdwh fkh xvldpr*_q* shu iru}duh xqd qxryd uljd h*_w* shu iru}duh xqd wdexod}lrqh1Xvldpr dqfkh *(v* shu lqfoxghuhlo qrph ghoo*dssolfd}lrqhfrqwhqxwr lq v|v1dujy^3`1 Txlqglxvldpr od ixq}lrqh huuru shuprvwuduh lo phvvdjjlr/ srl vlhvfh gdoo*dssolfd}lrqh+v|v1h{lw+4,,1
Frqwlqxldpr frq od urxwlqhhuuru1 Hffr od yhuvlrqh frpsohwd1
def error(message):print >> sys.stderr,
str(message)
Txl deeldpr xvdwr odfrvlghwwd uhgluh}lrqh +%AA%,1Txdqgr xvldpr od ixq}lrqh%sulqw%/ vwldpr glfhqgr d s|wkrq
fkh yrjoldpr ylvxdol}}duho*rxwsxw/ r or vwuhdp/ doglvsrvlwlyr vwdqgdug gl rxwsxw/ lqjhqhuh lo whuplqdoh lq xvr1 Shuiduh txhvwr xvldpr +lq prgrwudvsduhqwh, vwgrxw1 Txdqgryrjoldpr lqylduh xq phvvdjjlrgl huuruh/ xvhuhpr or vwuhdpvwghuu1 Dqfkh txhvwr Ê lowhuplqdoh1 Txlqgl uhlqglul}}ldpro*rxwsxw door vwuhdp vwghuu1
Rud odyruldpr vxood urxwlqhpdlq1 Txl lpsrvwhuhpr od qrvwudfrqqhvvlrqh h lo fxuvruh shu loqrvwur gdwdedvh/ txlqglfrqwuroohuhpr l qrvwul dujrphqwl
sdudphwul gl vlvwhpd h/ vh wxwwrÊ fruuhwwr/ fkldphuhpr odqrvwud ixq}lrqh fkh hvhjxlu lofrpslwr dvvhjqdwroh1 Hffr lofrglfh=
def usage(): message = (
'==============================================\n''mCat - Finds all *.mp3 files in a given folder (and sub-folders),\n''\tread the id3 tags, and write that information to a SQLite database.\n\n'
'Usage:\n''\t{0} <foldername>\n''\t WHERE <foldername> is the path to your MP3 files.\n\n''Author: Greg Walters\n''For Full Circle Magazine\n''==============================================\n').format(sys.argv[0])
error(message)sys.exit(1)
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 5/42
gvmm djsdmf nbhb{jof $46 45Õ lqglfh a
SURJUDPPDUH LQ S\WKRQ 0 SDUWH <
Frph deeldpr idwwr od yrowdsuhfhghqwh/ fuhldpr gxh
yduldelol joredol fkldpdwhfrqqhfwlrq h fxuvru shu lo qrvwurgdwdedvh1 Txlqgl frqwurooldpr lsdudphwul +vh fh qh vrqr,sdvvdwl gdood uljd gl frpdqgr qhowhuplqdoh1 Shu txhvwr ulfruuldprdo frpdqgr v|v1dujy1 Vwldprfhufdqgr gxh sdudphwul/ sulpd lo
qrph ghoo*dssolfd}lrqh/ fkh Êdxwrpdwlfr/ h txlqgl lo shufruvrghl qrvwul iloh PS61 Vh l gxh
sdudphwul pdqfdqr/ vdowhuhprdood urxwlqh xvdjh/ fkh vwdpsd lophvvdjjlr d vfkhupr h srl hvfh1Lq txhvwr fdvr ulfdgldpr qhoodfodxvrod hovh ghood qrvwudlvwul}lrqh LI1 Vxffhvvlydphqwh/lqvhuldpr lo sdudphwur ghoshufruvr lql}ldoh qhood yduldeloh
VwduwIroghu1 Dwwhq}lrqh fkh vhqho shufruvr Ê suhvhqwh xqrvsd}lr/ shu hvhpslr/+2pqw2pxvlfpdlq2DgxowFrqwhpsrudu|, l fdudwwhul grsrgl hvvr vdudqqr ylvwl frph xqdowur sdudphwur1 FrvÎ txdqgrxvdwh xq shufruvr frq xqrvsd}lr dvvlfxudwhyl gl lqfoxghuorwud ylujrohwwh1 Txlqgl lpsrvwldprod frqqhvvlrqh h lo fxuvruh/fuhldpr lo gdwdedvh h srlhvhjxldpr lo odyrur yhur hsursulr qhood urxwlqhZdonWkhSdwk h shu ilqluhfklxgldpr lo qrvwur fxuvruh h odfrqqhvvlrqh do gdwdedvh h
glfldpr doo*xwhqwh fkh deeldprilqlwr1 O*lqwhud ixq}lrqhZdonWkhSdwk sxÔ hvvhuh wurydwdtxl=kwws=22sdvwhelq1frp2FhjvD[mZ1
Sulpd fdqfhooldpr l wuhfrqwdwrul xvdwl shu whqhuh wudffldgho odyrur idwwr1 Txlqgl dsuldprxq iloh fkh frqwhuu lo uhjlvwur
ghjol huurul qho fdvr yh qh vldelvrjqr1 Txlqgl shufruuldprulfruvlydphqwh lo shufruvrlqglfdwr gdoo*xwhqwh1 Lq sudwlfd/lql}ldpr gdo shufruvr iruqlwr hghqwuldpr h xvfldpr gdoohvrwwrfduwhooh suhvhqwl/ doodulfhufd ghl iloh frq hvwhqvlrqh
%1ps6%1 Txlqgl lqfuhphqwldpr lofrqwdwruh ghood fduwhood h srltxhoor ghl iloh shu whqhuh wudffldgho qxphur ghl iloh surfhvvdwl1Txlqgl sdvvhuhpr lq udvvhjqdfldvfxq iloh1 Fdqfhooldpr odyduldeloh orfdoh fkh frqwlhqh ohlqirupd}lrql gl fldvfxqdfdq}rqh1 Xvldpr od ixq}lrqh mrlqgd rv1sdwk shu fuhduh xqshufruvr h xq qrph gl ilohdssursuldwl frvÎ gd srwhu gluh dpxwdjhq gryh wuryduh lo iloh1 Srlsdvvldpr lo vxr qrph dood fodvvhPS6 ulfhyhqgrqh xqd lvwdq}d gl%dxglr%1 Txlqgl uhfxshuldpr wxwwll wdj LG6 fkh lo iloh frqwlhqh h
vfruuldpr od olvwd dood ulfhufd ghlwdj fkh fl lqwhuhvvdqr h oldvvhjqdpr dooh qrvwuh yduldelolwhpsrudqhh1 Lq txhvwr prgr vlulgxfrqr do plqlpr jol huurul1Gdwh xq*rffkldwd do frglfh fkh vlrffxsd gho qxphur ghood wudffld1Txdqgr pxwdjhq or uhvwlwxlvfhsxÔ hvvhuh xq ydoruh vlqjror/ xqydoruh frph %724;% r frph
bwun^3` h bwun^4` r sxÔ hvvhuhyxrwr1 Xvldpr lo frvwuxwwrwu|2h{fhsw shu fdwwxuduh jolhyhqwxdol huurul1 Rud frqwuroodwh lofrglfh fkh vdoyd l gdwl qhogdwdedvh1 Vwldpr surfhghqgrglyhuvdphqwh ulvshwwr doo*xowlpdyrowd1 Fuhldpr o*lvwux}lrqh VTO
def main():global connectionglobal cursor#----------------------------------------------if len(sys.argv) != 2:
usage()else:
StartFolder = sys.argv[1]
if not exists(StartFolder): # From os.pathprint('Path {0} does not seem to
exist...Exiting.').format(StartFolder)sys.exit(1)
else:print('About to work {0}
folder(s):').format(StartFolder)# Create the connection and cursor.connection=apsw.Connection("mCat.db3")cursor=connection.cursor()# Make the database if it doesn't exist...
MakeDataBase()
# Do the actual work... WalkThePath(StartFolder)# Close the cursor and connection...cursor.close()connection.close()# Let us know we are finished...print("FINISHED!")
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 6/42
gvmm djsdmf nbhb{jof $46 46Õ lqglfh a
Juhj Zdowhuv Ê lo sursulhwdulrghood Udlq|Gd| Vroxwlrqv/ OOF/xqd vrflhw gl frqvxohq}d lqDxurud/ Frorudgr h surjudppdgdo 4<:51 Dpd fxflqduh/ iduhhvfxuvlrql/ dvfrowduh pxvlfd hsdvvduh lo whpsr frq od vxdidpljold1
SURJUDPPDUH LQ S\WKRQ 0 SDUWH <
frph sulpd/ pd txhvwd yrowdvrvwlwxldpr lo ydoruh ghoohyduldelol frq %B%1 Txlqgllqvhuldpr l ydorul qhoo*lvwux}lrqhfxuvru1h{hfxwh1 Vhfrqgr lo vlwrDVSZ txhvwr Ê lo vlvwhpdpljolruh shu lo qrvwur fdvr/txlqgl or suhqgr shu rur frodwr1Shu ilqluh fl rffxsldpr ghoodjhvwlrqh gl dowul hyhqwxdol huurulfxl vl srwuheeh lqfruuhuh1 Shu odpdjjlru sduwh vl wudwwd gl
W|shHuuruv r YdoxhHuuruvjhqhudwl hyhqwxdophqwh gdfdudwwhul Xqlfrgh lqjhvwlelol1Gdwh xq*rffkldwd dood vwudqdpdqlhud frq fxl irupdwwldpr hprvwuldpr oh vwulqjkh1 Qrqxvldpr lo fdudwwhuh glvrvwlwx}lrqh *(*1 Xvldpr odvrvwlwx}lrqh frq %~3€% fkh idsduwh ghooh vshflilfkh gl S|wkrq61{1 Od irupd edvh Ê=
Print('String that will beprinted with {0} number ofstatements”).format(replacement values)
Shu hiloh1zulwholqhv xvldprsxuh od vlqwdvvl fodvvlfd1
Shu ilqluh gryuhpr frqwurooduhod urxwlqh V5KPV1 Od ixq}lrqhsuhqgh od gxudwd ghood fdq}rqhuhfxshudwd gd pxwdjhq hg
hvsuhvvd wudplwh xq iordw h odfrqyhuwh lq xqd vwulqjd qhoirupdwr %Ruh=Plqxwl=Vhfrqgl%rssxuh %Plqxwl=Vhfrqgl%1Jxdugdwh oh lvwux}lrql uhwxuq1Dqfrud xqd yrowd/ vwldpr xvdqgrod vlqwdvvl S|wkrq 61{1Frpxqtxh/ f*Ê txdofrvd glqxryr lq shqwrod1 Vwldpr xvdqgrwuh vhulh gl vrvwlwx}lrql +3/ 4 h5,/ pd frvd vrqr l %=35q% grsr lqxphul 4 h 5B Glfh fkhyrjoldpr/ vh qhfhvvdul/ ghjol}hur lql}ldol1 FrvÎ vh xqd fdq}rqhgxud 5 plqxwl h 7 vhfrqgl/ odvwulqjd uhvwlwxlwd vdu %5=37%/qrq %5=7%1
O*lqwhur frglfh gho qrvwursurjudppd or wurydwh txl=kwws=22sdvwhelq1frp2uIi7Jp:H1
Vfdqgdjoldwh od uhwh h yhghwhfrvd srwhwh wuryduh vx Pxwdjhq1Lo vxr xvr yd rowuh jol PS61
OD PLD VWRULD YHORFHPHQWH
Lo plr vwxglr Ê frpsohwdphqwh gljlwdoh frq txdwwur pdffklqh frq Zlqgrzv[S lq xqd uhwh shhu wr shhu1 Od txlqwd pdffklqd hvhjxh Olqx{ Xexqwx <137hvfoxvlydphqwh frph vlvwhpd gl whvw shu Olqx{1 Kr lql}ldwr frq Xexqwx :137hg kr djjlruqdwr dg rjql qxryd xvflwd1 O*kr wurydwr prowr vwdeloh/ idfloh gdxvduh h frqiljxuduh gdwr fkh rjql yhuvlrqh pljolrud lo VR1
Lq txhvwr prphqwr Ê vror lo plr edqfr gl suryd pd Ê froohjdwr dood pld uhwhh frqglylgh gdwl frq oh pdffklqh frq Zlqgrzv1 Vrqr prowr vrgglvidwwr ghoodvwdelolw gl Xexqwx shu jol djjlruqdphqwl/ l surjudppl/ lo vxssruwr kdugzduhh o*djjlruqdphqwr ghl gulyhu1 Dqfkh vh Ê xq shffdwr fkh l surgxwwrul slÛlpsruwdqwl frph Dgreh qrq suhyhgdqr xqd yhuvlrqh ghglfdwd/ Zlqh vhpeudixq}lrqduh ehqh1 Fl vrqr surjudppl judilfl h vwdpsdqwl surihvvlrqdoldwwlqhqwl dood pld dwwuh}}dwxud irwrjudilfd fkh qrq ixq}lrqdqr frvÎ ghyrdvshwwduh fkh Zlqh pljolrul r fkh lo vriwzduh yhqjd sruwdwr1
Dxglr/ ylghr/ FG2GYG/ XVE h xqlw ]ls wxwwh vhpeudqr ixq}lrqduh dsshqdfroohjdwh/ lo fkh Ê idqwdvwlfr1 Dofxql glihwwl qho vriwzduh fl vrqr pd vhpeudqr
gl plqruh lpsruwdq}d1
Wxwwr vrppdwr Xexqwx Ê ylvlydphqwh iuhvfr h glyhuwhqwh gd xvduh1 Qrqvrqr xq vhffklrqh frvÎ qrq xvr od uljd gl frpdqgr d phqr fkh qrq yhqjdlqfxulrvlwr gd xq wxwruldo h qrq ghflgd gl suryduor> od JXL gho VR Êdeedvwdq}d frpsohwd shu qrl qrq0vhffklrql fkh yrjoldpr xvduh vroro*lqwhuidffld judilfd1
Vfdulfr Ixoo Flufoh Pdjd}lqh wxwwl l phvl h or frqglylgr frq xqr ghl plhlfroohjkl shu prvwudujol frvd Ê glvsrqleloh1 Prowh shuvrqh dqfrud qrqfrqrvfrqr txhvwr VR h frph Ê idfloh gd xvduh/ pd or vfrqwhqwr fkh suryrfd
Plfurvriw or idu fuhvfhuh gl slÛ1 O*xqlfd frvd fkh dvvroxwdphqwh dpr gltxhvwr VR Ê od fdsdflw gl fklxghuh xq surjudppd gdo frpsruwdphqwrdqrpdor1 Lo sxovdqwh shu o*lqwhuux}lrqh ixq}lrqd surqwdphqwh hg holplqd odiuxvwud}lrqh gl dvshwwduh fkh Zlqgrzv [S vl veorffkl1 ShufkË Zlqgrzv qrqsxÔ iduh xqd frvd dowuhwwdqwr vhpsolfhB Ududphqwh shuÔ kr elvrjqr gl xvduhlo sxovdqwh/ d glprvwud}lrqh gl txdqwr vld vwdeloh Olqx{1
Euldq J Kduwqhoo 0 Irwrjudir
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 7/42gvmm#djsdmf#nbhb{jof#$47 lqglfh#a
KRZ0WR Surjudppduh#lq#S|wkrq#0#Sduwh#43
IFP#qq1#5:068#0#S|wkrq#Sduwl#40<
Vyloxssr
Suredelophqwh#dyhwh#jlÂ#vhqwlwr#lo#whuplqh#[PO1#Srwuhvwh/#shuÔ/#qrq#vdshuh#frvd#vljqlilfd1#
[PO#vduÂ#o*rjjhwwr#ghood#oh}lrqh#gl#txhvwr#phvh1#Jol#relhwwlyl#vrqr=
™#Idploldul}}duh#frq#lo#frqfhwwr#gl#[PO™#Ohjjhuh#h#vfulyhuh#iloh#[PO#wudplwh#l#yrvwul#surjudppl™#Suhsduduyl#shu#xq#vxffhvvlyr#slÛ#lpsruwdqwh#surjhwwr#[PO
FrvÎ111#sduoldpr#gl#[PO1#[PO#vwd#shu#H[whqvleoh#Pdunxs#
Odqjxdjh#+olqjxdjjlr#pdufdwruh#hvwhqvleloh,/#dqdorjdphqwh#doo*KWPO1#Ix#surjhwwdwr#shu#frqvhuyduh#h#
wudvihuluh#gdwl#hiilfdfhphqwh#dwwudyhuvr#Lqwhuqhw#r#dowuh#ylh#gl#frpxqlfd}lrqh1#[PO#Ê#hvvhq}ldophqwh#xq#iloh#gl#whvwr#irupdwwdwr#xvdqgr#sursul#wdj#h#gryuheeh#hvvhuh#deedvwdq}d#dxwr0grfxphqwdqwh1#Hvvhqgr#xq#iloh#gl#whvwr/#sxÔ#hvvhuh#frpsuhvvr#shu#xq#wudvihulphqwr#slÛ#udslgr#h#idfloh1#Ulvshwwr#
doo*KWPO/#[PO#qrq#id#qxood#gd#vÊ1#Qrq#vl#fxud#gl#frph#l#yrvwul#gdwl#ghyrqr#dssduluh1#Frph#ghwwr#srfr#id/#[PO#qrq#reeoljd#dg#dwwhqhuvl#d#wdj#vwdqgdug1#Srwhwh#fuhduqh#gl#yrvwul1
Gldpr#xq*rffkldwd#d#xq#jhqhulfr#iloh#[PO=
<root><node1>Data Here</node1><node2
attribute="something">Node 2data</node2>
<node3><node3sub1>more
data</node3sub1></node3>
</root>
Od#sulpd#frvd#gd#qrwduh#Ê#o*lqghqwd}lrqh1#Lq#uhdowÂ/#o*lqghqwd}lrqh#vl#xvd#vror#shu#frprglwÂ1#Lo#iloh#[PO#
ixq}lrqhuheeh#dqfkh#vh#vfulwwr#frvÎ111
<root><node1>DataHere</node1><node2attribute="something">Node 2data</node2><node3><node3sub1>moredata</node3sub1></node3></root>
Frqwlqxdqgr/#l#wdj#frqwhqxwl#qhooh#sduhqwhvl#%?A%#ghyrqr#ulvshwwduh#dofxqh#uhjroh1#Sulpr/#ghyrqr#hvvhuh#xqd#sdurod#xqlfd1#Vhfrqgr/#txdqgr#dyhwh#xq#wdj#lql}ldoh#+shu#hvhpslr#?urrwA,#gryhwh#dyhuh#xq#fruulvsrqghqwh#wdj#gl#fklxvxud1#Txhvwr#wdj#lql}ld#frq#%2%1#L#wdj#vrqr#vhqvlelol#dooh#pdlxvfroh=#
?qrghA/#?QrghA/#?QRGHA#h#?QrgHA#vrqr#wxwwl#wdj#glyhuvl/#h#txhool#gl#fklxvxud#ghyrqr#fruulvsrqghuh1#L#qrpl#ghl#wdj#srvvrqr#frqwhqhuh#ohwwhuh/#qxphul#h#dowul#fdudwwhul/#pd#qrq#srvvrqr#lql}lduh#frq#xq#qxphur#r#fdudwwhul#gl#sxqwhjjldwxud1#Gryuhvwh#hylwduh#%0%/#%1%#h#%=%#
shufkË#dofxql#vriwzduh#ol#srwuheehur#frqvlghuduh#frpdqgl#r#sursulhwÂ#gl#xq#rjjhwwr1#Lqrowuh/#l#gxh#sxqwl#
vrqr#ulvhuydwl#shu#dowur1#Fl#vl#ulihulvfh#dl#wdj#frph#hohphqwl1#
Rjql#iloh#[PO#Ê#hvvhq}ldophqwh#xq#doehur#0#lql}ld#gd#xqd#udglfh#h#gd#oÎ#vl#vxgglylgh1#Rjql#iloh#[PO#GHYH#dyhuh#xqd#udglfh/#fkh#Ê#lo#jhqlwruh#gl#rjql#dowud#frvd#qho#iloh1#Wruqdwh#do#qrvwur#hvhpslr1#
Grsr#od#udglfh/#fl#vrqr#wuh#hohphqwl#iljol=#qrgh4/#qrgh5#h#qrgh61#Phqwuh#wxwwl#vrqr#iljol#ghoo*hohphqwr#urrw/#qrgh6#Ê#jhqlwruh#gl#qrgh6vxe41
Rud#rvvhuydwh#qrgh51#Qrwdwh#frph#doo*lqwhuqr#ghooh#sduhqwhvl#yl#vld#rowuh#do#vrolwr#gdwr#dqfkh#txdofrvd#fkldpdwr#dwwulexwh1#
Rjjljlruqr/#prowl#vyloxssdwrul#hylwdqr#jol#dwwulexwl#srlfkË#jol#hohphqwl#vrqr#dowuhwwdqwr#hiilfdfl#h#gdqqr#phqr#sureohpl/#pd#vfrsuluhwh#fkh#jol#dwwulexwl#yhqjrqr#dqfrud#xwlol}}dwl1#Ol#dssurirqgluhpr#d#euhyh1
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 8/42gvmm#djsdmf#nbhb{jof#$47 lqglfh#a
Gldpr#xq*rffkldwd#doo*xwloh#hvhpslr#lq#edvvr1
Txl#deeldpr#o*hohphqwr#udglfh#fkldpdwr#%shrsoh%#fkh#frqwlhqh#gxh#hohphqwl#iljol#fkldpdwl#%shuvrq%1#Fldvfxq#*shuvrq*#kd#9#hohphqwl#iljol=#iluvwqdph/#odvwqdph/#jhqghu/#dgguhvv/#flw|#h#vwdwh1#D#sulpd#ylvwd#srwuhvwh#shqvduh#d#txhvwr#iloh#[PO#frph#d#xq#gdwdedvh#+ulfrugdqgr#oh#xowlph#oh}lrql,/#h#dyuhvwh#udjlrqh1#Lqidwwl/#dofxqh#dssolfd}lrql#xvdqr#l#iloh#[PO#frph#vhpsolfl#vwuxwwxuh#gdwdedvh1#Rud/#vfulyhuh#xq#
surjudppd#shu#ohjjhuh#xq#iloh#[PO#srwuheeh#hvvhuh#idwwr#vhq}d#wdqwl#sureohpl1#
Vhpsolfhphqwh/#dsuluh#lo#iloh/#ohjjhuh#fldvfxqd#uljd#h/#edvdqgrvl#vxoo*hohphqwr/#wudwwduh#lo#gdwr#h#txlqgl#fklxghuh#lo#iloh#txdqgr#vl#Ê#ilqlwr1#ShuÔ#fl#vrqr#vlvwhpl#pljolrul1
Qhjol#hvhpsl#fkh#vhjxrqr/#xvhuhpr#lo#prgxor#gl#oleuhuld#fkldpdwr#HohphqwWuhh1#Srwhwh#uhfxshuduor#gluhwwdphqwh#frq#V|qdswlf#lqvwdoodqgr#s|wkrq0hohphqwwuhh1#Wxwwdyld#lr#kr#vfhowr#gl#ylvlwduh#lo#vlwr#gl#HohphqwWuhh#+kwws=22hiierw1ruj2grzqordgv2&hohphqwwuhh,#h#vfdulfduh#
gluhwwdphqwh#lo#iloh#vrujhqwh#+hohphqwwuhh0415190533836491wdu1j},1#Xqd#yrowd#
vfdulfdwr#kr#xvdwr#lo#jhvwruh#gl#sdffkhwwl#shu#hvwuduqh#lo#frqwhqxwr#lq#xqd#fduwhood#whpsrudqhd1#Vrqr#hqwudwr#qhood#fduwhood#h#kr#hvhjxlwr#%vxgr#s|wkrq#vhwxs1s|#lqvwdoo%1#Txhvwr#kd#srvl}lrqdwr#l#iloh#qhood#fduwhood#frpprq#gl#s|wkrq#frvÎ#srvvr#xvduor#vld#lq#s|wkrq#518#fkh#5191#Rud#srvvldpr#lql}lduh#d#odyruduh1#Fuhdwh#xqd#fduwhood#shu#lo#frglfh#gl#txhvwr#phvh/#frsldwh#lo#frglfh#[PO#gl#vrsud#qho#yrvwur#hglwru#gl#whvwr#suhihulwr#h#vdoydwhor#qhood#qxryd#fduwhood#frph#
%{povdpsoh41{po%1Rud#lo#qrvwur#
frglfh1#Od#sulpd#frvd#fkh#yrjoldpr#iduh#Ê#whvwduh#od#qrvwud#lqvwdood}lrqh#gl#HohphqwWuhh1#hffr#lo#frglfh=
importelementtree.ElementTree as ET
tree =ET.parse('xmlsample1.xml')
ET.dump(tree)
Txdqgr#hvhjxldpr#lo#surjudppd#gl#whvw/#gryuhppr#dyhuh#txdofrvd#gl#vlploh#d#txhoor#prvwudwr#lq#edvvr#d#ghvwud1
Wxwwr#txhoor#fkh#deeldpr#idwwr#Ê#vwdwr#shuphwwhuh#d#HohphqwWuhh#gl#dsuluh#lo#iloh/#dqdol}}duor#qhooh#vxh#sduwl#edvh#hg#hvwuduor#frvÎ#frph#Ê#lq#phpruld1#Srfd#idqwdvld#lq#txhvwr#fdvr1
Rud#vrvwlwxlwh#lo#yrvwur#frglfh#
<people><person>
<firstname>Samantha</firstname><lastname>Pharoh</lastname><gender>Female</gender><address>123 Main St.</address><city>Denver</city><state>Colorado</state>
</person><person><firstname>Steve</firstname><lastname>Levon</lastname><gender>Male</gender><address>332120 Arapahoe Blvd.</address><city>Denver</city><state>Colorado</state>
</person></people>
/usr/bin/python -u"/home/greg/Documents/articles/xml/reader1.py"
<people><person>
<firstname>Samantha</firstname><lastname>Pharoh</lastname><gender>Female</gender><address>123 Main St.</address><city>Denver</city><state>Colorado</state>
</person><person>
<firstname>Steve</firstname><lastname>Levon</lastname><gender>Male</gender><address>332120 Arapahoe
Blvd.</address><city>Denver</city><state>Colorado</state>
</person></people>
SURJUDPPDUH#LQ#S\WKRQ#0#SDUWH#43
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 9/42gvmm#djsdmf#nbhb{jof#$47 lqglfh#a
frq#lo#vhjxhqwh=
importelementtree.ElementTree as ET
tree =ET.parse('xmlsample1.xml')
person =
tree.findall('.//person')
for p in person:for dat in p:
print "Element: %s -Data: %s" %(dat.tag,dat.text)
hg#hvhjxlwhor#gl#qxryr1#Rud#lo#yrvwur#rxwsxw#gryuheeh#hvvhuh=
/usr/bin/python -u
"/home/greg/Documents/articles/xml/reader1.py"
Element: firstname - Data:SamanthaElement: lastname - Data:PharohElement: gender - Data: FemaleElement: address - Data: 123
Main St.Element: city - Data: DenverElement: state - Data:ColoradoElement: firstname - Data:SteveElement: lastname - Data:LevonElement: gender - Data: MaleElement: address - Data:332120 Arapahoe Blvd.Element: city - Data: DenverElement: state - Data:Colorado
Txlqgl#fldvfxq#gdwr#Ê#dffrpsdjqdwr#gdo#qrph#gho#wdj1#Shu#fdsluh#frq#frvd#deeldpr#d#fkh#iduh#srwuhppr#iduh#xqd#vhpsolfh#vwdpsd1#Dqdol}}ldpr#fkh#frvd#deeldpr#uhdol}}dwr1#Deeldpr#idwwr#dqdol}}duh#lo#iloh#d#HohphqwWuhh#fkh#kd#phvvr#lo#ulvxowdwr#qhoo*rjjhwwr#wuhh1##Txlqgl#deeldpr#fklhvwr#d#HohphqwWuhh#gl#wuryduh#wxwwh#oh#rffruuhq}h#gl#shuvrq1#Qhoo*hvhpslr#idwwr#fh#qh#vrqr#gxh#pd#srwuheehur#hvvhuh#4#r#43331#Shuvrq#Ê#iljolr#gl#shrsoh#h#qrl#vdssldpr#fkh#
txhvw*xowlpr#Ê#vhpsolfhphqwh#od#udglfh1#Wxwwl#l#qrvwul#gdwl#vrqr#ulsduwlwl#lq#shuvrq1#Txlqgl#deeldpr#fuhdwr#xq#vhpsolfh#
flfor#iru#shu#dqdol}}duh#fldvfxq#rjjhwwr#shuvrq1#Deeldpr#srl#fuhdwr#xq#dowur#flfor#iru#shu#hvwuduuh#l#gdwl#lq#fldvfxq#shuvrq#h#ylvxdol}}duol#prvwudqgr#lo#qrph#ghoo*hohphqwr#+1wdj,#h#lo#gdwr#+1wh{w,1
Rud#xq#hvhpslr#slÛ#uhdoh1#Od#pld#idpljold#hg#lr#fl#glyhuwldpr#lq#xq*dwwlylwÂ#fkldpdwd#Jhrfdfklqj1#Vh#qrq#vdshwh#frvd#vld#vdssldwh#fkh#vl#wudwwd#gl#xqd#fdffld#do#whvrur#shu#%vhffklrql%#lq#fxl#vl#xvd#xq#glvsrvlwlyr#JSV#sruwdwloh#shu#wuryduh#flÔ#fkh#xq#dowur#kd#qdvfrvwr1#Vl#sxeeolfdqr#oh#frruglqdwh#JSV#juh}}h#lq#xq#vlwr#zhe/#txdofkh#yrowd#frq#lqgl}l/#vl#lqvhulvfrqr#oh#frruglqdwh#qho#qrvwur#JSV#h#
txlqgl#lql}ld#od#fdffld1#Vhfrqgr#Zlnlshgld#fl#vrqr#rowuh#413331333#gl#vlwl#dwwlyl#lq#wxwwr#lo#prqgr/#txlqgl#suredelophqwh#fh#qh#vrqr#dofxql#qhood#yrvwud#}rqd1#Lr#qh#xvr#gxh#shu#rwwhqhuh#orfdolwÂ#lq#fxl#fhufduh1#Xqr#Ê#kwws=22zzz1jhrfdfklqj1frp2 #h#o*dowur#Ê#kwws=22qdylfdfkh1frp21#Fh#qh#vrqr#dowul/#pd#txhvwl#gxh#vrqr#txhool#slÛ#lpsruwdqwl1
Lq#jhqhuh#l#vlwl#gl#jhrfdfklqj#xvdqr#iloh#[PO#shu#oh#orur#lqirupd}lrql1#Fl#vrqr#dssolfd}lrql#fkh#uhfxshudqr#txhvwl#gdwl#h#ol#wudvihulvfrqr#do#glvsrvlwlyr#JSV1#Dofxqh#ixq}lrqdqr#gd#gdwdedvh/#shuphwwhqgryl#gl#whqhuh#wudffld#ghood#yrvwud#dwwlylwÂ/#wdoyrowd#frq#
<?xml version="1.0" encoding="ISO-8859-1"?><loc version="1.0" src="NaviCache">
<waypoint><name id="N02CAC"><![CDATA[Take Goofy Pictures at Grapevine Lake by g_phillips
Open Cache: UnrestrictedCache Type: Normal
Cache Size: NormalDifficulty: 1.5Terrain : 2.0]]></name>
<coord lat="32.9890166666667" lon="-97.0728833333333" /><type>Geocache</type><link text="Cache Details">http://www.navicache.com/cgi-
bin/db/displaycache2.pl?CacheID=11436</link></waypoint>
</loc>Qdylfdfkh#iloh
SURJUDPPDUH#LQ#S\WKRQ#0#SDUWH#43
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 10/42gvmm#djsdmf#nbhb{jof#$47 lqglfh#a
pdssh1#Shu#lo#prphqwr#fl#frqfhqwuhuhpr#qhoo*dqdolvl#ghl#iloh#vfdulfdwl1
Vrqr#dqgdwr#vx#Qdylfdfkh#h#kr#wurydwr#xq#qdvfrqgljolr#ghfhqwh#lq#Wh{dv1#Lo#frqwhqxwr#gho#iloh#Ê#prvwudwr#qhood#sdjlqd#suhfhghqwh1
Frsldwh#l#gdwl#gdo#er{#h#vdoydwhol#frph#%Fdfkh1orf%1#Sulpd#gl#lql}lduh#d#surjudppduh/#hvdplqldpr#lo#iloh#fdfkh1
Od#sulpd#uljd#hvvhq}ldophqwh#fl#lqirupd#fkh#vl#wudwwd#gl#xq#iloh#[PO#frqydolgdwr/#txlqgl#srvvldpr#wudqtxloodphqwh#ljqruduod1#Od#uljd#vxffhvvlyd#+txhood#fkh#lql}ld#frq#%orf%,#Ê#od#qrvwud#udglfh#h#frqwlhqh#jol#dwwulexwl#%yhuvlrq%#h#%vuf%1#Ulfrugdwh/#kr#jlÂ#ghwwr#fkh#dofxql#iloh#xwlol}}dqr#jol#dwwulexwl1#Qh#dyuhpr#d#fkh#iduh#frq#dowul#
survhjxhqgr#qho#iloh1#Gl#qxryr/#od#udglfh#lq#txhvwr#fdvr#sxÔ#hvvhuh#ljqrudwd1#Od#uljd#vxffhvvlyd#iruqlvfh#lo#iljolr#zd|srlqw#+xq#zd|srlqw#Ê#lo#oxrjr#gryh/#lq#txhvwr#fdvr/#vl#wuryd#od#fdfkh,1#Rud#uhfxshuldpr#l#gdwl#fkh#fl#lqwhuhvvdqr#gdyyhur1#F*Ê#lo#qrph#ghood#fdfkh/#oh#
frruglqdwh#lq#odwlwxglqh#h#orqjlwxglqh/#lo#wlsr#gl#fdfkh#h#xq#froohjdphqwr#dood#sdjlqd#zhe#frq#xowhulrul#lqirupd}lrql1#O*hohphqwr#qdph#Ê#xqd#vwulqjd#oxqjd#frqwhqhqwh#glyhuvh#lqirupd}lrql#xwlol#pd#fkh#greeldpr#dqdol}}duh#qrl#vwhvvl1#Rud#fuhldpr#xqd#qxryd#dssolfd}lrqh#shu#ohjjhuh#h#prvwuduh#lo#iloh1#Fkldpldprod#%uhdgdfdfkh1s|%1#Lql}ldpr#gdoo*lpsruw#h#gdo#sduvh#ghoo*hvhpslr#suhfhghqwh1
importelementtree.ElementTree as ET
tree = ET.parse('Cache.loc')
Dghvvr#yrjoldpr#uhfxshuduh#vror#l#gdwl#doo*lqwhuqr#gho#wdj#zd|srlqw1#Shu#iduor#xvldpr#od#ixq}lrqh#1ilqg#gl#HohphqwWuhh1#Phwwldpr#lo#ulvxowdwr#qhoo*rjjhwwr#%z%1
w = tree.find('.//waypoint')
Txlqgl/#greeldpr#dqdol}}duh#wxwwl#l#gdwl1#Shu#iduor#xvhuhpr#xq#flfor#orrs1#Doo*lqwhuqr#gho#flfor/#frqwurooldpr#lo#wdj#shu#fhufduh#jol#hohphqwl#*qdph*/#*frrug*/#*w|sh*#h#*olqn*1#Lq#edvh#do#wdj#fkh#rwwhqldpr/#hvwuduuhpr#o*lqirupd}lrqh#shu#vwdpsduod#lq#
vhjxlwr1
for w1 in w:if w1.tag == "name":
SrlfkË#lo#wdj#*qdph*#vduÂ#lo#sulpr#fkh#frqwuroohuhpr/#ulyhgldpr#l#gdwl#fkh#rwwhuuhpr1
<nameid="N02CAC"><![CDATA[TakeGoofy Pictures at GrapevineLake by g_phillips
Open Cache: Unrestricted
Cache Type: Normal
Cache Size: Normal
Difficulty: 1.5
Terrain : 2.0]]></name>
ª#gdyyhur#xqd#vwulqjd#prowr#oxqjd1#O*lg#ghood#fdfkh#Ê#
lpsrvwdwr#frph#dwwulexwr1#Lo#qrph#Ê#od#sduwh#grsr#%FGDWD%#h#sulpd#gl#%Rshq#Fdfkh=%1#Dqguhpr#d#iudpphqwduh#od#vwulqjd#lq#sduwl#slÛ#slffroh1#Shu#ulfdyduh#xqd#sduwh#ghood#vwulqjd#xvldpr=
newstring =oldstring[startposition:endposition]
FrvÎ#srvvldpr#xvduh#lo#frglfh#vrwwr#shu#uhfxshuduh#o*lqirupd}lrqh#qhfhvvduld1
Txlqgl#greeldpr#uhfxshuduh#o*lg#orfdol}}dwr#qhoo*dwwulexwr#gho#
wdj#qdph1#Frqwurooldpr#vh#fl#vrqr#dwwulexwl#+frvd#fkh#vdssldpr#yhud,/#frvÎ=
if w1.keys():for name,value in
# Get text of cache name up to the phrase "Open Cache: "CacheName = w1.text[:w1.text.find("Open Cache: ")-1]# Get the text between "Open Cache: " and "Cache Type: "OpenCache = w1.text[w1.text.find("Open Cache:")+12:w1.text.find("Cache Type: ")-1]# More of the sameCacheType = w1.text[w1.text.find("Cache Type:")+12:w1.text.find("Cache Size: ")-1]CacheSize = w1.text[w1.text.find("Cache Size:")+12:w1.text.find("Difficulty: ")-1]Difficulty= w1.text[w1.text.find("Difficulty:")+12:w1.text.find("Terrain : ")-1]Terrain = w1.text[w1.text.find("Terrain : ")+12:]
SURJUDPPDUH#LQ#S\WKRQ#0#SDUWH#43
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 11/42gvmm#djsdmf#nbhb{jof#$47 lqglfh#a
SURJUDPPDUH#LQ#S\WKRQ#0#SDUWH#43
w1.items():if name == 'id':
CacheID = value
Rud#srvvldpr#sdvvduh#do#frglfh#shu#oh#frruglqdwh/#lo#wlsr#h#lo#olqn#prvwudwr#lq#edvvr#d#ghvwud1#Lq#frqfoxvlrqh/#shu#
ylvlrqduol#ol#vwdpshuhpr#xvdqgr#lo#frglfh#lq#irqgr#d#ghvwud1#SlÛ#d#ghvwud#f*Ê#lo#frglfh#frpsohwr1
Dyhwh#lpsdudwr#deedvwdq}d#shu#ohjjhuh#od#pdjjlru#sduwh#ghl#iloh#[PO1#Frph#vhpsuh/#srwhwh#uhfxshuduh#o*lqwhur#frglfh#gl#txhvwd#
oh}lrqh#vxo#plr#vlwr#zhe#kwws=22zzz1wkhghvljqdwhgjhhn1frp1
Od#survvlpd#yrowd#xvhuhpr#oh#qrvwuh#frqrvfhq}h#[PO#shu#udffrjolhuh#lqirupd}lrql#gd#xq#phudyljolrvr#vlwr#
phwhr#h#prvwuduoh#qho#whuplqdoh1#Exrq#glyhuwlphqwr$
elif w1.tag == "coord":if w1.keys():
for name,value in w1.items():if name == "lat":
Lat = value
elif name == "lon":Lon = valueelif w1.tag == "type":
GType = w1.textelif w1.tag == "link":
if w1.keys():for name, value in w1.items():
Info = valueLink = w1.text
print "Cache Name: ",CacheName
print "Cache ID: ",CacheIDprint "Open Cache: ",OpenCacheprint "Cache Type: ",CacheTypeprint "Cache Size: ",CacheSizeprint "Difficulty: ", Difficultyprint "Terrain: ",Terrainprint "Lat: ",Latprint "Lon: ",Lonprint "GType: ",GTypeprint "Link: ",Link
#Ê#lo#sursulhwdulr#ghood# /#xqd#vrflhwÂ#gl#frqvxohq}d#lq#Dxurud/#Frorudgr#h#surjudppd#gdo#4<:51#Dpd#fxflqduh/#iduh#hvfxuvlrql/#dvfrowduh#pxvlfd#h#sdvvduh#lo#whpsr#frq#od#vxd#idpljold1
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 12/42gvmm#djsdmf#nbhb{jof#$48 lqglfh#a
KRZ0WR Surjudppduh#lq#S|wkrq#0#Sduwh#44
IFP#qq1#5:069#0#S|wkrq#sduwl#4043
Vyloxssr
O*xowlpd#yrowd#yl#kr#surphvvr#fkh#dyuhppr#xvdwr#oh#qrvwuh#frqrvfhq}h#[PO#shu#
uhfxshuduh#lqirupd}lrql#phwhr#gd#xq#vlwr#zhe#h#prvwuduoh#lq#xq#
whuplqdoh1#Ehqh/#txho#prphqwr#Ê#duulydwr1
Xvhuhpr#xqd#DSL#gd#zzz1zxqghujurxqg1frp1#Kr#vhqwlwr#od#grpdqgd#%Frv*Ê#xqd#DSL%#iduvl#vwudgd#qhooh#yrvwuh#jroh1#DSL#vwd#shu#Lqwhuidffld#gl#Surjudppd}lrqh#gl#
xq*Dssolfd}lrqh1#Vl#wudwwd#gl#xqd#hvsuhvvlrqh#vlpsdwlfd#shu#ghvfulyhuh#lo#prgr#gl#lqwhuidfflduvl#frq#xq*dowur#
surjudppd1#Shqvdwh#dooh#oleuhulh#fkh#lpsruwldpr1#Dofxqh#gl#hvvh#srvvrqr#hvvhuh#hvhjxlwh#frph#dssolfd}lrql#d#vË#vwdqwl/#pd#vh#oh#lpsruwldpr#frph#oleuhulh#srvvldpr#xvduh#prowh#ghooh#orur#ixq}lrql#qho#qrvwur#surjudppd/#ulxvfhqgr#frvÎ#dg#xvduh#lo#frglfh#gl#txdofxq#dowur1#Lq#txhvwr#fdvr/#xvhuhpr#lqglul}}l#XUO#
hvsuhvvdphqwh#irupdwwdwl#shu#lqwhuurjduh#lo#vlwr#zxqghujurxqg#shu#lqirupd}lrql#phwhr#0#vhq}d#xvduh#xq#eurzvhu#zhe1#Dofxql#srwuheehur#diihupduh#fkh#xqd#DSL#Ê#xqd#vshflh#gl#sruwd#vhjuhwd#shu#xq#dowur#surjudppd#0#lqvhulwd#lqwhq}lrqdophqwh#gdo#surjudppdwruh#shu#idufhod#xvduh1#Dg#rjql#prgr/#Ê#xqd#hvwhqvlrqh#
vxssruwdwd#gd#xq*dssolfd}lrqh#shu#shuphwwhuqh#o*xvr#lq#dowuh#dssolfd}lrql1
Vxrqd#lqwuljdqwhB#Ehqh/#frqwlqxdwh#d#ohjjhuh/#plhl#jlrydql#sdgdzdq1
Dyyldwh#lo#yrvwur#eurzvhu#suhihulwr#h#dsulwh#lo#vlwr#zzz1zxqghujurxqg1frp1#Rud#lqvhulwh#lo#yrvwur#frglfh#srvwdoh#r#
od#flwwÂ#h#or#vwdwr#+r#sdhvh,#qho#fdpsr#gl#ulfhufd1#Fl#vrqr#prowh#lqirupd}lrql#txl1#Rud/#vdowldpr#dood#sdjlqd#ghoo*DSL=#kwws=22zlnl1zxqghujurxqg1frp2lqgh{1sks2DSLb0b[PO
Xqd#ghooh#sulph#frvh#fkh#qrwhuhwh#vrqr#oh#Frqgl}lrql#gl#Xwlol}}r#ghoo*DSL1#Vlhwh#suhjdwl#gl#
ohjjhuoh#h#dwwhqhuyl#dg#hvvh1#Qrq#vrqr#rqhurvh#h#vrqr#prowr#vhpsolfl#gd#ulvshwwduh1#Oh#frvh#fkh#fl#lqwhuhvvdqr#vrqr#oh#fkldpdwh#JhrOrrnxs[PO/#Z[FxuuhqwRe[PO#h#Iruhfdvw[PO1#Suhqghwhyl#xq#sr*#gl#whpsr#shu#hvdplqduoh1
Kr#lqwhq}lrqh#gl#hylwduh#od#
urxwlqh#JhrOrrnxs[PO/#h#odvflduyhod#yhghuh#gd#vrol1#Fl#frqfhqwuhuhpr#vx#gxh#dowul#frpdqgl=#Z[FxuuhqwRe[PO#+Frqgl}lrql#Fruuhqwl,#txhvwd#yrowd#h#Iruhfdvw[PO#+Suhylvlrqh,#od#survvlpd1
Txhvwr#Ê#lo#olqn#shu#Z[FxuuhqwRe[PO=#kwws=22dsl1zxqghujurxqg1frp2dxwr2zxl2jhr2Z[FxuuhqwRe[PO2lqgh{1
{poBtxhu|@;3346
Vrvwlwxlwh#lo#frglfh#srvwdoh#ghjol#XVD#;3346#frq#lo#yrvwur#r/#vh#delwdwh#do#gl#ixrul#ghjol#Vwdwl#Xqlwl/#srwhwh#suryduh#frq#flwwÂ/#sdhvh#0#frph#Sduljl/#Iudqfld/#r#Orqgud/#Lqjklowhuud1
H#lo#olqn#shu#Iruhfdvw[PO=#
kwws=22dsl1zxqghujurxqg1frp2dxwr2zxl2jhr2Iruhfdvw[PO2lqgh{1{poBtxhu|@;3346
Dqfkh#txl#vrvwlwxlwh#;3346#frq#lo#yrvwur#frglfh#srvwdoh#r#flwwÂ/#sdhvh1
Lql}ldpr#frq#oh#lqirupd}lrql#fruuhqwl1#Lqfroodwh#o*lqglul}}r#qho#
yrvwur#eurzvhu#suhihulwr1#Yl#vdudqqr#prvwudwh#xqd#judq#txdqwlwÂ#gl#lqirupd}lrql1#OdvfhuÔ#d#yrl#ghflghuh#frvd#Ê#gdyyhur#lpsruwdqwh/#pd#fl#vriihuphuhpr#vx#dofxql#hohphqwl1
Shu#lo#qrvwur#hvhpslr/#iduhpr#
SURJUDPPDUH LQ S\WKRQ SDUWH 44
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 13/42gvmm#djsdmf#nbhb{jof#$48 lqglfh#a
dwwhq}lrqh#dl#wdj#vhjxhqwl=
Qdwxudophqwh/#srwhwh#djjlxqjhuh#dowul#wdj#fkh#shu#yrl#vrqr#lqwhuhvvdqwl1#Frpxqtxh/#txhvwl#wdj#yl#iruqludqqr#xqd#sdqrudplfd#deedvwdq}d#frpsohwd1
Rud#fkh#vdssldpr#frvd#fl#lqwhuhvvd/#lql}ldpr#d#vfulyhuh#lo#frglfh#ghood#qrvwud#dssolfd}lrqh1#Rvvhuyldpr#lq#jhqhudoh#lo#ioxvvr#frpsohvvlyr#gho#surjudppd1
Sulpd#gl#wxwwr/#frqwurooldpr#frvd#o*xwhqwh#fl#kd#fklhvwr#gl#iduh1#Vh#Ê#vwdwd#iruqlwd#xqd#orfdolwÂ#od#xvhuhpr#dowulphqwl#xwlol}}huhpr#txhood#suhghilqlwd1#Txlqgl#
sdvvhuhpr#dood#ixq}lrqh#jhwFxuuhqwv1#Xvldpr#od#orfdolwÂ#shu#frvwuxluh#od#qrvwud#vwulqjd#gl#ulfklhvwd#gd#lqylduh#do#vlwr#zhe1#Xvhuhpr#xuoole1xuorshq#shu#uhfxshuduh#od#ulvsrvwd#gdo#zhe/#phwwhuod#lq#xq#rjjhwwr#h#sdvvduor#dood#oleuhuld#HohphqwWuhh#shu#lo#sduvlqj1#Txlqgl#fklxghuhpr#od#
frqqhvvlrqh#zhe#h#lql}lhuhpr#d#fhufduh#l#qrvwul#wdj1#Xqd#yrowd#wurydwr#xq#wdj#fkh#fl#lqwhuhvvd/#vdoyhuhpr#txhvwr#whvwr#lq#xqd#yduldeloh#fkh#srvvldpr#xvduh#lq#vhjxlwr#shu#prvwuduh#o*rxwsxw1#Txdqgr#dyuhpr#d#glvsrvl}lrqh#wxwwl#l#gdwl#ol#prvwuhuhpr1#Deedvwdq}d#vhpsolfh#lq#whruld1
Lql}ldpr#fro#fkldpduh#lo#qrvwur#iloh#zbfxuuhqwv1s|1#Hffr#od#sduwh#gl#lpsruw#gho#qrvwur#frglfh=
from xml.etree importElementTree as ET
import urllib
import sys
import getopt
Txlqgl#lqvhuluhpr#xqd#vhulh#gl#olqhh#gl#dlxwr#+lq#dowr#d#ghvwud,#vrsud#jol#lpsruw1
Dvvlfxudwhyl#gl#xvduh#l#wulsol#grssl#dslfl1#Fl#shuphwwhuÂ#gl#
xvduh#frpphqwl#pxowl0uljd1#Sduohuhpr#gl#txhvwr#wud#srfr1
Rud#fuhhuhpr#od#qrvwud#fodvvh#vwxe/#lq#edvvr#d#ghvwud/#h#oh#urxwlqh#sulqflsdol/#fkh#vrqr#prvwudwh#qhood#sdjlqd#vhjxhqwh1
""" w_currents.pyReturns current conditions, forecast and alerts for agiven zipcode from WeatherUnderground.com.Usage: python wonderground.py [options]Options:-h, --help Show this help-l, --location City,State to use-z, --zip Zipcode to use as location
Examples: w_currents.py -h (shows this help information) w_currents.py -z 80013 (uses the zip code 80013 aslocation)"""
class CurrentInfo:"""This routine retrieves the current condition xml datafrom WeatherUnderground.com
based off of the zip code or Airport Code...currently tested only with Zip Code and Airport codeFor location,if zip code use something like 80013 (no quotes)if airport use something like "KDEN" (use double-quotes)if city/state (US) use something like "Aurora,%20CO" or“Aurora,CO” (use double-quotes)if city/country, use something like "London,%20England"(use double-quotes)"""def getCurrents(self,debuglevel,Location):pass
def output(self):passdef DoIt(self,Location):pass
#=========================================# END OF CLASS CurrentInfo()#=========================================
SURJUDPPDUH#LQ#S\WKRQ#0#SDUWH#44
SURJUDPPDUH LQ S\WKRQ SDUWH 44
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 14/42gvmm#djsdmf#nbhb{jof#$48 lqglfh#a
Ulfrughuhwh#gdjol#duwlfrol#suhfhghqwl#od#uljd#%libbqdphbb%1#Vh#od#fkldpldpr#frph#xq*dssolfd}lrqh#d#vË#vwdqwh/#od#urxwlqh#sulqflsdoh#yhuuÂ#hvhjxlwd/#dowulphqwl#od#srvvldpr#xvduh#frph#sduwh#gl#xqd#oleuhuld1#Xqd#yrowd#qhood#urxwlqh#sulqflsdoh/#frqwuroohuhpr/#vh#Ê#lo#fdvr/#frvd#Ê#vwdwr#wudvphvvr1
Vh#o*xwhqwh#xvd#lo#sdudphwur#%0k%#r#%00#khos%/#prvwuhuhpr#oh#wulsoh#uljkh#g*dlxwr#doo*lql}lr#gho#frglfh#gho#surjudppd#dwwudyhuvr#od#fkldpdwd#d#xqd#urxwlqh#gl#vxssruwr#fkh#glfh#doo*dssolfd}lrqh#gl#prvwuduhbbgrfbb1
Vh#o*xwhqwh#xvd#%0o%#+orfdolwÂ,#r#%0}%#+frglfh#srvwdoh,#o*lqirupd}lrqh#iruqlwd#vrvwlwxluÂ#txhood#lpsrvwdwd#lqwhuqdphqwh1#Txdqgr#vl#sdvvd#xqd#orfdolwÂ/#dvvlfxudwhyl#gl#xvduh#l#grssl#dslfl#shu#udffklxghuh#od#vwulqjd#h#gl#qrq#xvduh#vsd}l1#Shu#hvhpslr/#shu#uhfxshuduh#oh#dwwxdol#
frqgl}lrql#gl#Gdoodv/#Wh{dv/#xvduh#0o#%Gdoodv/Wh{dv%1
L#ohwwrul#slÛ#dvwxwl#dyudqqr#jlÂ#lqwxlwr#fkh#l#frqwurool#0}#h#0o#vrqr#suhvvrfkË#od#vwhvvd#frvd1#Srwhwh#prglilfduh#0o#shu#frqwurooduh#od#hyhqwxdoh#suhvhq}d#gl#vsd}l#h#ulirupdwwduh#od#vwulqjd#sulpd#gl#
sdvvduod#dooh#urxwlqh1#ª#txdofrvd#fkh#rupdl#gryuhvwh#hvvhuh#fdsdfl#gl#iduh1
Shu#ilqluh#fuhldpr#xq*lvwdq}d#ghood#qrvwud#fodvvh#FxuuhqwLqir#fkh#fkldpldpr#fxuuhqwv/#h#txlqgl#sdvvldpr#od#orfdolwÂ#dood#Urxwlqh#%GrLw%1#Hffr#frph#Ê#idwwd=
def DoIt(self,Location):
self.getCurrents(1,Location)
self.output()
Prowr#vhpsolfh1#Sdvvldpr#od#orfdolwÂ#h#lo#olyhoor#gl#ghexj#dood#
urxwlqh#jhwFxuuhqwv/#h#txlqgl#fkldpldpr#od#urxwlqh#gl#rxwsxw1#Dqfkh#vh#dyuhppr#srwxwr#vhpsolfhphqwh#hvhjxluh#o*rxwsxw#gluhwwdphqwh#gdood#urxwlqh#jhwFxuuhqwv/#vwldpr#vyloxssdqgr#od#iohvvlelolwÂ#shu#iruqluh#o*rxwsxw#lq#gliihuhqwl#prgl#qho#fdvr#qh#gryhvvlpr#dyhu#elvrjqr1
Lo#frglfh#shu#od#urxwlqh#jhwFxuuhqwv#Ê#prvwudwr#qhood#sdjlqd#vhjxhqwh1
Txl#deeldpr#xq#sdudphwur#fkldpdwr#ghexjohyho1#Lo#vxr#xwlol}}r#fl#shuphwwh#gl#frqwurooduh#lqirupd}lrql#xwlol#qho#fdvr#lo#
surjudppd#qrq#vl#frpsruwdvvh#qhood#pdqlhud#dvshwwdwd1#ª#dqfkh#xwloh#doo*lql}lr#ghood#idvh#gl#vyloxssr1#Vh#srl#vlhwh#frqwhqwl#gl#frph#lo#yrvwur#frglfh#ixq}lrqd/#srwhwh#ulpxryhuh#rjql#wudffld#uhodwlyd#d#ghexjohyho1#Vh#dyhwh#lqwhq}lrqh#gl#ulodvflduh#lo#frglfh#do#sxeeolfr/#frph#vh#or#vwhvwh#idfhqgr#shu#txdofxq#dowur/#dvvlfxudwhyl#gl#ulpxryhuh#lo#frglfh#
h#gl#whvwduor#qxrydphqwh#sulpd#gl#ulodvflduor1
Dghvvr#xvldpr#od#ixq}lrqh#wu|2h{fhsw#shu#dvvlfxudufl#fkh#dqfkh#vh#txdofrvd#dqgdvvh#vwruwr/#lo#surjudppd#qrq#hvsorgd1#Qhood#vh}lrqh#wu|#lpsrvwldpr#o*XUO#h#xq#wlphu#gl#;#vhfrqgl#+xuoole1vrfnhw1vhwghidxowwlphrxw+;,,
def usage():print __doc__ def main(argv):location = 80013try:opts, args = getopt.getopt(argv, "hz:l:", ["help=","zip=", "location="])except getopt.GetoptError:usage()
sys.exit(2)for opt, arg in opts:if opt in ("-h", "--help"):usage()sys.exit()elif opt in ("-l", "--location"):location = argelif opt in ("-z", "--zip"):location = argprint "Location = %s" % locationcurrents = CurrentInfo()currents.DoIt(location)
#============================================# Main loop#============================================if __name__ == "__main__":
main(sys.argv[1:])
SURJUDPPDUH#LQ#S\WKRQ#0#SDUWH#44
SURJUDPPDUH LQ S\WKRQ SDUWH 44
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 15/42gvmm#djsdmf#nbhb{jof#$48 lqglfh#a
1#Idffldpr#txhvwr#shufkË/#d#yrowh/#zxqghujurxqg#Ê#rffxsdwr#h#qrq#ulvsrqgh1#Lq#txhvwd#pdqlhud#vl#hylwd#gl#gryhu#dvshwwduh#doo*lqilqlwr1#Vh#vlhwh#lqwhuhvvdwl#d#xowhulrul#lqirupd}lrql#vx#xuoole#xq#exrq#srvwr#gd#fxl#lql}lduh#Ê#kwws=22grfv1s|wkrq1ruj2oleudu|2xuoole1kwpo1
Vh#dffdgh#txdofrvd#gl#lqdvshwwdwr#vl#sdvvd#qhood#vh}lrqh#h{fhsw#fkh#vwdpsd#xq#phvvdjjlr#gl#huuruh#h#whuplqd#o*dssolfd}lrqh#+v|v1h{lw+5,,1
Dvvxphqgr#fkh#wxwwr#ixq}lrql/#lql}ldpr#d#fhufduh#l#qrvwul#wdj1#Od#sulpd#frvd#fkh#iduhpr#Ê#fhufduh#od#qrvwud#orfdolwÂ#frq#wuhh1ilqgdoo+%22ixoo%,1#Ulfrugdwh/#wuhh#Ê#o*rjjhwwr#dqdol}}dwr#uhvwlwxlwr#gd#hohphqwwuhh1#Lq#edvvr#Ê#prvwudwr#sduwh#gl#flÔ#fkh#ylhqh#ulwruqdwr#gdoo*DSL#gho#vlwr1
Txhvwd#Ê#od#qrvwud#sulpd#lvwdq}d#gho#wdj#?ixooA/#fkh#lq#txhvwr#fdvr#Ê#%Dxurud/#FR%1#Txhvwd#Ê#od#orfdolwÂ#fkh#yrjoldpr#xvduh1#Txlqgl#fhufkldpr#%revhuydwlrqbwlph%1#Udssuhvhqwd#lo#prphqwr#gl#uhjlvwud}lrqh#ghooh#dwwxdol#frqgl}lrql1#Frqwlqxldpr#fhufdqgr#wxwwl#l#gdwl#fkh#fl#lqwhuhvvdqr#0#xvdqgr#od#vwhvvd#phwrglfd1
Shu#ilqluh#fl#rffxsldpr#ghood#qrvwud#urxwlqh#gl#rxwsxw#fkh#Ê#prvwudwd#lq#dowr#d#vlqlvwud#qhood#sdjlqd#vhjxhqwh1
Txl#vhpsolfhphqwh#prvwuldpr#oh#yduldelol1
Txhvwr#Ê#wxwwr1#Xq#rxwsxw#g*hvhpslr#shu#lo#plr#frglfh#srvwdoh#frq#xq#ghexjohyho#vhwwdwr#d#4#Ê#prvwudwr#lq#edvvr#d#vlqlvwud#qhood#survvlpd#sdjlqd1
def getCurrents(self,debuglevel,Location):if debuglevel > 0:print "Location = %s" % Locationtry:CurrentConditions ='http://api.wunderground.com/auto/wui/geo/WXCurrentObXML/index.xml?query=%s' % Locationurllib.socket.setdefaulttimeout(8)
usock = urllib.urlopen(CurrentConditions)tree = ET.parse(usock)usock.close()except:print 'ERROR - Current Conditions - Could not getinformation from server...'if debuglevel > 0:print Locationsys.exit(2)# Get Display Locationfor loc in tree.findall("//full"):self.location = loc.text
# Get Observation timefor tim in tree.findall("//observation_time"):self.obtime = tim.text# Get Current conditionsfor weather in tree.findall("//weather"):self.we = weather.text# Get Tempfor TempF in tree.findall("//temperature_string"):self.tmpB = TempF.text#Get Humidityfor hum in tree.findall("//relative_humidity"):self.relhum = hum.text
# Get Wind infofor windstring in tree.findall("//wind_string"):self.winds = windstring.text# Get Barometric Pressurefor pressure in tree.findall("//pressure_string"):self.baroB = pressure.text
jhwFxuuhqwv#urxwlqh
<display_location><full>Aurora, CO</full>
<city>Aurora</city><state>CO</state><state_name>Colorado</state_name><country>US</country><country_iso3166>US</country_iso3166><zip>80013</zip><latitude>39.65906525</latitude><longitude>-104.78105927</longitude><elevation>1706.00000000 ft</elevation></display_location>
SURJUDPPDUH#LQ#S\WKRQ#0#SDUWH#44
SURJUDPPDUH LQ S\WKRQ SDUWH 44
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 16/42gvmm#djsdmf#nbhb{jof#$48 lqglfh#a
SURJUDPPDUH#LQ#S\WKRQ#0#SDUWH#44
Vl#suhjd#gl#qrwduh#fkh#kr#vfhowr#gl#xvduh#l#wdj#fkh#lqfoxgrqr#l#ydorul#vld#lq#Idkuhqkhlw#fkh#Fhovlxv1#Vh#ghvlghudwh/#shu#hvhpslr/#ylvxdol}}duh#vror#l#ydorul#Fhovlxv#srwhwh#xvduh#lo#wdj#?whpsbfA#slxwwrvwr#fkh#?whpshudwxuhbvwulqjA1
O*lqwhur#frglfh#sxÔ#hvvhuh#vfdulfdwr#gd=#kwws=22sdvwhelq1frp27leMJp:7
Od#survvlpd#yrowd#fl#frqfhqwuhuhpr#vxood#sduwh#suhylvlrqdoh#ghooh#DSL1#Qho#iudwwhpsr/#exrq#glyhuwlphqwr$
def output(self):print 'Weather Information From Wunderground.com'print 'Weather info for %s ' % self.locationprint self.obtimeprint 'Current Weather - %s' % self.weprint 'Current Temp - %s' % self.tmpBprint 'Barometric Pressure - %s' % self.baroBprint 'Relative Humidity - %s' % self.relhum
print 'Winds %s' % self.winds
Location = 80013 Weather Information From Wunderground.com Weather info for Aurora, ColoradoLast Updated on May 3, 11:55 AM MDTCurrent Weather - Partly CloudyCurrent Temp - 57 F (14 C)Barometric Pressure - 29.92 in (1013 mb)Relative Humidity - 25%
Winds From the WNW at 10 MPHScript terminated.
Gvmm#Djsdmf#Qpedbtu
#Ê#lo#sursulhwdulr#ghood# /#xqd#vrflhwÂ#gl#frqvxohq}d#lq#Dxurud/#Frorudgr#h#surjudppd#gdo#4<:51#Dpd#fxflqduh/#iduh#hvfxuvlrql/#dvfrowduh#pxvlfd#h#sdvvduh#lo#whpsr#frq#od#vxd#idpljold1
Lo# #Ê#wruqdwr#h#pljolruh#fkh#pdl$
Jol#dujrphqwl#qhoo*hslvrglr#txdwwur#lqfoxgrqr=™#Qhzv#0#ulodvfldwr#Xexqwx#43137™#Rslqlrql™#Jlrfkl#0#Vwhdp#duulyd#vx#Olqx{B™#Ihhgedfn111h#wxwwr#lo#vrolwr#xprulvpr1
-#Urelq#Fdwolqj-#Hg#Khzlww
-#Gdyh#Zlonlqv
Lo#srgfdvw#h#oh#uhodwlyh#qrwh#ol#wurydwh#vx=kwws=22ixooflufohpdjd}lqh1ruj2
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 17/42gvmm djsdmf nbhb{jof $49
7
i n d i c e ^
KRZ0WRS c r i t t o d a G r e g W a l t e r s
Surjudppduh lq S|wkrq 0 Sduwh 45
V E D I A N C H E :
F C M # 2 7 - 3 7 - P y t h o n P a r t i 1 - 1 1
V A L I D O P E R :
C A T E G O R I E :
D I S P O S I T I V I :
G r a f i c a
S v i l u p p o I n t e r n e t
M / m e d i a
S i s t e m a
H D D
C D / D V D
U S B D r i v e L a p t o p
W i r e l e s s
N
e l l ' u l t i m a s e s s i o n e ,
a b b i a m o t r a t t a t o l ' A P I d i
w u n d e r g r o u n d e s c r i t t o
u n p o ' d i c o d i c e p e r
r i c a v a r e l e c o n d i z i o n i a t t u a l i .
Q u e s t a v o l t a c i o c c u p e r e m o d e l l a
p a r t e d e l l e A P I r i g u a r d a n t e l e
p r e v i s i o n i . S e n o n a v e t e a v u t o
m o d o d i d a r e u n ' o c c h i a t a a l l e
u l t i m e d u e p u n t a t e s u X M L , e d i n
p a r t i c o l a r e l ' u l t i m a , d o v r e s t e f a r l o
p r i m a d i p r o c e d e r e u l t e r i o r m e n t e .
C o s ì c o m e e s i s t e u n i n d i r i z z o
w e b p e r l e c o n d i z i o n i a t t u a l i , c e
n e è u n o p e r l e p r e v i s i o n i . E c c o i l
l i n k a l l a p a g i n a d e l l e p r e v i s i o n i
X M L :
h t t p : / / a p i . w u n d e r g r o u n d . c o m / a u t o
/ w u i / g e o / F o r e c a s t X M L / i n d e x . x m l ? q
u e r y = 8 0 0 1 3
C o m e a l s o l i t o , s o s t i t u i t e
' 8 0 0 1 3 ' c o n l a v o s t r a C i t t à / P a e s e ,
C i t t à / S t a t o o c o d i c e p o s t a l e .
P r o b a b i l m e n t e o t t e r r e t e c i r c a 6 0 0
r i g h e d i c o d i c e X M L . C ' è u n
e l e m e n t o r o o t c h i a m a t o ' f o r e c a s t '
e q u i n d i q u a t t r o s o t t o e l e m e n t i :
' t e r m s o f s e r v i c e ' , ' t x t _ f o r e c a s t ' ,
' s i m p l e f o r e c a s t ' a n d
' m o o n _ p h a s e ' . C i c o n c e n t r e r e m o
s u ' t x t _ f o r e c a s t ' e ' s i m p l e f o r e c a s t ' .
P o i c h é l ' u l t i m a v o l t a a b b i a m o
g i à t r a t t a t o d e l l e s e z i o n i u s a g e ,
m a i n e " i f _ _ n a m e _ _ " , q u e l l e l e
l a s c e r ò a f f r o n t a r e a v o i e c i
f o c a l i z z e r e m o s u l l e c h i c c h e d i c u i
a b b i a m o b i s o g n o q u e s t a v o l t a .
P o i c h é v i h o m o s t r a t o u n a
p o r z i o n e d i t x t _ f o r e c a s t , i n i z i a m o
d a q u i .
I n b a s s o è m o s t r a t a u n a
p i c c o l a p o r z i o n e d i t x t _ f o r e c a s t
p e r l a m i a z o n a .
D o p o l ' e l e m e n t o p r e c u r s o r e
t x t _ f o r e c a s t a b b i a m o l a d a t a , u n
e l e m e n t o " n u m b e r " , q u i n d i u n
e l e m e n t o c h i a m a t o f o r e c a s t d a y
c h e h a a s u a v o l t a d e i f i g l i c h e
i n c l u d o n o p e r i o d , i c o n , i c o n s , t i t l e
e q u a l c o s a c h i a m a t o f c t t e x t . . . e a
s e g u i r e u n a r i p e t i z i o n e d e l l o
s t e s s o . L a p r i m a c o s a c h e
n o t e r e t e i n t x t _ f o r e c a s t è c h e l a
d a t a n o n è u n a d a t a m a u n v a l o r e
t e m p o r a l e . S i t r a t t a d e l m o m e n t o
i n c u i è s t a t a f a t t a l a p r e v i s i o n e .
L ' e t i c h e t t a < n u m b e r > m o s t r a
q u a n t e p r e v i s i o n i s o n o p r e s e n t i
p e r l e p r o s s i m e 2 4 o r e . N o n
r i c o r d o d i a v e r v i s t o m a i u n v a l o r e
i n f e r i o r e a 2 . P e r c i a s c u n a
p r e v i s i o n e n e l l e 2 4 o r e
( < f o r e c a s t d a y > ) , a v r e t e u n
< p e r i o d > n u m e r i c o , o p z i o n i
m u l t i p l e p e r l e i c o n e , u n ' o p z i o n e
p e r i l t i t o l o ( " T o d a y " , " T o n i g h t " ,
" T o m o r r o w " ) e d i l t e s t o r i a s s u n t i v o
d e l l a p r e v i s i o n e . Q u e s t a è
u n ' a n t e p r i m a r a p i d a d e l l a
p r e v i s i o n e , d i s o l i t o p e r l e
s u c c e s s i v e 1 2 o r e .
P r i m a d i i n i z i a r e a l a v o r a r e c o n
i l n o s t r o c o d i c e d o v r e m m o d a r e
<txt_forecast><date>3:31 PM MDT</date><number>2</number>−<forecastday>
<period>1</period><icon>nt_cloudy</icon>+<icons></icons><title>Tonight</title>−<fcttext>
Mostly cloudy with a 20percent chance of thunderstorms in the evening...thenpartly cloudy after midnight. Lows in the mid 40s.Southeast winds 10 to 15 mph shifting to the south after
midnight.</fcttext>
</forecastday>+<forecastday></forecastday>
</txt_forecast>
SURJUDPPDUH LQ S\WKRQ SDUWH 45
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 18/42gvmm djsdmf nbhb{jof $49
8
i n d i c e ^
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 45
u n ' o c c h i a t a a l l a p o r z i o n e
< s i m p l e f o r e c a s t > d e l f i l e x m l c h e
è m o s t r a t o a d e s t r a .
C ' è u n ' e t i c h e t t a < f o r e c a s t d a y >
p e r c i a s c u n g i o r n o d e l p e r i o d o d i
p r e v i s i o n e , d i s o l i t o 6 g i o r n i
i n c l u s o q u e l l o a t t u a l e . A v e t e
i n f o r m a z i o n i s u l l a d a t a i n v a r i
f o r m a t i ( i o p e r s o n a l m e n t e
p r e f e r i s c o l ' e t i c h e t t a < p r e t t y > ) ,
t e m p e r a t u r e m a s s i m e e m i n i m e
p r e v i s t e s i a i n F a h r e n h e i t c h e
C e l s i u s , p r o i e z i o n e d e l l e c o n d i z i o n i
g e n e r a l i , v a r i e i c o n e , u n a i c o n a
d e l c i e l o ( c o n d i z i o n i d e l c i e l o a l l a
s t a z i o n e d i r i f e r i m e n t o ) , e " p o p "
c h e s t a p e r " P r o b a b i l i t à d i
P r e c i p i t a z i o n e " . L ' e t i c h e t t a
< m o o n _ p h a s e > f o r n i s c e a l c u n e
i n f o r m a z i o n i i n t e r e s s a n t i c o m e
a l b a , t r a m o n t o e f a s i l u n a r i .
O r a c i a d d e n t r i a m o n e l c o d i c e .
E c c o l a s e z i o n e d e g l i i m p o r t :
from xml.etree import
ElementTree as ET
import urllib
import sys
import getopt
D o b b i a m o o r a c r e a r e l a n o s t r a
c l a s s e . C r e e r e m o u n a r o u t i n e
_ i n i t _ p e r i m p o s t a r e e p u l i r e l e
v a r i a b i l i n e c e s s a r i e , c o m e
m o s t r a t o i n a l t o a d e s t r a n e l l a
p a g i n a s e g u e n t e .
S e n o n v i i n t e r e s s a s u p p o r t a r e
s i a F a h r e n h e i t c h e C e l s i u s ,
e s c l u d e t e l a v i a r i a b i l e c h e n o n v i
i n t e r e s s a . I o h o d e c i s o d i t e n e r l e
e n t r a m b e .
A s e g u i r e , c r e e r e m o l a n o s t r a
r o u t i n e p r i n c i p a l e p e r r e c u p e r a r e i
d a t i d e l l a p r e v i s i o n e . È m o s t r a t a
i n b a s s o a d e s t r a n e l l a p a g i n a
s u c c e s s i v a .
È m o l t o s i m i l e a l l a r o u t i n e d e l l a
v o l t a s c o r s a p e r l e c o n d i z i o n i
a t t u a l i . L a d i f f e r e n z a p r i n c i p a l e
( f i n o r a ) è l ' U R L u t i l i z z a t o . O r a l e
c o s e c a m b i a n o . D a t o c h e a b b i a m o
f i g l i m u l t i p l i c o n l a s t e s s a
e t i c h e t t a a l l ' i n t e r n o d e l g e n i t o r e
d o b b i a m o m o d i f i c a r e i n p a r t e l e
n o s t r e c h i a m a t e a l l ' a n a l i z z a t o r e . I l
c o d i c e è m o s t r a t o i n a l t o a s i n i s t r a
n e l l a p a g i n a s e g u e n t e .
N o t a t e c o m e q u e s t a v o l t a s i s t i a
u s a n d o t r e e . f i n d , e d i c i c l i p e r
s c o r r e r e i d a t i . È u n p e c c a t o c h e
P y t h o n n o n f o r n i s c a u n c o s t r u t t o
S E L E C T / C A S E c o m e i n a l t r i
l i n g u a g g i . L a r o u t i n e I F / E L I F ,
<simpleforecast>−<forecastday>
<period>1</period>−<date>
<epoch>1275706825</epoch><pretty_short>9:00 PM MDT</pretty_short><pretty>9:00 PM MDT on June 04, 2010</pretty><day>4</day><month>6</month>
<year>2010</year><yday>154</yday><hour>21</hour><min>00</min><sec>25</sec><isdst>1</isdst><monthname>June</monthname><weekday_short/><weekday>Friday</weekday><ampm>PM</ampm><tz_short>MDT</tz_short><tz_long>America/Denver</tz_long>
</date>−<high><fahrenheit>92</fahrenheit><celsius>33</celsius>
</high>−<low>
<fahrenheit>58</fahrenheit><celsius>14</celsius>
</low><conditions>Partly Cloudy</conditions><icon>partlycloudy</icon>+<icons>
<skyicon>partlycloudy</skyicon><pop>10</pop></forecastday>
...</simpleforecast>
SURJUDPPDUH LQ S\WKRQ SDUWH 45
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 19/42gvmm djsdmf nbhb{jof $49
9
i n d i c e ^
class ForecastInfo:def __init__(self):
self.forecastText = [] # Today/tonight forecastinformation
self.Title = [] # Today/tonightself.date = ''self.icon = [] # Icon to use for conditions
today/tonightself.periods = 0
self.period = 0#==============================================# Extended forecast information#==============================================self.extIcon = [] # Icon to use for extended
forecastself.extDay = [] # Day text for this forecast
("Monday", "Tuesday" etc)self.extHigh = [] # High Temp. (F)self.extHighC = [] # High Temp. (C)self.extLow = [] # Low Temp. (F)self.extLowC = [] # Low Temp. (C)
self.extConditions = [] # Conditions textself.extPeriod = [] # Numerical Period information(counter)
self.extpop = [] # Percent chance OfPrecipitation
def GetForecastData(self,location):try:
forecastdata = 'http://api.wunderground.com/auto/wui/geo/ForecastXML/index.xml?query=%s' % locationurllib.socket.setdefaulttimeout(8)usock = urllib.urlopen(forecastdata)tree = ET.parse(usock)usock.close()
except:print 'ERROR - Forecast - Could not get information from server...'sys.exit(2)
#=================================# Get the forecast for today and (if available)tonight#=================================fcst = tree.find('.//txt_forecast')
for f in fcst:if f.tag == 'number':
self.periods = f.textelif f.tag == 'date':
self.date = f.textfor subelement in f:
if subelement.tag == 'period':self.period=int(subelement.text)
if subelement.tag == 'fcttext':
self.forecastText.append(subelement.text)elif subelement.tag == 'icon':
self.icon.append( subelement.text)elif subelement.tag == 'title':self.Title.append(subelement.text)
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 45
SURJUDPPDUH LQ S\WKRQ SDUWH 45
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 20/42gvmm djsdmf nbhb{jof $49
1 0
i n d i c e ^
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 45
c o m u n q u e , f u n z i o n a a d o v e r e , è
s o l o u n p o ' p i ù a r z i g o g o l a t a . O r a
a n a l i z z i a m o i l c o d i c e . A s s e g n a m o
l a v a r i a b i l e f c s t a d o g n i c o s a
a l l ' i n t e r n o d e l l ' e t i c h e t t a
< t x t _ f o r e c a s t > c h e c o s ì i n c l u d e r à
t u t t i i d a t i p e r q u e l g r u p p o . Q u i n d i
c e r c h i a m o l e e t i c h e t t e < d a t e > e
< n u m b e r > — d a t o c h e s o n o
s e m p l i c i e t i c h e t t e d i " p r i m o
l i v e l l o " — e c a r i c h i a m o i d a t i n e l l e
n o s t r e v a r i a b i l i . O r a l e c o s e s i
f a n n o u n p o ' p i ù d i f f i c i l i . G u a r d a t e
a l n o s t r o e s e m p i o x m l d i r i s p o s t a .
C i s o n o d u e i s t a n z e d i
< f o r e c a s t d a y > . S o t t o
< f o r e c a s t d a y > c i s o n o i s o t t o -
e l e m e n t i < p e r i o d > , < i c o n > ,
< i c o n s > , < t i t l e > e < f c t t e x t > . L i
p a s s e r e m o i n r a s s e g n a e d a n c o r a
u t i l i z z i a m o l ' i s t r u z i o n e I F p e r
c a r i c a r l i n e l l e n o s t r e v a r i a b i l i .
O r a d o b b i a m o d a r e u n ' o c c h i a t a
a i d a t i s u l l e p r e v i s i o n i e s t e s e p e r i
s u c c e s s i v i X g i o r n i .
F o n d a m e n t a l m e n t e r i c o r r i a m o a l l o
s t e s s o m e t o d o u s a t o p e r
a s s e g n a r e l e n o s t r e v a r i a b i l i ;
q u e s t o è m o s t r a t o i n a l t o a d e s t r a .
A d e s s o d o b b i a m o c r e a r e l a
n o s t r a r o u t i n e p e r l ' o u t p u t . C o m e
a b b i a m o f a t t o l ' u l t i m a v o l t a , s a r à
a b b a s t a n z a g e n e r i c o . I l c o d i c e p e r
f a r e c i ò è m o s t r a t o a d e s t r a n e l l a
p a g i n a s e g u e n t e .
A n c o r a , s e n o n v o l e t e m o s t r a r e
l e i n f o r m a z i o n i s i a i n C e n t i g r a d i
c h e i n F a h r e n h e i t , m o d i f i c a t e i l
c o d i c e p e r m o s t r a r e q u e l l o c h e
v o l e t e . P e r f i n i r e a b b i a m o l a
r o u t i n e " D o I t " :
def
DoIt(self,Location,US,IncludeTo
day,Output):
self.GetForecastData(Location)
self.output(US,IncludeToday,Out
put)
O r a p o s s i a m o c h i a m a r e l a
r o u t i n e c o m e s e g u e :
forecast = ForecastInfo()
forecast.DoIt('80013',1,0,0) #
Insert your own postal code
Q u e s t o è t u t t o p e r o r a . L a s c i o i l
c o d i c e p e r i c o n t r o l l i a v o i , s e
v o l e t e c i m e n t a r v i .
E c c o i l c o d i c e e s e g u i b i l e
c o m p l e t o :
h t t p : / / p a s t e b i n . c o m / w s S X M X Q x
D i v e r t i t e v i f i n o a l l a
p r o s s i m a v o l t a .
#=================================# Now get the extended forecast
#=================================fcst = tree.find('.//simpleforecast')for f in fcst:
for subelement in f:if subelement.tag == 'period':
self.extPeriod.append(subelement.text)elif subelement.tag == 'conditions':
self.extConditions.append(subelement.text)elif subelement.tag == 'icon':
self.extIcon.append(subelement.text)elif subelement.tag == 'pop':
self.extpop.append(subelement.text)elif subelement.tag == 'date':
for child in subelement.getchildren():if child.tag == 'weekday':
self.extDay.append(child.text)elif subelement.tag == 'high':
for child in subelement.getchildren():if child.tag == 'fahrenheit':
self.extHigh.append(child.text)if child.tag == 'celsius':self.extHighC.append(child.text)
elif subelement.tag == 'low':for child in subelement.getchildren():
if child.tag == 'fahrenheit':self.extLow.append(child.text)
if child.tag == 'celsius':self.extLowC.append(child.text)
G r e g W a l t e r s è i l p r o p r i e t a r i o
d e l l a R a i n y D a y S o l u t i o n s , L L C ,
u n a s o c i e t à d i c o n s u l e n z a i n
A u r o r a , C o l o r a d o e p r o g r a m m a
d a l 1 9 7 2 . A m a c u c i n a r e , f a r e
e s c u r s i o n i , a s c o l t a r e m u s i c a e
p a s s a r e i l t e m p o c o n l a s u a
f a m i g l i a .
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 45
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 21/42
gvmm djsdmf nbhb{jof $491 1
i n d i c e ^
Gvmm DjsdmfQpedbtu
I l P o d c a s t d i F u l l C i r c l e è t o r n a t o e m i g l i o r e c h e
m a i !
G l i a r g o m e n t i n e l l ' e p i s o d i o o t t o i n c l u d o n o :
• N e w s - s v i l u p p o d i M a v e r i c k
• I n t e r v i s t a a L u b u n t u
• G i o c h i - E d r e c e n s i s c e O s m o s
• F e e d b a c k
. . . e t u t t o i l s o l i t o u m o r i s m o .
I c o n d u t t o r i :
• R o b i n C a t l i n g
• E d H e w i t t
• D a v e W i l k i n s
I l p o d c a s t e l e r e l a t i v e n o t e l i t r o v a t e s u :
h t t p : / / f u l l c i r c l e m a g a z i n e . o r g /
def output(self,US,IncludeToday,Output):# US takes 0,1 or 2# 0 = Centigrade# 1 = Fahrenheit# 2 = both (if available)# Now print it allif Output == 0:
for c in range(int(self.period)):
if c <> 1:print '-------------------------------'
print 'Forecast for %s' %self.Title[c].lower()
print 'Forecast = %s' %self.forecastText[c]
print 'ICON=%s' % self.icon[c]print '-----------------------------------'
print 'Extended Forecast...'if IncludeToday == 1:
startRange = 0else:
startRange = 1for c in range(startRange,6):print self.extDay[c]if US == 0: #Centigrade information
print '\tHigh - %s(C)' %self.extHigh[c]
print '\tLow - %s(C)' % self.extLow[c]elif US == 1: #Fahrenheit information
print '\tHigh - %s(F)' %self.extHigh[c]
print '\tLow - %s(F)' % self.extLow[c]else: #US == 2 both(if available)
print '\tHigh - %s' % self.extHigh[c]print '\tLow - %s' % self.extLow[c]
if int(self.extpop[c]) == 0:print '\tConditions - %s.' %
self.extConditions[c]else:
print '\tConditions - %s. %d%% chanceof precipitation.' %(self.extConditions[c],int(self.extpop[c]))
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 45
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 22/42
gvmm djsdmf nbhb{jof $4: :Õ lqglfh a
KRZ0WRVfulwwr gd Juhj Zdowhuv
Surjudppduh lq S|wkrq 0 Sduwh 46
Txhvwr phvh sduohuhprghoo*xvr gl Fxuvhv lqS|wkrq1 Qr/ qrq vwldprglfhqgr gl xvduh S|wkrq
shu gluh sdurodffh/ ehqfkËsrvvldwh lq fdvr qh vhqwldwh loelvrjqr1 Vwldpr sduodqgrghoo*xwlol}}r ghood oleuhuld Fxuvhvshu fuhduh txdofkh vwudydjdqwhrxwsxw ghoor vfkhupr1
Vh vlhwh yhffkl deedvwdq}d gdulfrugduh l sulpl whpsl ghlfrpsxwhu/ ulfrughuhwh fkh/ lq
dpelwr odyrudwlyr/ l frpsxwhuhudqr wxwwl pdlqiudph 0 frqvhpsolfl whuplqdol +vfkhupl hwdvwlhuh, shu o*lqsxw h o*rxwsxw1Srwhydwh dyhuh slÛ whuplqdolfroohjdwl dg xq vror frpsxwhu1 Losureohpd hud fkh l whuplqdolulvxowdydqr glvsrvlwlyl qrlrvl1 Qrqdyhydqr ilqhvwuh/ frorul r frvh ghojhqhuh 0 vror 57 uljkh gl ;3
fdudwwhul +qhooh pljolrul ghoohlsrwhvl,1 Txdqgr l shuvrqdofrpsxwhu glyhqqhur srsrodul/ dlwhpsl gl GRV h FSP/ txhvwr Êtxhoor fkh fl vl ulwurydyd1 Txdqgr lsurjudppdwrul odyrudydqr vxl orurvwudydjdqwl +shu txhl whpsl,vfkhupl/ vrsudwwxwwr shu
o*lpplvvlrqh h ylvxdol}}d}lrqh glgdwl/ xvdydqr fduwd judilfd shuglvhjqduh lo frqwhqxwr ghoorvfkhupr1 Fldvfxq eorffr vxoodfduwd judilfd udssuhvhqwdyd odsrvl}lrqh gl xq fdudwwhuh1 Txdqgrxvldpr l qrvwul surjudppl lqS|wkrq qho whuplqdoh/ dqfruddeeldpr d fkh iduh frq xqrvfkhupr 57{;31 Frpxqtxh/ txhoodolplwd}lrqh sxÔ hvvhuh idflophqwhvxshudwd frq xq*dghjxdwddffruwh}}d h suhsdud}lrqh1 Txlqgluhfdwhyl yhuvr lo slÛ ylflqr qhjr}lr
gl duwlfrol gl fdqfhoohuld hsurfxudwhyl txdofkh eorffkhwwr glfduwd judilfd1
Dg rjql prgr/ suhsduldprfl dfuhduh lo qrvwur sulpr surjudppdFxuvhv/ prvwudwr lq dowr d ghvwud1Yh or vslhjkhuÔ grsr fkh dyuhwhgdwr xq*rffkldwd do frglfh1
Euhyh pd vhpsolfh1Hvdplqldpror uljd shu uljd1 Shulql}lduh/ lqvhuldpr jol lpsruw/ fkhrupdl gryuheehur hvvhuyl idploldul1Lq vhjxlwr/ fuhhuhpr xq qxryrrjjhwwr Fxuvhu shu or vfkhupr/ orlql}ldol}}huhpr h or fkldphuhprp|vfuhhq1 +p|vfuhhq @
fxuvhv1lqlwvfu+,,1 Txhvwd Ê od qrvwudwhod fkh glslqjhuhpr1 Txlqgl/
xvldpr lo frpdqgrp|vfuhhq1erughu+3, shu glvhjqduhxq pdujlqh lqwruqr dood whod1 Qrq Êqhfhvvdulr pd uhqgh or vfkhuprslÛ judghyroh1 Txlqgl xvldpr lophwrgr dggvwu shu %vfulyhuh% vxoodqrvwud whod d sduwluh gdood uljd 45srvl}lrqh 581 Shqvdwh do phwrgr1dggvwu gl Fxuvhv frph dgxq*lvwux}lrqh sulqw1 Shu ilqluh/ lo
phwrgr 1uhiuhvk+, uhqghu lo qrvwurodyrur ylvleloh1 Vh qrq ulfdulfkldpror vfkhupr/ l qrvwul fdpeldphqwlqrq vdudqqr ylvlelol1 Txlqgldvshwwldpr fkh o*xwhqwh suhpd xqwdvwr +1jhwfk, h srl ulodvfldpro*rjjhwwr vfkhupr +1hqgzlq, shushuphwwhuh do qrvwur whuplqdoh gl
wruqduh dood qrupdolwÂ1 Lo frpdqgr
fxuvhv1hqgzlq+, Ê PROWRlpsruwdqwh h/ vh qrq ylhqhulfkldpdwr/ lo yrvwur whuplqdohulvxowhu lq xqr vwdwr gl judqghglvruglqh1 Dvvlfxudwhyl txlqgl glxvduh txhvwr phwrgr sulpd ghoodilqh ghoo*dssolfd}lrqh1
Vdoydwh txhvwr surjudppdfrph FxuvhvH{dpsoh41s| hg
hvhjxlwhor lq xq whuplqdoh1 Dofxqhfrvh gd qrwduh1 Rjqltxdoyrowdxvdwh xq erugr/ txhvwr vsuhfd xqfdudwwhuh %xwlol}}deloh% shu fldvfxqhohphqwr gho erugr vwhvvr1 Lqdjjlxqwd/ vld od srvl}lrqh ghoodolqhd fkh gho fdudwwhuh ylhqhfrqwhjjldwd d sduwluh gd ]HUR1
#!/usr/bin/env python# CursesExample1#-------------------------------# Curses Programming Sample 1#-------------------------------
import curses myscreen = curses.initscr() myscreen.border(0) myscreen.addstr(12, 25, "See Curses, See Curses Run!") myscreen.refresh() myscreen.getch()curses.endwin()
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 46
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 23/42
gvmm djsdmf nbhb{jof $4: ;Õ lqglfh a
SURJUDPPDUH LQ S\WKRQ SDUWH 46
Txhvwr vljqlilfd fkh od sulpd uljdvxo qrvwur vfkhupr Ê od olqhd 3 ho*xowlpd Ê od 561 FrvÎ/ od srvl}lrqhlq dowr d vlqlvwud Ê ulihulwd 3/3 htxhood lq edvvr d ghvwud Ê 56/:<1Idffldpr xq slffror hvhpslr +lqdowr d ghvwud, shu glprvwuduhtxhvwr1
Wxwwr prowr vhpsolfh hffhwwrfkh shu l eorffkl wu|2ilqdoo|1Ulfrugdwh/ kr ghwwr fkhfxuvhv1hqgzlq Ê PROWR lpsruwdqwhh ghyh hvvhuh ulfkldpdwr sulpdfkh o*dssolfd}lrqh whuplql1 Ehqh/ lqtxhvwd pdqlhud/ dqfkh vh oh frvhvl phwwrqr pdoh/ od urxwlqh hqgzlqyhuu ulfkldpdwd1 Fl vrqr prowlprgl gl iduor/ pd txhvwr plvhpeud deedvwdq}d vhpsolfh1
Rud fuhldpr xq phqx glvlvwhpd fdulqr1 Vh ulfrugdwh whpsrdgglhwur uhdol}}dppr
o*dssolfd}lrqh frrnerrn fkhdyhyd xq phqx +Surjudppduhlq S|wkrq 0 Sduwh ;,1 Wxwwr qhowhuplqdoh vfruuhydvhpsolfhphqwh yhuvr o*dowrtxdqgr vwdpsdydpr dvfkhupr txdofrvd1 Txhvwdyrowd suhqghuhpr txhoo*lghd h
fuhhuhpr xq vhpsolfh phqxfkh srwuhwh xwlol}}duh shudeehooluh frrnerrn1 Lq edvvr Êprvwudwr flÔ fkh xwlol}}dpprdoorud1
Txhvwd yrowd xvhuhprFxuvhv1 Lql}ldpr frq lovhjxhqwh prghoor1Suredelophqwh yruuhwh vdoyduhtxhvwr iudpphqwr gl frglfh+lq edvvr d ghvwud, shu srwhuorxwlol}}duh qhl yrvwul surjudpplixwxul1
Rud vdoydwh dqfrud lo yrvwur
#!/usr/bin/env python# CursesExample2import curses#==========================================================# MAIN LOOP#==========================================================try:
myscreen = curses.initscr() myscreen.clear()
myscreen.addstr(0,0,"0 1 2 34 5 6 7")
myscreen.addstr(1,0,"12345678901234567890123456789012345678901234567890123456789012345678901234567890")
myscreen.addstr(10,0,"10") myscreen.addstr(20,0,"20") myscreen.addstr(23,0, "23 - Press Any Key to Continue") myscreen.refresh() myscreen.getch()
finally:curses.endwin()
===================================================RECIPE DATABASE
===================================================
1 - Show All Recipes2 - Search for a recipe3 - Show a Recipe4 - Delete a recipe5 - Add a recipe6 - Print a recipe0 - Exit
===================================================Enter a selection ->
#!/usr/bin/env python#-------------------------------# Curses Programming Template#-------------------------------import curses
def InitScreen(Border):if Border == 1:
myscreen.border(0)
#==========================================================# MAIN LOOP#==========================================================
myscreen = curses.initscr()InitScreen(1)try:
myscreen.refresh()# Your Code Stuff Here...
myscreen.addstr(1,1, "Press Any Key to Continue") myscreen.getch()
finally:curses.endwin()
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 46
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 24/42
gvmm djsdmf nbhb{jof $4: <Õ lqglfh a
prghoor frph %fxuvhvphqx41s|%frvlffkË srvvldpr odyruduh vxo ilohh pdqwhqhuh lo prghoor1
Sulpd gl surfhghuhxowhulruphqwh frq lo frglfh/suhsduldprfl dg xq dssurfflrprgxoduh1 Txl +lq dowr d ghvwud, f*Ê
xq hvhpslr lq svhxgr0frglfh gltxhoor fkh dqguhpr d uhdol}}duh1
Ryyldphqwh txhvwr svhxgr0frglfh Ê vror111 svhxgr1 Pd yl gÂxq*lghd vxoo*lqglul}}r gho surjhwwrjhqhudoh1 Gdwr fkh vl wudwwd vror glxq hvhpslr/ qrq fl gloxqjkhuhprrowuh lq txhvwd vhgh/ pd vlhwh olehulgl sruwduor d frpslphqwr1 Lql}ldprfrq lo flfor sulqflsdoh +do fhqwur/doo*hvwuhpd ghvwud,1
Qrq f*Ê prowr gd surjudppduhtxl1 Deeldpr l qrvwul eorffklwu|•ilqdoo| frvÎ frph ol dyhydpr qhoprghoor1 Lql}ldol}}ldpr or vfkhuprFxuvhv h txlqgl ulfkldpldpr xqdurxwlqh fkldpdwd OrjlfOrrs1 Lo vxrfrglfh Ê prvwudwr lq edvvr/doo*hvwuhpd ghvwud1
Dqfrud/ qrq prowr/ pd Ê vror xqhvhpslr1 Txl lqyrfkhuhpr gxhixq}lrql1 Xqd fkldpdwdGrPdlqPhqx h o*dowud PdlqLqNh|1GrPdlqPhqx prvwuhu lo qrvwur
curses.initscreenLogicLoop
ShowMainMenu # Show the main menu MainInKey # This is our main input handling routine
While Key != 0:If Key == 1:
ShowAllRecipesMenu # Show the All Recipes MenuInkey1 # Do the input routines for this
ShowMainMenu # Show the main menuIf Key == 2:SearchForARecipeMenu # Show the Search for a Recipe MenuInKey2 # Do the input routines for this optionShowMainMenu # Show the main menu again
If Key == 3:ShowARecipeMenu # Show the Show a recipe menu routineInKey3 # Do the input routine for this routineShowMainMenu # Show the main menu again
… # And so on and so oncurses.endwin() # Restore the terminal
# MAIN LOOPtry:
myscreen = curses.initscr()LogicLoop()
finally:curses.endwin()
def LogicLoop():DoMainMenu()
MainInKey()
def DoMainMenu(): myscreen.erase() myscreen.addstr(1,1,
"========================================") myscreen.addstr(2,1, " Recipe
Database") myscreen.addstr(3,1,
"========================================") myscreen.addstr(4,1, " 1 - Show All
Recipes") myscreen.addstr(5,1, " 2 - Search for a
recipe")
myscreen.addstr(6,1, " 3 - Show a recipe") myscreen.addstr(7,1, " 4 - Delete a recipe") myscreen.addstr(8,1, " 5 - Add a recipe") myscreen.addstr(9,1, " 6 - Print a recipe") myscreen.addstr(10,1, " 0 - Exit") myscreen.addstr(11,1,
"========================================") myscreen.addstr(12,1, " Enter a selection: ") myscreen.refresh()
SURJUDPPDUH LQ S\WKRQ SDUWH 46
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 46
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 25/42
gvmm djsdmf nbhb{jof $4: 43Õ lqglfh a
SURJUDPPDUH LQ S\WKRQ SDUWH 46
phqx sulqflsdoh/ phqwuh PdlqLqNh|jhvwlu rjql dowud frvd gl txhvwrphqx sulqflsdoh1 Od urxwlqhGrPdlqPhqx Ê prvwudwd d ghvwud1
Qrwdwh frph txhvwd ixq}lrqhqrq idffld dowur fkh sxoluh orvfkhupr +p|vfuhhq1hudvh, h txlqgl
vwdpsduh txhoor fkh yrjoldpr1 Qrqf*Ê qlhqwh txl fkh vl rffxsl ghoodjhvwlrqh ghood wdvwlhud1 Txhvwr Ê loodyrur ghood urxwlqh PdlqLqNh|/ fkhÊ prvwudwd lq edvvr1
Vl wudwwd gl xqd ixq}lrqhgdyyhur vhpsolfh1 Vl hqwud lq xqflfor zkloh ilqfkË lo wdvwr suhpxwrgdoo*xwhqwh Ê xjxdoh d 31 Doo*lqwhuqrgho flfor/ frqwurooldpr vh Ê xjxdohd glyhuvl ydorul h/ vh frvÎ/ odqfldprxqd vhulh gl ixq}lrql h txdqgrilqlwr ulfkldpldpr lo phqx
sulqflsdoh1 Srwhwh frpsohwduh odpdjjlru sduwh gl txhvwh ixq}lrqlgd vrol/ pd gduhpr xq*rffkldwddoo*rs}lrqh 5/ Vhdufk iru d Uhflsh1Txhvwr phqx Ê euhyh h jud}lrvr1
def MainInKey():key = 'X'
while key != ord('0'):key = myscreen.getch(12,22)
myscreen.addch(12,22,key)if key == ord('1'):
ShowAllRecipesMenu()DoMainMenu()
elif key == ord('2'):SearchForARecipeMenu()InKey2()DoMainMenu()
elif key == ord('3'):ShowARecipeMenu()DoMainMenu()
elif key == ord('4'):
NotReady("'Delete A Recipe'")DoMainMenu()
elif key == ord('5'):NotReady("'Add A Recipe'")DoMainMenu()
elif key == ord('6'):NotReady("'Print A Recipe'")DoMainMenu()
myscreen.refresh()
def SearchForARecipeMenu(): myscreen.addstr(4 ,1, "------------------------ -------") myscreen.addstr(5,1, " Search in") myscreen.addstr(6 ,1, "------------------------ -------") myscreen.addstr(7,1, " 1 - Recipe Name") myscreen.addstr(8,1, " 2 - Recipe Source") myscreen.addstr(9,1, " 3 - Ingredients") myscreen.addstr(10,1," 0 - Exit") myscreen.addstr(11,1,"Enter Search Type -> ") myscreen.refresh()
def InKey2():key = 'X'doloop = 1
while doloop == 1:key = myscreen.getch(11,22)
myscreen.addch(11,22,key)tmpstr = "Enter text to search in "if key == ord('1'):
sstr = "'Recipe Name' for -> "tmpstr = tmpstr + sstrretstring = GetSearchLine(13,1,tmpstr)break
elif key == ord('2'):sstr = "'Recipe Source' for -> "
tmpstr = tmpstr + sstrretstring = GetSearchLine(13,1,tmpstr)break
elif key == ord('3'):sstr = "'Ingredients' for -> "tmpstr = tmpstr + sstrretstring = GetSearchLine(13,1,tmpstr)break
else:retstring = ""break
if retstring != "": myscreen.addstr(15,1,"You entered - " + retstring)
else: myscreen.addstr(15,1,"You entered a blank string")
myscreen.refresh() myscreen.addstr(20,1,"Press a key") myscreen.getch()
def GetSearchLine(row,col,strng): myscreen.addstr(row,col,strng) myscreen.refresh()instring = myscreen.getstr(row,len(strng)+1)
myscreen.addstr(row,len(strng)+1,instring) myscreen.refresh()return instring
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 46
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 26/42
gvmm djsdmf nbhb{jof $4: 44Õ lqglfh a
Juhj Zdowhuv Ê lo sursulhwdulrghood Udlq|Gd| Vroxwlrqv/ OOF/xqd vrflhw gl frqvxohq}d lqDxurud/ Frorudgr h surjudppdgdo 4<:51 Dpd fxflqduh/ iduhhvfxuvlrql/ dvfrowduh pxvlfd hsdvvduh lo whpsr frq od vxdidpljold1
SURJUDPPDUH LQ S\WKRQ SDUWH 46
Gvmm DjsdmfQpedbtu
Lo Srgfdvw gl Ixoo Flufoh Ê wruqdwr h pljolruh fkhpdl$
Jol dujrphqwl qhoo*hslvrglr glhfl lqfoxgrqr=™ Qhzv™ Rslqlrqh 0 Frqwulexluh djol duwlfrol frq lo uhgdwwruhgl IFP1™ Lqwhuylvwd frq Dpehu Judqhu™ Ihhgedfn111h wxwwr lo vrolwr xprulvpr1
L frqgxwwrul=
… Urelq Fdwolqj
… Hg Khzlww ™ Urqqlh Wxfnhu
Lo srgfdvw h oh uhodwlyh qrwh ol wurydwh vx=kwws=22ixooflufohpdjd}lqh1ruj2
Od ixq}lrqh LqNh|5 +d ghvwud, Êxq sr* slÛ frpsolfdwd1
Dqfrud/ vwldpr xvdqgr xq flforzkloh vwdqgdug1 Lpsrvwldpr odyduldeloh grorrs @ 4/ frvlffkË loqrvwur flfor frqwlqxl vhq}d ilqhilqfkË qrq wuryldpr txhoor fkh
yrjoldpr1 Xvldpr lo frpdqgreuhdn shu lqwhuurpshuh lo flfor1 Ohwuh rs}lrql vrqr prowr vlplol1 Odgliihuhq}d vrvwdq}ldoh Ê fkhlql}ldpr frq xqd yduldelohfkldpdwd wpsvwu/ h srldjjlxqjldpr xqd txdoxqtxhrs}lrqh fkh deeldpr vfhowr111uhqghqgrod xq sr* slÛ dplfkhyroh1Txlqgl fkldpldpr od ixq}lrqhJhwVhdufkOlqh shu rwwhqhuh odvwulqjd gd fhufduh1 Xvldpr odurxwlqh jhwvwu shu ulfhyhuhgdoo*xwhqwh xqd vwulqjd slxwwrvwrfkh xq fdudwwhuh1 Txlqgluhvwlwxldpr od vwulqjd dood ixq}lrqhgl lqsxw shu o*hoderud}lrqhvxffhvvlyd1
Lo frglfh frpsohwr Êdoo*lqglul}}r=kwws=22sdvwhelq1frp2HOx]6W7S
Xq*xowlpd frvd1 Vh vlhwhlqwhuhvvdwl dg dssurirqgluh Fxuvhv/fl vrqr prowl dowul phwrglglvsrqlelol rowuh d txhool xwlol}}dwl
txhvwr phvh1 Rowuh d iduh xqdulfhufd frq Jrrjoh/ lo pljolru sxqwrgl sduwhq}d Ê od grfxphqwd}lrqhxiilfldoh=kwws=22grfv1s|wkrq1ruj2oleudu|2fxuvhv1kwpo1
Dood survvlpd1
RRSV$
Vhpeud fkh lo frglfh shuS|wkrq Sw144 qrq vld vwdwrvwdpsdwr fruuhwwdphqwh vxSdvwhelq1 O*lqglul}}r fruuhwwrshu lo frglfh Ê=kwws=22sdvwhelq1frp2Sn:7iOI6
Frqvxowdwh dqfkh=kwws=22ixooflufohpdjd}lqh1sdvwhelq1frp shu wxwwr lo frglfhS|wkrq +dqfkh ixwxur,1
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 27/42
ixoo flufoh pdjd}lqh &73 ; lqglfh a
KKRRZZ00WWRRVfulwwr gd Juhj Zdowhuv SSuurrjjuuddppppdduuhh llqq SS||wwkkrrqq 00 SSdduuwwhh 4477
O *xowlpd yrowd deeldprwudwwdwr od oleuhuld Fxuvhv1Txhvwd yrowddssurirqgluhpr
o*dujrphqwr frqfhqwudqgrfl vxlfrpdqgl shu lo froruh1 Vh yl vlhwhshuvl o*duwlfror suhfhghqwh/ hffr xqeuhyh uldvvxqwr1 Sulpd gl wxwwrgryhwh lpsruwduh od oleuhuld fxuvhv1Txlqgl gryhwh lql}ldol}}duh frqfxuvhv1lqlwvfu1 Shu lqvhuluh lo whvwrvxoor vfkhupr vl fkldpd od ixq}lrqhdggvwu h txlqgl uhiuhvk shuprvwuduh l fdpeldphqwl1 Lqilqh
fkldpdwh fxuvhv1hqgzlq+, shuulsulvwlqduh od ilqhvwud gho whuplqdohdo vxr vwdwr qrupdoh1
Rud fuhhuhpr xq surjudppdvhpsolfh h yhorfh fkh xvd l frorul1 Ãprowr vlploh d txdqwr jlÛ idwwr pdfrq o*djjlxqwd gl qxryl frpdqgl1 Vlxvd sulpd fxuvhv1vwduwbfroru+, shugluh do vlvwhpd fkh yrjoldpr xvduh l
frorul qho qrvwur surjudppd1Txlqgl dvvhjqldpr od frssld glfrorul shu lo whvwr h or virqgr1Srvvldpr dvvhjqduh slô frsslh hvfhjolhuh txdoh xvduh gl yrowd lqyrowd1 O*dvvhjqd}lrqh dyylhqhwudplwh od ixq}lrqh fxuvhv1lqlwbsdlu1Od vlqwdvvl ã=
curses.init_pair([pairnumber],[foregroundcolor],[background color])
L frorul vrqr lpsrvwdwl xvdqgr
%fxuvhv1FRORUb% frq lo froruhghvlghudwr1 Shu hvhpslr/fxuvhv1FRORUbEOXH rfxuvhv1FRORUbJUHHQ1 L srvvlelolydorul vrqr eodfn/ uhg/ juhhq/ |hoorz/eoxh/ pdjhqwd/ f|dq h zklwh1 Edvwddjjlxqjhuh lq pdlxvfror lo qrph ghofroruh d %fxuvhv1FRORUb%1 Xqd yrowdghilqlwh oh qrvwuh frsslh gl frorul/srvvldpr xvduoh frph sdudphwur
ilqdoh ghood ixq}lrqh vfuhhq1dggvwufrph qhood vhjxhqwh uljd=
myscreen.addstr([row],[column],[text],curses.color_pair(X))
Txl [ udssuhvhqwd lo vhw gl frorulfkh yrjoldpr xvduh1
Vdoydwh lo vhjxhqwh frglfh +lqdowr d ghvwud, frph froruwhvw41s|txlqgl hvhjxlwhor1 Qrq fhufdwh glhvhjxluh xq surjudppd fxuvhv lqxqd LGH frph VSH r Gu1 S|wkrq1Hvhjxlwhor lq xq whuplqdoh1
Flí fkh gryuhvwh yhghuh ã xqr
virqgr juljlr frq wuh uljkh gl whvwruhfdqwl od vfulwwd %Wklv lv d whvw% lqfrorul gliihuhqwl1 Lo sulpr gryuheehhvvhuh qhur0vx0yhugh/ lo vhfrqgreox0vx0eldqfr h lo whu}r pdjhqwd
vxoor virqgr juljlr1
Ulfrugdwh od frssld Wu|2Ilqdoo|1 Lovxr xwlol}}r fl shuphwwh glulsulvwlqduh lo whuplqdoh do vxr vwdwrqrupdoh vh txdofrvd gl vedjoldwr vlgryhvvh yhulilfduh1 Lq dowhuqdwlyd ãsrvvleloh xvduh lo frpdqgr fxuvhv
fkldpdwr zudsshu1 Zudsshu hvhjxhlo odyrur do srvwr yrvwur1 Hvhjxhfxuvhv1lqlwvfu+,/ fxuvhv1vwduwbfroru+,h fxuvhv1hqgzlq+, frvç gd qrqgryhuor iduh yrl vwhvvl1 Yl gryhwh
vror ulfrugduh gl ulfkldpduhfxuvhv1zudsshu qhood yrvwudixq}lrqh pdlq1 Txhvwd uhvwlwxlvfhxq sxqwdwruh door vfkhupr1 Qhoodsdjlqd vhjxhqwh +lq dowr d ghvwud,f*ã or vwhvvr surjudppd dsshqdfuhdwr pd frq od ixq}lrqhfxuvhv1zudsshu1
import cursestry:
myscreen = curses.initscr()curses.start_color()curses.init_pair(1, curses.COLOR_BLACK,
curses.COLOR_GREEN)curses.init_pair(2, curses.COLOR_BLUE,
curses.COLOR_WHITE)curses.init_pair(3,
curses.COLOR_MAGENTA,curses.COLOR_BLACK) myscreen.clear() myscreen.addstr(3,1," This is a test
",curses.color_pair(1)) myscreen.addstr(4,1," This is a test
",curses.color_pair(2)) myscreen.addstr(5,1," This is a test
",curses.color_pair(3))
myscreen.refresh() myscreen.getch()finally:
curses.endwin()
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 47
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 28/42
ixoo flufoh pdjd}lqh &73 < lqglfh a
Frph yhghwh ã prowr slôvhpsolfh h qrq deeldpr elvrjqr glfkldpduh fxuvhv1hqgzlq+, vh vlyhulilfd txdofkh huuruh1 Ylhqh idwwrwxwwr do srvwr qrvwur1
Rud fkh deeldpr xqdlqidulqdwxud ghooh edvl/ phwwldpr d
iuxwwr txhoor fkh deeldpr lpsdudwrqhoo*xowlpr dqqr gl odyrur h fuhldprxq jlrfr1 Sulpd gl lql}lduh/ghilqldpr txhoor fkh dqguhpr diduh1 Lo qrvwur jlrfr suhqghuÛ xqdohwwhud pdlxvfrod txdoxqtxh h odpxryhuÛ gdo odwr ghvwur do vlqlvwurghoor vfkhupr1 D xqd srvl}lrqhfdvxdoh txhvwd fdpelhuÛ gluh}lrqhgluljhqgrvl yhuvr lo edvvr1 Qrl
dyuhpr xq %fdqqrqh% fkh srwuÛhvvhuh prvvr wudplwh l wdvwl iuhffldghvwud h vlqlvwud frvç gd srvl}lrqduorvrwwr od ohwwhud lq fdgxwd1 Txlqglsuhphqgr od eduud vsd}lr srwuhprvsduduh1 Vh frosluhpr od ohwwhudsulpd fkh txhvwd udjjlxqjd loqrvwur fdqqrqh uhdol}}huhpr xqsxqwr1 Dowulphqwl lo qrvwur fdqqrqhhvsorghuÛ1 Vh shugldpr wuh fdqqrqllo jlrfr ilqluÛ1 Dqfkh vh sxívhpeuduh xq jlrfr vhpsolfh lquhdowÛ f*ã sduhffklr frglfh gdvfulyhuh1
Lql}ldpr1 Greeldpr suhsduduh loqrvwur odyrur h fuhduh dofxqh
ixq}lrql sulpd gl surfhghuhxowhulruphqwh1 Fuhldpr xq qxryrsurjhwwr h fkldpldpror jdph41s|1Lql}ldpr frq lo frglfh prvwudwr lqedvvr d ghvwud=
Txhvwr frglfh do prphqwr qrqid judqfkä/ pd ã lo qrvwur sxqwr gl
lql}lr1 Qrwdwh fkh deeldpr txdwwurlvwux}lrql lqlwbsdlu shu ghilqluh lfrorul fkh xvhuhpr frph qrvwul vhwfdvxdol h xqr shu oh hvsorvlrql+qxphur 8,1 Rud greeldprlpsrvwduh dofxqh yduldelol h frvwdqwlfkh xvhuhpr gxudqwh lo jlrfr1 Ohlqvhuluhpr qhood urxwlqh bblqlwbb ghood fodvvh Jdph41 Vrvwlwxlwho*lvwux}lrqh sdvv lq bblqlwbb frq lo
frglfh ghood sdjlqd vhjxhqwh1
Gryuhvwh hvvhuh lq judgr glfdsluh frvd dffdgh lq txhvwhghilql}lrql1 Vh do prphqwrgryhvvhur vrujhuh gxeel/ wxwwrgryuheeh glyhqwduh fkldur slôdydqwl1
Vldpr ylflql dg rwwhqhuhtxdofrvd gl hvhjxleloh1 Pdqfdqrdqfrud srfkh urxwlqh1 Odyruldprvxood ixq}lrqh fkh pxryh xqdohwwhud gd ghvwud d vlqlvwud vxoorvfkhupr=kwws=22ixooflufohpdjd}lqh1sdvwhelq1frp2}8FjPDjp
import cursesdef main(stdscreen):
curses.init_pair(1, curses.COLOR_BLACK,curses.COLOR_GREEN)
curses.init_pair(2, curses.COLOR_BLUE,curses.COLOR_WHITE)
curses.init_pair(3,curses.COLOR_MAGENTA,curses.COLOR_BLACK)
stdscreen.clear()
stdscreen.addstr(3,1," This is a test",curses.color_pair(1))
stdscreen.addstr(4,1," This is a test",curses.color_pair(2))
stdscreen.addstr(5,1," This is a test",curses.color_pair(3))
stdscreen.refresh()stdscreen.getch()
curses.wrapper(main)
import cursesimport random
class Game1():def __init__(self):
passdef main(self,stdscr):
curses.init_pair(1, curses.COLOR_BLACK,curses.COLOR_GREEN)
curses.init_pair(2, curses.COLOR_BLUE,curses.COLOR_BLACK)
curses.init_pair(3, curses.COLOR_YELLOW,curses.COLOR_BLUE)
curses.init_pair(4, curses.COLOR_GREEN,curses.COLOR_BLUE)
curses.init_pair(5, curses.COLOR_BLACK,curses.COLOR_RED)
def StartUp(self):curses.wrapper(self.main)
g = Game1()g.StartUp()
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 47
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 29/42
ixoo flufoh pdjd}lqh &73 43 lqglfh a
Txhvwd ã od urxwlqh slô frusrvdghoo*lqwhur surjudppd/ h d vxd yrowdlqwurgxfh qxryh ixq}lrql1vfuq1ghofk+, fdqfhood lo fdudwwhuh dxqd gdwd uljd2frorqqd1fxuvhv1qdspv+, glfh d s|wkrq glihupduvl shu [ ploolvhfrqgl +pv,1
Od orjlfd ghood urxwlqh vl wuryd +lqsvhxgrfrglfh, qhood sdjlqdvhjxhqwh +lq dowr d ghvwud,1
Rud gryuhvwh hvvhuh lq judgr glvhjxluh lo frglfh1 Deeldpr elvrjqrgl gxh qxryh urxwlqh shu jdudqwluhfkh wxwwr vld fruuhwwr1 Od sulpd ãH{sorgh/ lq fxl lqvhuluhpr odgluhwwlyd sdvv1 Od vhfrqgd ã
UhvhwIruQhz1 Txl ulsulvwlqhuhpr oduljd fruuhqwh shu od ohwwhud dood uljdsuhghilqlwd/ od frorqqd fruuhqwh/lpsrvwhuhpr GursslqjOhwwhu d 3/suhqghuhpr xqd ohwwhud h xq sxqwrgl fdgxwd fdvxdol1 Qhood sdjlqd fkhvhjxh/ do fhqwur d ghvwud vrqrsuhvhqwdwh oh gxh ixq}lrql1
Deeldpr rud elvrjqr gl dowuhtxdwwur ixq}lrql shu pdqwhqhuh lowxwwr +sdjlqd vhjxhqwh/ lq edvvr dghvwud,1 Xqd shu od ohwwhud fdvxdoh/xq*dowud shu lo sxqwr gl fdgxwd1Ulfrugdwh fkh deeldpr glvfxvvryhorfhphqwh lo prgxor udqgrpdoo*lql}lr ghood vhulh1
Lq SlfnDOhwwhu jhqhuldpr xqlqwhur fdvxdoh wud 98 h <3 +gd %D% d%]%,1 Vh ulfrugdwh/ txdqgr vl xvd odixq}lrqh udqgrp elvrjqd iruqluh xqydoruh plqlpr h xqr pdvvlpr1Vwhvvd frvd shu SlfnGursSrlqw1Hvhjxldpr dqfkh xqd fkldpdwd dudqgrp1vhhg+, lq hqwudpeh oh
urxwlqh fkh dvvhjqd do jhqhudwruh
fdvxdoh xq qxphur glyhuvr dg rjqlfkldpdwd1 Od txduwd ixq}lrqh ãFkhfnNh|v1 Txhvwd vl rffxsd glfrqwurooduh l wdvwl suhpxwlgdoo*xwhqwh h wudgxuol lq prylphqwlgho fdqqrqh1 Frpxqtxh shu loprphqwr qrq od frpsohwhuhpr/ oriduhpr slô wdugl1 Deeldpr elvrjqr
dqfkh ghood ixq}lrqh FkhfnIruKlw/
dqfkh txhvwd vror glfkldudwd1defCheckKeys(self,scrn,keyin):
passdef CheckForHit(self,scrn):
pass
Rud fuhhuhpr xqd euhyh
# Line Specific Stuffself.GunLine = 22 #Row where our gun livesself.GunPosition = 39 #Where the gun starts on GunLineself.LetterLine = 2 #Where our letter runs right to leftself.ScoreLine = 1 #Where we are going to display the scoreself.ScorePosition = 50 #Where the score column isself.LivesPosition = 65 #Where the lives column is
# Letter Specific Stuff
self.CurrentLetter = "A" #A dummy Holder Variableself.CurrentLetterPosition = 78 #Where the letter will start on the LetterLineself.DropPosition = 10 #A dummy Holder Variableself.DroppingLetter = 0 #Flag - Is the letter dropping?self.CurrentLetterLine = 3 #A dummy Holder Variableself.LetterWaitCount = 15 #How many times should we loop before actually
working?
# Bullet Specific Stuffself.Shooting = 0 #Flag - Is the gun shooting?self.BulletRow = self.GunLine - 1self.BulletColumn = self.GunPosition
# Other Stuffself.LoopCount = 0 #How many loops have we done in MoveLetterself.GameScore = 0 #Current Game Scoreself.Lives = 3 #Default number of livesself.CurrentColor = 1 #A dummy Holder Variableself.DecScoreOnMiss = 0 #Set to 1 if you want to decrement the
#score every time the letter hits the#bottom row
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 47
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 30/42
ixoo flufoh pdjd}lqh &73 44 lqglfh a
ixq}lrqh fkh vduÛ lo %fhuyhoor% ghoqrvwur jlrfr1 Od fkldphuhprJdphOrrs +sdjlqd vhjxhqwh/ lq dowrd ghvwud,1
Od orjlfd fkh vwd glhwur vl edvdqhoo*lpsrvwduh od qrvwud wdvwlhud vxqrghod|+4,1 Txhvwr vljqlilfd fkh qrq
dwwhqghuhpr fkh xq wdvwr yhqjdsuhpxwr h txdqgr dffdgh oruhjlvwuldpr shu xq xwlol}}rvxffhvvlyr1 Txlqgl hqwuldpr lq xqflfor zkloh iru}dwr d hvvhuh vhpsuhyhur +4, frvlffkä lo jlrfr ydgd dydqwlilqfkä qrq vldpr surqwl d vphwwhuh1Phwwldpr lq sdxvd shu 73ploolvhfrqgl txlqgl pxryldpr odqrvwud ohwwhud h frqwurooldpr vh
o*xwhqwh kd suhpxwr xq wdvwr1 Vh ãxqd %T% +qrwdwh fkh ã lq pdlxvfror,r lo wdvwr HVF doorud lqwhuurpsldprlo flfor h whuplqldpr lo surjudppd1Dowulphqwl frqwurooldpr vh vl wudwwdgho wdvwr iuhffld ghvwud r vlqlvwud rod eduud vsd}lr1 Vxffhvvlydphqwh ãsrvvleloh uhqghuh lo jlrfr slôfrpsohvvr frqiurqwdqgr lo wdvwrsuhpxwr frq lo fdudwwhuh fruuhqwh htxlqgl vsduduh vror vh o*xwhqwh kdsuhpxwr or vwhvvr wdvwr/ frph xqsurjudppd shu pljolruduh odgdwwlorjudild1 Ulfrugdwhyl glulpxryhuh %T% frph wdvwr glfklxvxud1
Deeldpr dqfkh elvrjqr gl xqd
ixq}lrqh fkh lpsrvwl fldvfxqdqxryd sduwlwd1 Od fkldpldprQhzJdph +sdjlqd vhjxhqwh/ dofhqwur d ghvwud,1
Qhfhvvlwldpr dqfkh ghoodurxwlqh SulqwVfruh fkh prvwud losxqwhjjlr fruuhqwh h lo qxphur glylwh uhvwdqwl +sdjlqd vhjxhqwh/ lqedvvr d ghvwud,1
Rud greeldpr vror djjlxqjhuhxq sr* gl frglfh +sdjlqd vhjxhqwh/ lqedvvr d vlqlvwud, dood qrvwud ixq}lrqh
IF we have waited the correct number of loops THENReset the loop counterIF we are moving to the left of the screen THEN
Delete the character at the the current row,column.Sleep for 50 millisecondsIF the current column is greater than 2 THEN
Decrement the current columnSet the character at the current row,columnIF the current column is at the random column to drop to the bottom THEN
Set the DroppingLetter flag to 1ELSEDelete the character at the current row,columnSleep for 50 millisecondsIF the current row is less than the line the gun is on THEN
Increment the current row Set the character at the current row,column
ELSEIFExplode (which includes decrementing the score if you wish) and check to
see if we continue.Pick a new letter and position and start everything over again.
ELSEIncrement the loopcounterRefresh the screen.
def Explode(self,scrn):pass
def ResetForNew(self):self.CurrentLetterLine = self.LetterLineself.CurrentLetterPosition = 78self.DroppingLetter = 0self.PickALetter()self.PickDropPoint()
def PickALetter(self):random.seed()char = random.randint(65,90)self.CurrentLetter = chr(char)
def PickDropPoint(self):random.seed()self.DropPosition = random.randint(3,78)
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 47
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 31/42
ixoo flufoh pdjd}lqh &73 45 lqglfh a
pdlq shu lql}lduh lo flfor1 Dowurfrglfh ã lq edvvr1 Djjlxqjhwhorvrwwr o*xowlpd fkldpdwd d lqlwbsdlu1
Rud gryuhppr dyhuh xqsurjudppd fkh id txdofrvd1Surydwhor1 Lr dvshwwr1
Lo surjudppd suhqgh xqd ohwwhudpdlxvfrod fdvxdoh/ od pxryh gdghvwud d vlqlvwud ghoor vfkhupr shuxq qxphur fdvxdoh gl frorqqhtxlqgl od pxryh yhuvr lo edvvr1Frpxqtxh xqd frvd fkh qrwhuhwh hfkh dg rjql dyylr gho surjudppd odsulpd ohwwhud ã vhpsuh xqd %D% h losxqwr gl fdgxwd ã vhpsuh odfrorqqd 431 Txhvwr shu yld ghlydorul suhghilqlwl lq bblqlwbb1 Shu
ulvroyhuh fkldpdwhvhoi1UhvhwIruQhz sulpd gl hqwuduhqho flfor zkloh qhood ixq}lrqh Pdlq1
D txhvwr sxqwr greeldprodyruduh vxo qrvwur %fdqqrqh% h ohurxwlqh gl vxssruwr1 Djjlxqjhwh lofrglfh +sdjlqd vhjxhqwh/ lq dowr d
ghvwud, dood fodvvh Jdph41
Pryhjxq vl rffxsd gl pxryhuh lofdqqrqh lq txdoxqtxh gluh}lrqh vlyrjold1 O*xqlfd vh}lrqh qxryd lqtxhvwd urxwlqh ã od ixq}lrqh dggfk1Fkldpldpr frorusdlu +5, shu ghilqluhlo froruh h/ door vwhvvr whpsr/iru}ldpr lo fdqqrqh dg dyhuho*dwwulexwr judvvhwwr1 Xvldpro*rshudwruh gl elwzlvh RU +%•%, shu
def GameLoop(self,scrn):test = 1 #Set the loop
while test == 1:curses.napms(20)self.MoveLetter(scrn)keyin =
scrn.getch(self.ScoreLine,self.ScorePosition)if keyin == ord('Q') or keyin == 27: # 'Q'
or <Esc>break
else:self.CheckKeys(scrn,keyin)
self.PrintScore(scrn)if self.Lives == 0:
breakcurses.flushinp()scrn.clear()
def NewGame(self,scrn):self.GunChar = curses.ACS_SSBS
scrn.addch(self.GunLine,self.GunPosition,self.GunChar,curses.color_pair(2) | curses.A_BOLD)
scrn.nodelay(1) #Don't wait for akeystroke...just cache it.
self.ResetForNew()self.GameScore = 0self.Lives = 3self.PrintScore(scrn)scrn.move(self.ScoreLine,self.ScorePosition)
def PrintScore(self,scrn):
scrn.addstr(self.ScoreLine,self.ScorePosition,"SCORE:%d" % self.GameScore)
scrn.addstr(self.ScoreLine,self.LivesPosition,"LIVES:%d" % self.Lives)
stdscr.addstr(11,28,"Welcome to Letter Attack")stdscr.addstr(13,28,"Press a key to begin....")stdscr.getch()stdscr.clear()PlayLoop = 1
while PlayLoop == 1:self.NewGame(stdscr)self.GameLoop(stdscr)stdscr.nodelay(0)
curses.flushinp()stdscr.addstr(12,35,"Game Over")stdscr.addstr(14,23,"Do you want to play
again? (Y/N)")keyin = stdscr.getch(14,56)if keyin == ord("N") or keyin == ord("n"):
breakelse:
stdscr.clear()
def MoveGun(self,scrn,direction):SURJUDPPDUH LQ S\WKRQ 0 SDUWH 47
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 32/42
ixoo flufoh pdjd}lqh &73 46 lqglfh a
iru}duh o*dwwulexwr d yhur1 Txlqglgreeldpr gduh frusr dood urxwlqhFkhfnNh|v1 Vrvwlwxlwh o*lvwux}lrqhsdvv frq lo qxryr frglfh +sdjlqdvhjxhqwh/ lq edvvr d ghvwud,1
Rud deeldpr elvrjqr gl xqdurxwlqh shu pxryhuh lo surlhwwloh
yhuvr o*dowr +lq edvvr d vlqlvwud,1
Deeldpr dqfrud elvrjqr gl dowuhixq}lrql +sdjlqd vhjxhqwh/ lq dowr dghvwud, sulpd gl ilqluh1 Hffr lo frglfhshu frpsohwduh od ixq}lrqhFkhfnIruKlw h lo frglfh shuH{sorghExoohw1
Shu ilqluh/ frpsohwldpr H{sorgh1
Vrvwlwxldpr sdvv frq lo vhjxhqwhfrglfh +survvlpd sdjlqd/ lq edvvr,1
Deeldpr ilqdophqwh xqsurjudppd ixq}lrqdqwh1 Srwhwhshuvrqdol}}duh lo ydoruh lqOhwwhuZdlwFrxqw shu yhorfl}}duh rudoohqwduh lo prylphqwr ghoodohwwhud vxoor vfkhupr shu uhqghuorslô gliilfloh r idfloh1 Srwhwh dqfkhxvduh od yduldeloh FxuuhqwFroru shuvfhjolhuh fdvxdophqwh xqr ghltxdwwr frorul gd dvvhjqduh doodohwwhud1 Yl odqflr txhvwd vilgd1
Vshur fkh yl vldwh glyhuwlwltxhvwd yrowd h fkh djjlxqjhuhwhdowur frglfh shu uhqghuh lo jlrfr slô
glyhuwhqwh1 Frph do vrolwr/ o*lqwhursurjhwwr ã glvsrqleloh suhvvrzzz1wkhghvljqdwhgjhhn1frprdoo*lqglul}}rkwws=22ixooflufohpdjd}lqh1sdvwhelq1frp2GhUhhk;p
( , , )scrn.addch(self.GunLine,self.GunPosition," ")if direction == 0: # left
if self.GunPosition > 0:self.GunPosition -= 1
elif direction == 1: # rightif self.GunPosition < 79:
self.GunPosition += 1
scrn.addch(self.GunLine,self.GunPosition,self.GunChar,curses.color_pair(2) | curses.A_BOLD)
if keyin == 260: # left arrow - NOT on keypadself.MoveGun(scrn,0)curses.flushinp() #Flush out the input buffer for safety.
elif keyin == 261: # right arrow - NOT on keypadself.MoveGun(scrn,1)curses.flushinp() #Flush out the input buffer for safety.
elif keyin == 52: # left arrow ON keypadself.MoveGun(scrn,0)curses.flushinp() #Flush out the input buffer for safety.
elif keyin == 54: # right arrow ON keypadself.MoveGun(scrn,1)
curses.flushinp() #Flush out the input buffer for safety.elif keyin == 32: #spaceif self.Shooting == 0:
self.Shooting = 1self.BulletColumn = self.GunPositionscrn.addch(self.BulletRow,self.BulletColumn,"|")curses.flushinp() #Flush out the input buffer for safety.
def MoveBullet(self,scrn):scrn.addch(self.BulletRow,self.BulletColumn," ")if self.BulletRow > self.LetterLine:
self.CheckForHit(scrn)self.BulletRow -= 1
scrn.addch(self.BulletRow,self.BulletColumn,"|")else:
self.CheckForHit(scrn)
scrn.addch(self.BulletRow,self.BulletColumn," ")self.BulletRow = self.GunLine - 1self.Shooting = 0
Juhj Zdowhuv ã lo sursulhwdulr ghoodUdlq|Gd| Vroxwlrqv/ OOF/ xqd vrflhwÛgl frqvxohq}d lq Dxurud/ Frorudgr hsurjudppd gdo 4<:51 Dpd fxflqduh/iduh hvfxuvlrql/ dvfrowduh pxvlfd hsdvvduh lo whpsr frq od vxd idpljold1
SURJUDP LQ S\WKRQ 0 SDUW 47
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 33/42
ixoo flufoh pdjd}lqh &73 47 lqglfh a
def CheckForHit(self,scrn):if self.Shooting == 1:
if self.BulletRow == self.CurrentLetterLine:if self.BulletColumn == self.CurrentLetterPosition:
scrn.addch(self.BulletRow,self.BulletColumn," ")
self.ExplodeBullet(scrn)self.GameScore +=1self.ResetForNew()
def ExplodeBullet(self,scrn):scrn.addch(self.BulletRow,self.BulletColumn,"X",curses.color_pair(5))scrn.refresh()curses.napms(200)scrn.addch(self.BulletRow,self.BulletColumn,"|",curses.color_pair(5))scrn.refresh()curses.napms(200)scrn.addch(self.BulletRow,self.BulletColumn,"-",curses.color_pair(5))scrn.refresh()curses.napms(200)scrn.addch(self.BulletRow,self.BulletColumn,".",curses.color_pair(5))
scrn.refresh()curses.napms(200)scrn.addch(self.BulletRow,self.BulletColumn," ",curses.color_pair(5))scrn.refresh()curses.napms(200)
scrn.addch(self.CurrentLetterLine,self.CurrentLetterPosition,"X",curses.color_pair(5))curses.napms(100)scrn.refresh()scrn.addch(self.CurrentLetterLine,self.CurrentLetterPosition,"|",curses.color_pair(5))curses.napms(100)
scrn.refresh()scrn.addch(self.CurrentLetterLine,self.CurrentLetterPosition,"-",curses.color_pair(5))curses.napms(100)scrn.refresh()scrn.addch(self.CurrentLetterLine,self.CurrentLetterPosition,".",curses.color_pair(5))curses.napms(100)scrn.refresh()scrn.addch(self.CurrentLetterLine,self.CurrentLetterPosition," ")scrn.addch(self.GunLine,self.GunPosition,self.GunChar,curses.color_pair(2) | curses.A_BOLD)scrn.refresh()
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 34/42
ixoo flufoh pdjd}lqh &74 ; frqwhqwv a
KKRRZZ00WWRRVfulwwr gd Juhj Zdowhuv SSuurrjjuuddppppdduuhh llqq SS||wwkkrrqq 00 SSdduuwwhh 4488
T xhvwr phvh dqguhpr dghvsoruduhS|jdph/ xq vhwglprgxol surjhwwdwrshuvfulyhuh jlrfkl1 lo vlwr zhe ã
kwws=22zzz1s|jdph1ruj2 1Xqdflwd}lrqh gdoiloh uhdgphgl S|jdph=%S|jdph ã xqdoleuhuld pxowl0sldwwdirupdsurjhwwdwdshu uhqghuhidflohod vfulwwxudgl vriwzduhpxowlphgldol/ frph l jlrfkl/ lq S|wkrq1S|jdph ulfklhgh lo olqjxdjjlr S|wkrqh od oleuhuld pxowlphgldohVGO1 Sxídqfkh iduh xvrgl dowuh glyhuvh oleuhulhprowrqrwh1%
Vl sxílqvwdooduh S|jdphdwwudyhuvrV|qdswlf frph *s|wkrq0jdph*1Idwhor rud lq prgr fkhsrvvldpr dqgduh dydqwl1
Lq sulpr oxrjr lpsruwldprS|jdph+yhgl vrsud d ghvwud,1Vxffhvvlydphqwh lpsrvwhuhprrv1hqylurq shu idu vç fkh odqrvwudilqhvwud vldfhqwudwd vxoqrvwurvfkhupr1 Grsr gl fkhlql}ldol}}huhpr
S|jdph/ srl lpsrvwhuhpr od ilqhvwudS|jdph d ;33{933 sl{ho h srl odglgdvfdold1 Lqilqhylvxdol}}huhprodvfkhupdwd h dqguhpr lq xq orrs gldwwhvdghood suhvvlrqhgl xq wdvwr vxoodwdvwlhudr gl xqsxovdqwh gho prxvh1Or vfkhupr ã xq rjjhwwr fkhfrqwlhqh txdoxqtxhfrvd ghflgldprgl
lqilodufl1 Ã fkldpdwr vxshuilflh1Shqvdwh frph vhirvvh xq sh}}r glfduwd vx fxlglvhjqhuhpr oh frvh1
Qrq prowr hfflwdqwh/pdã jlÛ xqlql}lr1Uhqgldpror xq sr* phqrqrlrvr1 Srvvldpr fdpelduh lo froruhghoor virqgr frq xqtxdofrvdgl phqrvfxur1Kr wurydwr xq surjudppdglqrph %froruqdph% fkhsrwhwhlqvwdooduhwudplwh XexqwxVriwzduhFhqwhu1 Txhvwryl shuphwwh gl xvduh od%uxrwdghl frorul% shusuhqghuh lofroruhfkhylsldfhhylgduÛlydorulUJE ryyhur Uhg/ Juhhq/ Eoxh gl txho
froruh1 Greeldpr xvduh l frorul UJEvh qrq yrjoldprxvduh l frorulsuhghilqlwl fkhS|jdphfl riiuh1Vlwudwwdgl xq surjudppd dffxudwr glfxlvl gryuheeh suhqghuh lqfrqvlghud}lrqh o*lqvwdood}lrqh1
Vxelwr grsr oh glfkldud}lrqlg*lpsruwd}lrqh djjlxqjhwh111
Background = 208, 202, 104
Txhvwr lpsrvwhuÛ od yduldelohEdfnjurxqg vx xq froruhgrudwr1Vxffhvvlydphqwhgrsr od olqhds|jdph1glvsod|1vhwbfdswlrq/djjlxqjhwhoh vhjxhqwl olqhh111
screen.fill(Background)pygame.display.update()
Lo phwrgrvfuhhq1iloo+, lpsrvwhuÛlofroruh d wxwwr flívx fxl sdvvldprvrsud1Od olqhd vxffhvvlyd/s|jdph1glvsod|1xsgdwh+,/ lq uhdowÛdjjlruqd l fdpeldphqwl dl qrvwulvfkhupl1
Vdoydwh txhvwr frq lo qrph gls|jdph41s| h dqgldpr dydqwl1
Rudprvwuhuhpr dofxqlwhvwl vxoqrvwur prghvwr vfkhupr1Qxrydphqwhlql}ldpr frq o*lpsruwduhoh qrvwulglfkldud}lrql h od yduldelohgldvvhjqd}lrqh gl edfnjurxqgghoqrvwur xowlprsurjudppd1
import pygamefrom pygame.locals import *import osBackground = 208, 202, 104
Rud/djjlxqjhwhxqd yduldelohdjjlxqwlyd shulo froruhgl sulpr sldqrghood qrvwudirqw1
FontForeground = 255,255,255 # White
Txlqgl djjlxqjhuhpr qhoodpdjjlru sduwh ghofrglfhgdoqrvwurxowlpr surjudppd+prvwudwrdghvwud,1
#This is the Importimport pygamefrom pygame.locals import *import os# This will make our game window centered in the screen
os.environ['SDL_VIDEO_CENTERED'] = '1'# Initialize pygamepygame.init()#setup the screenscreen = pygame.display.set_mode((800, 600))# Set the caption (title bar of the window)pygame.display.set_caption('Pygame Test #1')# display the screen and wait for an eventdoloop = 1
while doloop:if pygame.event.wait().type in (KEYDOWN,
MOUSEBUTTONDOWN):
break
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 48
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 35/42
ixoo flufoh pdjd}lqh &74 < frqwhqwv a
Vhorvlhvhjxhdghvvrqrqãfdpeldwr qlhqwhylvlydphqwh gdoprphqwr fkhdeeldpr djjlxqwrodghilql}lrqh lq sulpr sldqr 1 Rud grsrod olqhd vfuhhq1iloo+, h sulpd ghoorrsghoqrvwurfrglfh/lqvhulwh oh vhjxhqwlolqhh=
font =pygame.font.Font(None,27) text= font.render('Here is sometext', True, FontForeground,Background) textrect =text.get_rect()screen.blit(text,textrect)pygame.display.update()
Dqgdwhdydqwl/ vdoydwh losurjudppd frq lo qrphgl
s|jdph51s|hg hvhjxlwhor1QhoorVfkhupr lq dowr d vlqlvwud vl gryuheehyhghuh lo whvwr •Khuh lv vrphwh{w‘1
Dqgldpr d vfulyhuh dofxql frpdqgl1Lq sulpr oxrjr fkldpldprlo phwrgrIrqw h orsdvvldpr d gxh dujrphqwl1 Losulpr ã lo qrphghood irqw fkhghvlghuldpr xvduh h lo vhfrqgr ã odglphqvlrqh ghood irqw1 Lq txhvwr
prphqwr fl olplwhuhpr d xvduh *Qrqh*h odvflduh fkh lo vlvwhpd vfhojdxqwlsrgl fdudwwhuh shu qrl h lpsrvwldprodglphqvlrqh ghofdudwwhuhd 5: sxqwl1
Grsr deeldpr lo phwrgrirqw1uhqghu+,1 Txhvwr kd txdwwurdujrphqwl1 Lq ruglqh fl vrqr= l whvwl
fkhghvlghuldpr prvwuduh vhyrjoldpr xvduho*dqwl0doldvlqj +Yhurlqtxhvwrfdvr,/ lo froruhghofdudwwhuhlqsulpr sldqr h lqilqh lo froruhghofdudwwhuh gl virqgr1
Od olqhdvxffhvvlyd+wh{w1jhwbuhfw+,,dvvhjqd xq rjjhwwr uhwwdqjroduhfkh
xvhuhpr shulqvhuluh lo whvwr vxoorvfkhupr1 Txhvwdã xqdfrvdlpsruwdqwh gdoprphqwr fkhtxdvlwxwwr lo uhvwr gl fxl fl rffxshuhprãfrq l uhwwdqjrol +fdsluhwhgl slô lq xqvhfrqgr prphqwr,1Srl pxryldpr+eolw, lo uhwwdqjror vxoor vfkhupr1 Hilqdophqwh djjlruqldpr or vfkhuprshuiduprvwuduh lo qrvwurwhvwr1Frvdyxro gluh %eolw%h shufkägldplqh
gryuhliduh txdofrvd fkhvxrqd frvçvwudqrB Lo whuplqh ulvdohdjol dqql *:3 hyhqlydgd[hur{ SDUF+gd fxlsurylhqh prowdghoodwhfqrorjldrglhuqd,1 Lo whuplqh ruljlqdohhudElwEOWfkh vljqlilfdElw+ruElwpds,Eorfn Wudqvihu1Srlyhqqh fdpeldwr lqEolw +iruvhshufkäã slô fruwr,1Sudwlfdphqwh vwldpr pxryhqgr odqrvwudlppdjlqh r lo qrvwurwhvwrvxoorvfkhupr1
Fkh iduh vhyrjoldpr fkh lo whvwryhqjd fhqwudwr vxoor vfkhupr lqyhfhfkh vxood uljdlq dowr gryhfl yxroh xqsr* gl whpsr shu yhghuorB Wud odolqhdwh{w1jhwbuhfw+, h vfuhhq1eolw lqvhulwh oh
vhjxhqwl gxholqhh=
textRect.centerx =screen.get_rect().centerxtextRect.centery =screen.get_rect().centery
Dghvvrvwldprulohydqgrlo fhqwurghoo*rjjhwwr vfkhupr +ulfrugdwh/vxshuilflh, qhooh srvl}lrql lq sl{ho { h |h vwldprlpsrvwdqgr l sxqwl fhqwudol {h | gho qrvwur rjjhwwr wh{wUhfwd txhlydorul1
Hvhjxlwh lo surjudppd1 Rudloqrvwurwhvwr ã fhqwudwr qhoodvxshuilflh1Srwhwh lqrowuh prglilfduhlowhvwr xvdqgr+qho qrvwurvhpsolfhfrglfh,irqw1vhwberog+Wuxh, h2r
irqw1vhwblwdolf+Wuxh, d ghvwud grsr od
olqhd s|jdph1irqw1Irqw1
Ulfrugdwh/deeldpr glvfxvvreuhyhphqwh vxoo*lpsrvwd}lrqh *Qrqh*txdqgrlpsrvwldpr lo wlsr glfdudwwhuhd xq irqw jhqhulfr1Lppdjlqldpr fkhgl yrohu xwlol}}duhxq irqw slô hoderudwr1Frph krghwwrsulpdlo s|jdph1irqw1Irqw+, phwkrgkd gxhdujrphqwl1 Lo sulpr vl ulihulvfh
do shufruvr h doqrphgho iloh ghoodirqw fkhyruuhppr xvduh/ lo vhfrqgrid ulihulphqwr dood glphqvlrqh ghofdudwwhuh1 D txhvwrsxqwr lo sureohpdã lo shufruvr1Frph idffldpr d vdshuhlo yhurshufruvr h lo qrph gho iloh ghoodirqw fkh yruuhppr xvduh lq xqtxdoxqtxh vlvwhpdB Shu iruwxqd
# This will make our game window centered in the screenos.environ['SDL_VIDEO_CENTERED'] = '1'# Initialize pygamepygame.init()# Setup the screenscreen = pygame.display.set_mode((800, 600))# Set the caption (title bar of the window)pygame.display.set_caption('Pygame Test #1')screen.fill(Background)
pygame.display.update()
# Our Loopdoloop = 1
while doloop:if pygame.event.wait().type in (KEYDOWN,
MOUSEBUTTONDOWN):break
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 48
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 36/42
ixoo flufoh pdjd}lqh &74 43 frqwhqwv a
S|jdphkdxqd ixq}lrqh fkh fl shqvdshuqrl1Vl fkldpdpdwfkbirqw1 Hffrtxl xq surjudppdfkh prvwuhuÛ loshufruvr h lo qrphgho iloh ghood irqw+lq txhvwrfdvr, Frxulhu Qhz1
import pygamefrom pygame.locals import *import osprintpygame.font.match_font('Courier New')
Qhoplrvlvwhpd lo ydoruhuhvwlwxlwrã%2xvu2vkduh2irqwv2wuxhw|sh2pvwwfruhi rqwv2frxu1wwi%1Vh shuí lo irqw qrqylhqh wurydwr lo ydoruh gl ulwruqr ã•Qrqh‘1 Dpphwwhqgr lo fdvr fkhod
irqw à vwdwd wurydwd/ doorudsrvvldprdvvhjqduhd xqdyduldelohlo ydoruhuhvwlwxlwrh gl frqvhjxhq}d srvvldprxvduhoh vhjxhqwl dwwulex}lrql1
courier =pygame.font.match_font('Courier New') font =pygame.font.Font(courier,27)
Fdpeldwh od yrvwudxowlpdyhuvlrqhghosurjudppd lqvhuhqgrtxhvwhgxholqhh h surydwh gl qxryr1O*xowlpdolqhd glfh txhvwr= xvdwh xq fdudwwhuhfkhyrlVDSHWHhvvhuhglvsrqleloh qhofrpsxwhu ghoo*xwhqwhilqdoh rssxuhlqfoxghwhortxdqgr glvwulexlwhloyrvwursurjudppdh frglilfdwhlo
shufruvr h lo qrphghood irqw1 Fl vrqrdowul prgl shu iduhod vwhvvdfrvd/ pdor odvflr fdsluh d yrl lq prgr fkhsrvvldpr dqgduh dydqwl1
Vhlo whvwr ã ehoor/ odjudilfd ã shuípljolruh1Kr wurydwr xq wxwruldoyhudphqwhfdulqrshuS|jdphvfulwwr
gd Sh|wrq PfFrooxjk h kr shqvdwr glsuhqghuorh prglilfduor1Shutxhvwdsduwh deeldpr elvrjqr gl lql}lduh frqxqd iljxud fkh vl pxryhuÛ lqwruqr odqrvwudvxshuilflh1 Txhvwdiljxudãqrwd frph *vsulwh*1 Xwlol}}dwh JLPS rtxdofkh dowur vwuxphqwrshufuhduhxqdiljxudvwlol}}dwd1 Qlhqwh glidqwdvwlfr/ vror xqdjhqhulfd iljxudvwlol}}dwd1 Vl suhvxph fkhvwldwh
xvdqgrJLPS1 Fuhdwhxqdqxrydlppdjlqh/lpsrvwdwhoh glphqvlrqlgldowh}}d h odujkh}}d d 83sl{ho h qhoohrs}lrql dydq}dwh lpsrvwdwhloulhpslphqwrvx wudvsduhqwh1Xwlol}}dwh or vwuxphqwrpdwlwdfrqxqshqqhoor ulwrqgr+36,1 Glvhjqdwhodyrvwudslffrod iljxudh vdoydwhodfrphvwlfn1sqjqhood vwhvvdfduwhood fkhdyhwh xvdwr shu lo frglfh1 Hffr frphdssduhtxhoodpld1 Vrqr vlfxurfkhyrlvdshwhiduh gl phjolr1
Orvr111 qrq vrqrxq*duwlvwd1 Wxwwdyld shulqrvwulvfrsl edvwd1Deeldpr vdoydwr lo iloh
frph 1sqj h deeldpr lpsrvwdwrorvirqgrvx wudvsduhqwh lq prgr fkhyhqjdqr prvwudwh vror oh slffroholqhh qhuh ghood qrvwudiljxudvwlol}}dwdhqrqxqrvirqgreldqfrrglxqdowurfroruh1
Yhgldpr dghvvr frvdyrjoldprfkhlo surjudppd idffld1 Yrjoldprprvwuduh xqdilqhvwud gl S|jdphfrqod qrvwudiljxudvwlol}}dwd lq hvvd1Yrjoldpr fkhod iljxudvl pxrydtxdqgrsuhpldpr txdoxqtxh iuhffldgluh}lrqdoh+vx/ jlô/ghvwud/ vlqlvwud,vhpsuhfkh qrq vldpr vxo erugr ghoorvfkhupr h odiljxudqrq vl srvvdpxryhuh xowhulruphqwh1 Yruuhpr
xvfluhgdojlrfr txdqgrsuhpldpr lowdvwr •t‘1 Rud vsrvwduh or vsulwh lq jlursrwuheeh vhpeuduhidfloh h orã/ pdãxq sr* slô gliilfloh gl txdqwr vhpeullql}ldophqwh1 Lql}ldpr fuhdqgr gxhuhwwdqjrol1 Xqrshuor vsulwhvh vwhvvrh xqrghooh vwhvvhglphqvlrql pdeldqfr1 Pxryldpr or vsulwhvxood
vxshuilflh shulql}lduh/ srltxdqgro*xwhqwh suhph xq wdvwr pxryldpr louhwwdqjror eldqfrvrsud or vsulwhruljlqdoh/ulohyldpr od qxrydsrvl}lrqhh pxryldpr qxrydphqwh or vsulwhvxoodvxshuilflh qhoodqxrydsrvl}lrqh1Slô r phqr txhoorfkh deeldpr idwwro*xowlpd yrowd frqlo jlrfrghoo*doidehwr1 Txhvwrã wxwwr shutxhvwrsurjudppd1 Fl gduÛ xq*lghdglfrph phwwhuh hiihwwlydphqwh xqhohphqwr judilfr vxoor vfkhupr hpxryhuor1
Txlqgl lql}ldpr xq qxryrsurjudppdh or fkldpldprs|jdph71s|1 Srvl}lrqdwhor qhoodfduwhood lqfoxghv fkhdeeldpr xvdwr
gxudqwh txhvwr wxwruldo1 Txhvwd yrowdxwlol}}huhpr xqrvirqgrgl froruhyhugh phqwd/txlqgl l ydorulgryuheehur hvvhuh3/ 588/ 45:+yhglvrsud,1
Vxffhvvlydphqwh fuhldpr xqdfodvvh fkh jhvwluÛ odqrvwud judilfd r or
import pygamefrom pygame.locals import *import os
Background = 0,255,127os.environ['SDL_VIDEO_CENTERED'] = '1'pygame.init()screen = pygame.display.set_mode((800, 600))pygame.display.set_caption('Pygame Example #4 - Sprite')
screen.fill(Background)
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 48
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 37/42
ixoo flufoh pdjd}lqh &74 44 frqwhqwv a
vsulwh+ã prvwudwr qhood sdjlqdvxffhvvlyd lq edvvr d vlqlvwud,1 Phwwhwhtxhvwrsdudphwurgrsr ohlpsruwd}lrql1
Fkh frv*ã wxwwr txhvwrfkh vwridfhqgrB Frplqfldpr frqod urxwlqhbblqlwbb1 Lql}ldol}}ldpr lo prgxor ghoor
vsulwh gl S|jdph frq odolqhds|jdph1vsuwh1Vsulwh1bblqlwbb1Srllpsrvwldpr od vxshuilflh h odfkldpldpr vfkhupr1 Txhvwr fl
shuphwwhuÛ gl frqwurooduh vh or *vsulwh*yd ixrul gdoor vfkhupr1Vxffhvvlydphqwhfuhldpr hlpsrvwldpr od srvl}lrqh ghoodyduldeloh yxrwdrogvsulwh/fkhpdqwhuuÛ od srvl}lrqhghoqrvwurvsulwh1 Rudfdulfkldpr od qrvwudiljxudvwlol}}dwd frqod urxwlqh
s|jdph1lpdjh1ordg/ lqglfdqgrohloqrphgho iloh +h loshufruvr/ vhtxhvwrqrqã qhoshufruvr ghosurjudppd,1Txlqgl dftxlvldpr xq ulihulphqwr
+vhoi1uhfw, door vsulwhfkhlpsrvwldxwrpdwlfdphqwhod odujkh}}dho*dowh}}dgho uhwwdqjror h lpsrvwl odsrvl}lrqh{/|gl txho uhwwdqjror doodsrvl}lrqhfkhdeeldpr sdvvdwr qhoodurxwlqh1
Od urxwlqh gl djjlruqdphqwrsudwlfdphqwh fuhd xqdfrsld ghoor
vsulwh/srl frqwuroodvh txhvwryd ixrulgdoor vfkhupr1 Vh ã frvç/ ulpdqhgry*ã/dowulphqwl od vxdsrvl}lrqhylhqhvsrvwdwdgl txho wdqwr fkh fkh jol
deeldpr lqglfdwr1
Rud/ grsr od glfkldud}lrqhvfuhhq1iloo/ lqvhulwh lo frglfhulsruwdwrqhoodsdjlqd vhjxhqwh +odwrghvwur,1
Txl fuhldpr xq*lvwdq}dghoodqrvwudfodvvhgl qrph %fkdudfwhu%1Srl
pxryldpr or vsulwh1 Fuhldpr or vsulwhuhwwdqjroduh yxrwrh ulhpsldprorfrqlo froruhgl virqgr1 Djjlruqldpr odvxshuilflhh lql}ldpr lo qrvwurflfor1
Ilqr d txdqgrGrOrrs ãhtxlydohqwh d 4/ hiihwwxldpr lo orrsdwwudyhuvrlo frglfh1Xvldprs|jdph1hyhqw1jhw+, shu dyhuhxqfdudwwhuhgdood wdvwlhud1Srlor
yhulilfkldprd vhfrqgd ghowlsr glhyhqwr1 Vhã TXLW/ xvfldpr1 Vhã xqhyhqwrNH\GRZQ gl s|jdphorhvhjxldpr1Jxdugldprlo ydoruh ghoodfkldyhuhvwlwxlwdh od frqiurqwldprfrqoh frvwdqwl ghilqlwh gd S|jdph1Srl fkldpldpro*djjlruqdphqwrghoodurxwlqhqhood qrvwudfodvvh1 Qrwdwhtxlfkh vwldpr vhpsolfhphqwh sdvvdqgrxqd olvwd fkh frqwlhqh l qxphul ghl
sl{ho ghjol dvvl[ h \ shu pxryhuh loshuvrqdjjlr1Or fdpeldpr gl 43 sl{ho+srvlwlyryhuvr ghvwudr vrwwr hqhjdwlyr yhuvr vlqlvwud r vrsud,1 Vh loydoruh ghood fkldyh ã xjxdoh d •t‘/lpsrvwldprGrOrrsd 3 h xvfldpr gdoorrs1 Grsr wxwwr txhvwrpxryldpr loshuvrqdjjlr yxrwrdoodyhffkld
class Sprite(pygame.sprite.Sprite):def __init__(self, position):
pygame.sprite.Sprite.__init__(self)# Save a copy of the screen's rectangleself.screen = pygame.display.get_surface().get_rect()
# Create a variable to store the previous position of the spriteself.oldsprite = (0, 0, 0, 0)self.image = pygame.image.load('stick3.png')self.rect = self.image.get_rect()self.rect.x = position[0]self.rect.y = position[1]
def update(self, amount):# Make a copy of the current rectangle for use in erasingself.oldsprite = self.rect# Move the rectangle by the specified amountself.rect = self.rect.move(amount)
# Check to see if we are off the screenif self.rect.x < 0:self.rect.x = 0
elif self.rect.x > (self.screen.width - self.rect.width):self.rect.x = self.screen.width - self.rect.width
if self.rect.y < 0:self.rect.y = 0
elif self.rect.y > (self.screen.height - self.rect.height):self.rect.y = self.screen.height - self.rect.height
SURJUDPPDUH LQ S\WKRQ 0 SDUWH 48
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 38/42
ixoo flufoh pdjd}lqh &74 45 frqwhqwv a
srvl}lrqh/ pxryldpr or vsulwhqhoodqxryd srvl}lrqhh frph xowlpdfrvddjjlruqldpr> pd lq txhvwrfdvrdjjlruqldpr vror l gxhuhwwdqjrolfrqwhqhqwl or vsulwhyxrwr h txhoordwwlyr1 Txhvwrfrqvhqwh glulvsduplduh xqdtxdqwlwÛ hqruphglwhpsr h gl hoderud}lrqh1
Frph vhpsuho*lqwhur frglfhãudjjlxqjleloh do vlwrzzz1wkhghvljqdwhgjhhn1frprdoo*lqglul}}rkwws=22ixooflufohpdjd}lqh1sdvwhelq1frp2GyVs]edm1
Vl srvvrqr iduhprowh slôfrvhfrqS|jdph1 Frqvljolrgl ylvlwduh lo orurvlwr h gl jxdugduhodsdjlqdglulihulphqwr
+kwws=22zzz1s|jdph1ruj2grfv2uhi2lqgh{1kwpo,1 Lq djjlxqwd srwhwhgduhxq*rffkldwd dl jlrfklfkhjoldowulkdqqrfdulfdwr1
Od survvlpd yrowd vfdyhuhprslôlqsurirqglwÛ vx S|jdphfuhdqgr xqjlrfr fkhsurylhqh gdoplrsdvvdwr111gdoplrsdvvdwr prowr ORQWDQR1
character = Sprite((screen.get_rect().x, screen.get_rect().y))screen.blit(character.image, character.rect)
# Create a Surface the size of our characterblank = pygame.Surface((character.rect.width, character.rect.height))blank.fill(Background)
pygame.display.update()
DoLoop = 1 while DoLoop:
for event in pygame.event.get():if event.type == pygame.QUIT:
sys.exit()# Check for movementelif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:character.update([-10, 0])
elif event.key == pygame.K_UP:character.update([0, -10])
elif event.key == pygame.K_RIGHT:
character.update([10, 0])elif event.key == pygame.K_DOWN:character.update([0, 10])
elif event.key == pygame.K_q:DoLoop = 0
# Erase the old position by putting our blank Surface on itscreen.blit(blank, character.oldsprite)# Draw the new positionscreen.blit(character.image, character.rect)# Update ONLY the modified areas of the screenpygame.display.update([character.oldsprite, character.rect])
Juhj Zdowhuv ã lo sursulhwdulr ghoodUdlq|Gd| Vroxwlrqv/ OOF / xqd vrflhwÛgl frqvxohq}d lq Dxurud/ Frorudgr hsurjudppd gdo 4<:51 Dpd fxflqduh/iduh hvfxuvlrql/ dvfrowduh pxvlfd hsdvvduh lo whpsr frq od vxd idpljold1
HHOOWW TTOO
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 39/42
full circle magazine #42 8indice ^
HHOOWW00TTOOScritto da Greg Walters PPrrooggrraammmmaarree iinn PPyytthhoonn 00 PPaarrttee 1166
Tempo fa promisi a
qualcuno che avrei
trattato le differenze tra
Python 2.x e 3.x. La volta
scorsa dissi che avremmo
continuato la programmazione con
pygame ma sento che dovrei
mantenere la mia promessa così
approfondiremo di più pygame la
prossima volta.
In Python 3.x sono stati fatti
molti cambiamenti. Sul web c'è una
gran quantità di informazioni
riguardo questi mutamenti e allafine dell'articolo includerò alcuni
collegamenti. Vi sono anche molte
preoccupazioni relativamente al
fare il cambiamento. Mi
concentrerò sulle variazioni che
riguardano le cose che avete
imparato finora.
Forza, iniziamo.
Come ho detto prima uno degliargomenti più importanti è il modo
in cui affrontiamo il comando print.
Con la versione 2.x possiamo usare
semplicemente:
print "This is a test"
e così sarà fatto. Tuttavia, con la
3.x, se ci proviamo otterremo il
messaggio di errore mostrato sopraa destra.
Non è bello. Per usare il
comando print dobbiamo mettere
ciò che vogliamo stampare tra
parentesi tonde così:
print ("This is a test")
Non è un cambiamento molto
grande ma è qualcosa di cui
dobbiamo essere consapevoli.
Potete prepararvi alla migrazioneutilizzando questa sintassi sotto
Python 2.x.
Formattazione esostituzionedivariabile
Anche la formattazione e la
sostituzione di variabile sono
cambiate. Con la versione 2.xabbiamo usato cose simili
all'esempio mostrato sotto a
sinistra e, con la versione 3.1,
potete ottenere il giusto risultato.
Comunque ciò è dovuto al
cambiamento dato che le funzioni
di formattazione '%s' e '%d'
spariranno. Il nuovo modo,
mostrato sotto, è usare le
dichiarazioni di sostituzione '{x}'.
In effetti mi sembra essere più
facile da leggere. Potete anche fare
cose come questa:
>>> print ("Hello {0}. I'm glad you are here at{1}.format("Fred","MySite.com "))
Hello Fred. I'm glad you arehere at MySite.com
>>>
Ricordate, potete ancora usare
'%s' e così via ma essi spariranno.
Numeri
Sotto Python 2.x, se facevate:x = 5/2.0x avrebbe contenuto 2.5. Tuttavia
se aveste fatto:
>>> print "This is a test"File "<stdin>", line 1
print "This is a test"^
SyntaxError: invalid syntax
>>>
>>> months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']
>>> print "You selected month %s" % months[3]You selected month Apr>>>
>>> months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']>>> print("You selected month {0}".format(months[3]))You selected month Apr>>>
VECCHIO METODO
NUOVO METODO
PROGRAMMARE IN PYTHON 0 PARTE 16
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 40/42
full circle magazine #42 9indice ^
x = 5/2x avrebbe contenuto 2 grazie al
troncamento. Sotto la versione 3.x
se fate:x = 5/2ottenete ancora 2.5. Per troncare la
divisione dovete fare:x = 5//2
Input
Un po' di tempo fa abbiamo
avuto a che fare con un sistema di
menù che usava raw_input() per
ottenere una risposta dall'utente
della nostra applicazione. Qualcosa
che andava così:
response = raw_input('Enter aselection -> ')
Questo andava bene sotto la
versione 2.x. Tuttavia sotto la 3.x
otteniamo:
Traceback (most recent calllast):
File "<Stdin>", line 1,
in <module>
NameError: name 'raw_input'is not definited
Questo non è un grosso
problema. Il metodo raw_input() è
stato sostituito da input().
Semplicemente, cambiate la riga in:
response = input ('Enter aselection -> ')
e funziona proprio bene.
Non uguale
Sotto la versione 2.x avremmo
potuto fare un test di "nonuguaglianza" con "<>". Tuttavia ciò
non è consentito nella versione 3.x.
L'operatore di prova adesso è "!=".
Convertire i programmipiù vecchi in Python 3.x
Python 3.x
arriva con una
utility che aiuta a
convertire
un'applicazione 2.x
in codice conforme
alla versione 3.x.
Non funziona
sempre ma vi ci porterà vicini inmolti casi. Lo strumento di
conversione viene chiamato "2to3".
Prendiamo come esempio un
programma davvero semplice.
L'esempio sotto è preso da
Programmare in Python Parte 3 di
tempo addietro.
Quando viene eseguito sotto la
versione 2.x, l'output è simile a
quello mostrato sopra a destra.
Naturalmente quando lo
eseguiamo sotto la 3.x non
funziona.
#pprint1.py#Example of semi-useful functions
def TopOrBottom(character,width):# width is total width of returned linereturn '%s%s%s' % ('+',(character * (width-2)),'+')
def Fmt(val1,leftbit,val2,rightbit):# prints two values padded with spaces# val1 is thing to print on left, val2 is thing to print on right# leftbit is width of left portion, rightbit is width of right portionpart2 = '%.2f' % val2return '%s%s%s%s' % ('| ',val1.ljust(leftbit-2,' '),part2.rjust(rightbit-2,' '),'
|')
# Define the prices of each item item1 = 3.00item2 = 15.00# Now print everything out...print TopOrBottom('=',40)print Fmt('Item 1',30,item1,10)print Fmt('Item 2',30,item2,10)print TopOrBottom('-',40)print Fmt('Total',30,item1+item2,10)print TopOrBottom('=',40)
+======================================+| Item 1 3.00 || Item 2 15.00 |+--------------------------------------+| Total 18.00 |+======================================+Script terminated.
PROGRAMMARE IN PYTHON 0 PARTE 16
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 41/42
full circle magazine #42 1indice ^
File "pprint1.py", line 18print TopOrBottom('=',40)
SyntaxError: invalid syntax
Proveremo a lasciare che
l'applicazione di conversione lo
sistemi per noi. Per prima cosa
dovremmo creare una copia di
riserva dell'applicazione che saràconvertita. Io lo faccio creando una
copia del file e aggiungendo un
"v3" alla fine del nome:
cp pprint1.py pprint1v3.py
Vi sono molteplici modi di
eseguire l'applicazione. Il modo più
semplice è lasciare che
l'applicazione controlli il codice e ci
dica dove sono i problemi, il che
viene mostrato sotto a sinistra.
Notate che il codice sorgente
originale non è cambiato.
Dobbiamo usare il flag "0w" per
dirgli di scrivere sul file i
cambiamenti. Ciò è mostrato sotto
a destra.
Noterete anche che l'output è
identico. Questa volta, comunque, il
file sorgente (mostrato nella
pagina successiva) è cambiato in un
file "versione 3 compatibile".
Adesso il programma funziona
come dovrebbe sotto la versione
3.x. E, dato che era semplice,
funziona ancora anche sotto la
versione 2.x.
Passo adesso allaversione 3.x?
Molti dei problemi sono comuni
a qualunque cambiamento in un
linguaggio di programmazione. Icambiamenti di sintassi abbondano
ad ogni nuova versione. A volte
spuntano fuori dal nulla scorciatoie
come += o 0= e rendono la nostra
> 2to3 pprint1v3.pyRefactoringTool: Skipping implicit fixer: bufferRefactoringTool: Skipping implicit fixer: idiomsRefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_commaRefactoringTool: Refactored pprint1v3.py--- pprint1v3.py (original)+++ pprint1v3.py (refactored)@@ -15,9 +15,9 @@
item1 = 3.00item2 = 15.00# Now print everything out...
-print TopOrBottom('=',40)-print Fmt('Item 1',30,item1,10)-print Fmt('Item 2',30,item2,10)-print TopOrBottom('-',40)-print Fmt('Total',30,item1+item2,10)-print TopOrBottom('=',40)+print(TopOrBottom('=',40))+print(Fmt('Item 1',30,item1,10))+print(Fmt('Item 2',30,item2,10))+print(TopOrBottom('-',40))+print(Fmt('Total',30,item1+item2,10))+print(TopOrBottom('=',40))RefactoringTool: Files that need to be modified:RefactoringTool: pprint1v3.py
> 2to3 -w pprint1v3.pyRefactoringTool: Skipping implicit fixer: bufferRefactoringTool: Skipping implicit fixer: idiomsRefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_commaRefactoringTool: Refactored pprint1v3.py--- pprint1v3.py (original)+++ pprint1v3.py (refactored)@@ -15,9 +15,9 @@
item1 = 3.00item2 = 15.00# Now print everything out...
-print TopOrBottom('=',40)-print Fmt('Item 1',30,item1,10)-print Fmt('Item 2',30,item2,10)-print TopOrBottom('-',40)-print Fmt('Total',30,item1+item2,10)-print TopOrBottom('=',40)+print(TopOrBottom('=',40))+print(Fmt('Item 1',30,item1,10))+print(Fmt('Item 2',30,item2,10))+print(TopOrBottom('-',40))+print(Fmt('Total',30,item1+item2,10))+print(TopOrBottom('=',40))RefactoringTool: Files that were modified:RefactoringTool: pprint1v3.py
PROGRAMMARE IN PYTHON 0 PARTE 16
5/6/2018 FCM Speciale: Python, volume 2 - slidepdf.com
http://slidepdf.com/reader/full/fcm-speciale-python-volume-2 42/42
vita più facile, in effetti.
Quale è lo svantaggio del
migrare semplicemente alla
versione 3.x proprio adesso? Beh, ce
n'è un po'. Molti moduli di librerie
che abbiamo utilizzato non sono
disponibili per la versione 3 proprio
adesso. Cose come Mutegen, cheabbiamo utilizzato qualche articolo
fa, non sono proprio ancora
disponibili. Quantunque questo sia
un ostacolo, non richiede che
rinunciate completamente a Python
3.x.
Il mio suggerimento è di
cominciare ora a scrivere codice
utilizzando un'apposita sintassi 3.x.La versione 2.6 di Python supporta
quasi tutto ciò di cui avreste
bisogno per scrivere in modalità
3.x. In questo modo sarete pronti a
partire una volta che dovrete
cambiare alla 3.x. Se riuscite a
sopravvivere con la libreria di
moduli standard, continuate e fate
il salto. Se, d'altro canto, andate
oltre i limiti potreste volerattendere fino a che la libreria dei
moduli si aggiorna. E lo farà.
Sotto vi sono alcuni
collegamenti che ho pensato
potessero essere utili. Il primo è
alla pagina sull'impiego di 2to3. Il
secondo è un bignamino di 4 pagine
che ho scoperto essere un
riferimento molto buono. Il terzo è
a ciò che considero essere il miglior
libro sull'utilizzo di Python (questo
fino a che deciderò di scrivere il
mio).
Arrivederci alla prossima volta.
Collegamenti
Utilizzo di 2to3
http://docs.python.org/library/2to3
.html
Passare da Python 2 a Python 3
(un bignamino di 4 pagine)
http://ptqmedia.pearsoncmq.com/i
mprint_downloads/informit/promo
tions/python/python2python3.pdf
Dive into Python 3
http://diveintopython3.org
#pprint1.py#Example of semi-useful functions
def TopOrBottom(character,width):# width is total width of returned linereturn '%s%s%s' % ('+',(character * (width-2)),'+')
def Fmt(val1,leftbit,val2,rightbit):# prints two values padded with spaces# val1 is thing to print on left, val2 is thing to print on right
# leftbit is width of left portion, rightbit is width of right portionpart2 = '%.2f' % val2return '%s%s%s%s' % ('| ',val1.ljust(leftbit-2,' '),part2.rjust(rightbit-2,' '),'
|')# Define the prices of each item item1 = 3.00item2 = 15.00# Now print everything out...print(TopOrBottom('=',40))print(Fmt('Item 1',30,item1,10))print(Fmt('Item 2',30,item2,10))print(TopOrBottom('-',40))print(Fmt('Total',30,item1+item2,10))print(TopOrBottom('=',40))
Greg Walters è il proprietario dellaRainyDay Solutions, LLC, una societàdi consulenza in Aurora, Colorado eprogramma dal 1972. Ama cucinare,fare escursioni, ascoltare musica epassare il tempo con la sua famiglia.