0% found this document useful (0 votes)
110 views

The Python Book

Uploaded by

Gib Riu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
110 views

The Python Book

Uploaded by

Gib Riu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 182
| NEW) Everything you need to start coding with Python in Linux Python Book s OVER 2HOURS OF VIDEO TUTORIALS Learn to use Python Program games « Get creative with Pi Pron saninredby vesatle expansie iguagethat due tolssiiartyto every language suring) en tole even erinesperence progiammets hasseena hugeincresse in populaty since therelease andre cf the RasphenyPif uch Python she oil ecognsed programming language nthisreedtion cof TePython Book youl nd plenty of creatveproetstohelpyougettowpswith the combination ofyourRaspbery and Pyhonspowerfulfuncionaty pusits ‘of woviasthatfocusonFythonsefletvenss aay rom the tey computer Yel leamallabouthowtocode with Pythonromastanding tarwthourcomprehensive masercas then ont complete tz that ill consoateyoursis adh youbecomefluent inthe guage Youtleam how torake Python nerf you swith utorabioncoding wth Django Fas Pygame are ever more seul party farewerks Get ready to becomeatrueP then expert withthe wath ofinformation certained within these pagesandthe Fee video uttonon Fle, @ 4 L FUTURE 4 r age eval ete tue i Se he Aa A ee aR SR A 104 Make a Pac-Man-style game. TcpeparenneesRintint ier avers ee eee Cae) etre nary eu Laird Be ed coerce esr REY Peron urs " pace Essential knowledge for Python users Baap re aid ieatiaior eran 32 Code rock, paper, scissors De CE eu er) Eiteeeind in oo 7 Heke tT : MT aM yoo eon pa EO ere eee , Pex eng ea eee ial are fasneineentitee ees Es Adireeee teeny 74 Make extensions for Kodi le eet Laer ent 50 Create a graphical interface —_ : periment EO] forebrain Se Wee ed ‘ era tte od Sauer) ceric Ee reed ros iene ero 94 Copy: A cp to call your own Develop alight version of cpin Python 3 Cees nT Ceoee eon en SOON err | Perens tt meet Oecd Peed hrs ity Cu oy reach Puen) pee ann) Dea a) perecosse pets ues esc enero Ce eRe aory ore’ en ey ost) ee ay Dre noee rst eet Pat: Embed our hacks into toy relay Eat ete ee re Hello World Let's get stuck in, and what better way than with the programmer's best fiend, tho ‘Hello World’ application! Start by opening a terminal. Its curent working drectary will be your home directory. I's probably a ood idea to make a directory for the files well be creatingin this tutorial, rather than having them loose in your home directory. You can create a directory called Python using the command MKAHEVEHR. You'l then want to ‘change into that directory using the command @EVEHN. ‘The next step isto create an empty file using the command “tovch’ followed by the filename. Our expert used the command ‘The final and most important part of setting up the file is making it executable. This allows us to run ‘ode inside the helo_ word py ile. We do this withthe command Now that we have our Fie set up, We ‘ean go ahead and open it up in nano, or any text editor of your choice. Gedit is a great editor with syntax highlighting support that should be avatable on any distribution Youll be able to instal it using your package managerifyou don'thaveit already. Our ao rs prog very lon mtv ines. ‘The first line | 18 with a “shebang” (the symbol #! — also known ze hasan fled by te pat too Python intro pp eet Os ee at eee a Inet nea tbe nareted whips ume tis ron 6S elke perettncnoeetieneheast “nocache scl eae yan ertr ion a Sono ate pacd tefl Pole Word toto pe ‘uncon ty pucgitn sutolrmeday aterweve cles hogan eon Helo ers econ unaton marae Pate tta ted luc tré aon nlbe oe oe ieee cetera aera Siovperaemerten se cmon Stu oncoe dschangargaesjareciome fe a ame using te tay combination MED, lle y Enter Use CER Solerans You can run the Hello Wirld program by prefixing its filename with J ~ in this case youd type: Soounacatien comies coynocorotenes ‘0 The Python Book Variables and data types A variable sa are in ource code that is associated with an trea in memory that you can us to etore dat, which fe then alld upon toughou the code, The data ean be one of many types icudng decimal numbers eer) ‘As well as these main data types, there are sequence types, (technically, a stingis sequence type but isso commonly used we've classedit as amain datatype [A tuple would be used for something Uke a co-ordinate, Containing an x and y value stored as a single variable, whereas 4 lst is typically used to store larger collections. The data Stored in & tuple le immutable because you aren't able to ‘chango values of indvidval elements in a tuple. However, you eando soinalist, it will also be useful to know about Python's dictionary type. A dictionary is a mapped data type. It stores data in key-value pairs. This means that you access values stored in ‘the dictionary Using that value's corresponding key, which i different to how you would do it witha ist. In a ist, you would access an element of the list using that element's index (a ‘number representing the element's position inthe Uist) Let's work on a program we can use to demonstrate how to use variables and different data types. I's worth noting at this point that you don't always have to specify data types in Python. Feel Tree to create this file in any editor you tke. Everything wil work just fine as long as you remember to make thefile executable. We're going to call ours “A variable is a name in source code that is associated with an area in memory that you can use to store data” Integer ed lint seve ou 1 Nee Keniderneedtgoin ‘espe inlet cael dain way ‘ou coulda nate the {smetatitheoomng ay Werigh a eeates Noteenow weve signea the ‘ions balan tomate the ede {hoexiomaton mare shen ‘somnt aespont ie wth ‘epson SBtenfatha one ‘eerste eomdty enter Bebsnyvcanete | peint(hellost) Get started with Python Ml Wsinvew pps 4 We reat vaableby witing the name ofthe variable we want olowed Sivanenabasn uit tlie Uiraioon ert neste ‘olable For example De olloning ine cress avert aed + hate scoring he sting elo Ver helt =o Wor™ | helo int = 21 | elo. bot =e {el tuple=(21,32) | hell. ts = Helo hiss ‘Thislist now contains 5 strings. Notice that there are no spaces 4 between these strings so if you were to join them up to make a sentence # yould have toad a space between each element. helio ist= Hist hello listappend("Hello’) hello_listappend(this") hello listappendt is") hellolistappend(a") hello listappendist") # The frstline creates an empty list and the following lines use the append #function of thelist type to add elements to the list. Tis way of using a 4#istisrt really very useful when working with strings you know of in 4 advance, butt can be useful when working with dynamic data such as user # input. Ths lst wil overwrite the first list without any warning as we + are using the same variable name asthe previous ls. hello_dict= (first_name":"Liam “lastname” :"Fraser “eye colour’:"Blue"} # Let's access some elements inside our collections 4 Wiel start by changing the value ofthe last string in our hello ist and 4 add an exclamation mark to the end, The“ sting isthe Sth element #inthe lst. However, indexes in Python are zero-based, which means the # first element has an index of 0. Printihlloist) hello Hist} +=" # The above line isthe same as helo tists] =hello Ista] +" “Any text in a Python file that follows a # character will be ignored” feenae taupe sciauthedenensot hem Lets crste sentence using the ‘oud betes Pane Control structures In programing «contol structure any kind of statement that ‘canchange the path that he codo execution takes. For example, the program fa number was less than would look something he thi: ‘contol stuctue that decided toa ‘The path thatthe cade takes will dopend on the valve of ‘the integer ntconiton. Te code inthe“ block wil only be ‘enecuted if the condition is true. The import statement is used 1 los the Python syst brary; the latter peowdes the ext unction, allowing you to exit th program, preting en ear message. Note that indentation (inthis eae four spaces per indent) 16 used to lndeate which statement @ block of code olongato. “Wf stataments are prbebly the most commonly used conta structures, Other contol structures include ‘For statements, which allow you t0 ‘colectons, oF to repeat apace of cade oft: While” statements, Th moans any changes in astolows: 12 The Pthon Book print(strthello_tuple(0)) ff We cant change the value of those elr # Notice the use ofthe st function above to explicitly convert the integer # value inside the tuple toa string before printing it loop that continues wile the contin Wore going to write a program that accops user input from tho sorte demontrate how ontol structures work Ware caling Toop is using a local copy ofthe curant valu, which ‘the loop wont make any changes affoctng the ist. On the other hand however, the ‘while’ oop Is ‘rectly accassingelaments in the it, so youcouls chang heist ‘thre should youwantta doo. We walk about variable scope in ‘some moe detail lator on. The output rom the above program is print("(0} (1) has 2) eyestformat{hello_dict(first_name"), hello-dictlast name"), hello_dict'eye_colour') “The ‘for’ loop uses a local copy, so 3s lke we just did with thelist [' printthello_dict(‘first_name’] +**+ hello_dict("last_name"]+*has" + hhello_dict(eye_colour"|+" eyes") changes in the loop won't affect the list” ‘he enbarofteges we sonia | Asttostoethetge ‘hee aad koptrck Thon mang integer we vent rove Hane sbovesuecoude thant ‘nilocestto tint Tue By no he users given par eh ttindmaper ‘upto ete Sierbop “target int = ram_input(How many integers?) #Vust/binjenv python’ ##Wete going to write a program that will ask the user to input an arbitrary # numberof integers, tore them ina collection, and then demonstrate how the # collection would be used with various contro structures, Import sys # Used for the ysexit function f wheter hsp te reedo ty ancora tan rept levndyo celui thers ftsno Otters the pega wl teh | & ret nt itor nd cep Veron yee Yourt enter anbeper) ints = Hist) ) ‘count =0 ) # Keep asking for an integer until we have the required number ‘hile count < target_int: ‘new _int = raw_input("Please enter integer (0):"format{count +1)) except print"You must enter an integer”) # Only carry on if we have an integer. not, well loop again # Notice below |use ==; which is diferent from =. The single equals san ‘assignment operator whereas the double equalsis a comparison operator. tinea tue 4 ‘nsdn reer tothe colecton j -append{new_int) # Increment the count by 1 / count-+=1 Bint Using for loop’) for value in ints: Printstrivalue) MEGH MY) EEL’ The Python Book 13 ‘ovcandere aes ovaratoefyeuwant 41 Or with a while loop rint(‘Using while loop”) Sere rage 4 useful those tee total = lenCints) ‘hovealorara For count = @ while count < total print(str(intsCeount})) count += 1 Functions and variable scope Functions ar usd in programing to break processes dawn into smal ‘hunks This often mates code much easier tread. Fanctons ean alo be reusable if designed ina certain wa. Furcton can have variables passed to them Variables in Python are vay passed by value, which means that ‘copy af the vabie ig passed ta the function thts ony vain the scope ofthe unction Any changes maceto tha crgeal variable nie the function wil be cscarded. However, functions ean also retur values, 0 this fan Issue. Functions are defined with the heynard det, flowed by the rare of the function. ny veabea that canbe passed through are putin brackets folowing the function's name, Mute variables ere separate by ‘commas. The namee gven to the variables in these brackets ar the ones 4 Mie already have the total above, but knowing the Ler unction is very ‘that they wil have nthe seope of the function, regardase of what ‘the variable that's passed tothe furction i called. Lets se this inacton. ‘Thecutput fom the program opposites follows “Functions are used in programming to break processes down in” essen Bing ancien aoe Fave reduced the evel Findontaton jp [test_string Theteststringwort be thangedinthcode fincuti ns ‘Whe Python Book ‘L/use/bin/eny python3 # Below is a function called modify_string, which accepts a variable 4 that will be called original in the scope of the function. Anything 4 indented with 4 spaces under the function definition is in the 8 scope ef nodify_string(original) original +=" that has been modified.” At the moment, only the local copy of this string has been modified def modify_string.return(original): original += * that has been wodified.” # Honever, we can return our local copy to the caller. The function ¥ ends as’ soon as the return statement is used, regardless of where it fs in the function return original “This is a test string” | nodify_string(test_string) print(test_string) test string = modify_string_return(test string) print(test_string) 4 The function’s return value is stored in the variable test string # overwriting the original and therefore changing the value that is # printed ‘Scope isan important thing to get the hang of otherwise it can get you into some bad habits. Let's wite a quick program to demonstrat this fs ‘going to havea Boolean vac called con, which will deceit @numbor wil be assigned toa variaboin anf’ statorment. However, the variable hasnt beon defined anywhere apart fomin the scope ofthe statement. ells ff by trying print the varabe Inthe section of cade above, Python wil conver the integer toasting before printing it. However, t's elvaya a good ides to explctly convert things to atings - eapacialy when i comes to conestenatng stings ‘agether If you try 0 ube te + operator ona ting and an integer, there wil be an eer because i's not expletly clear what needs to happen ‘The + operator would usually add two ntegarstogathe. Having ea hat Pythons ting formatter that we demonstrated earl sa cleaner way of ‘ingthat. Can you athe probe? Var has only bean dened cope cof theif statment. This means that we get avery nasty ere when Wetry 'Fcontis sotto Tue then tho variable wl be reated and we can access it just fine. However, this is a bad way to do things. The correct way isto init the variable outsise ofthe scope ofthe statement “The variable vari defined ina wider spe than the statement, and ‘can bl be acooseedby theif statement, Ary changes mad tovar inside the “i statomant are changing the variable defined i the larger scope This oxampie doesnt really do anything useful apart from ilustrat the potenti problam, but the worst-case seenrihas gone fm the program ‘rating opening zero, Even that doesn thappenbacaue weve added ‘anentra construct to tet the vale far before printing Coding style ite worth faking tie total about coins. snp to mito {iy code The byw Coney, For eae yu shuld are sue Yourratos ithe ser man ower matorf yeu wa oor ‘Einteet or su unecre tebe. Ove eu hing tow Setedccunanng tertirs for vorabe. Yu sour’ he t gre stctyiosathan en hata variable does. The other ting that goes wth tis isto always omment your code. This wi help anyone eae who reads your code, fad yourset nthe futures aloo useful to put a rit summary ‘thetopofacode file describing what the appatin does, ora partat ‘the appleationifits made up of multiples ‘Summary ‘isartleshuidhaenseduesyouto th bao programing inPython Hope you se pting aed othe yt, detston td gener! ok and fel of Python pega. Te Nest ep telean ow come up wth apebe tht you want ase and reo dou ssa eno stp ht you can npn programing ngage Googe oray ther such engin. vey hall fyou ae stk win anyon. ech an oer message you eat woke hon 9 ‘i te Googe ado staid be acer nology proto For example, ne Googly mp fie with yo re Frat i toast «Stack Oreo trend wth burch of sf ‘eps, Dont be aastogt suckin therel fot soaring ‘sire pretoneone mangmiochinket tire Happy programing! 4 - | ESSENTIAL maine). COMMANDS mw Std ee ee OLS oie erecheir ier ire dense language, with lots of modules capable of doing. almost anything. Here, we will lookat the core Peconic ccc rea ene) needs to know aa Importing modules The svength of Pere ay 0 be cetnded trough nodes, The fe stp may frogara to rnp these odie tha au nesd. The pls nga tenet fo tcl ing tredlerane. the casa, those tcton ond chet pronad ar ot nth gener narespac. Yow need to call than wing be covets name {dena metodnare) You can arin the ‘noddename’ prt wih the comand "grt treerame aa. et You can a the ese comply wih the command "ror maianame impart toimert everything rom the given edule, Thenyeucan al these proved capabilties rect, Iryeu ony rood few of tho provided toms, you can import them scaly ty ret meted aretjectnames th the ree cry le most ofthe creeds we ae lokng a er Pyton commands st pd/pypipytbonorg nt te. Youray need adrian 18a Python session there re few essntal cutie of Pythen. The fist of tose s Bp. amedule riches dovroatingthe sourcecode andcompingaryrched code Lucky hreisarapcataryehundedsafPytren ecules alte ot dangeverirg manual youcan tal new edie usngthe command jp real meoora ‘sod a dependency chackand instal ary misirg mod tbl lraryforyeur computer On Lux machine, you woud pammand wth suo. Others you cen insta rectoryoyadrgthecommand nection use “Every programming language out there has a core set of functionality that everyone should know in order to get useful work done. Python is no different” Executinga script imoring a mcd doesn the age thn he mode eb ees taught treule msteance code win fe Pyton tngoe, he martenance code ala cela th tung ielng code you ony wah tae 0 Python sp and cnt the rn code twin te eure ssn, you ean se th ‘ecfle ienamapyT command, wears the train optonsa stingconaningte Python fle {lead and cut 8 dete y cir tre lade io the lala and gba ofthe current ezeson, You can opal nce {wo onva parametrs th encfla comand. “here tno options are bot dtorares, one feraciteret setae andere st oF bse you oy hand none tony fs Sesurad boa bale esa The etn >> jon of 50 gems to make your Python rememeerthatPytron alastabsveryserusly ~saifyouarereciengaryerorthatrenons tbs, corectthetabenacre 03 Dynamic typing ih da, Cer, and other statically, yeed Ierguagee, you ust epocty tho data typo of the faction retum value and ach function sgunent. Python is a dynamically typed Torg.age, you paver have t ext spect the dota ype of anything Baced on what value you assign Pon wl keep tack ofthe data ‘opener O04 Python statements fytton tste carage route, 1 saps depute code Hoda Most of the conded proginglreagts shes Cerdcr ae semcotre to separ statements on ety tral sepurntecodebote 05 ==and = operators Fyn vase == for conparson and = fr szolpment.co hae recur ecdertly {eoenre te ve wen you atily war 0 camper 06 Concatenating strings Yoon eet eerie orp D> printny'¥ thon) python 07 The_init_ method Te _at_matidisnneneomes ance ccisintartated Trerathdivaeht {Ddoay/intazstonyounarttodowthyor Shoat The nt rathodeoniognete ortucernr.osoroe Example: ‘lass Person! de init__(self, mane): selfsrane = nae ef saytiselt): rint(Hello, my nane is", self, ane) b= Person("Thego") past [-/sre/pythen 8:3 python initmethod.py Hello, ay nae 1s Taege 08 Modules To top your roars ranagiobe 08 Thy gown sz you nay wartwbreaxte pio Sora fies Ptr lw you tp rile frcten dintons ina a e and we thm be'e medi tat can be tmpored io other sci and poguia, Tae le mutha 8 edraon 4 file my_function.py ‘def miomax(a,b): face sin, max = 3, © flee: fin, max =, a Wodule Usage inport my_function 09 Module definednames Example: Te bain function ‘id! can be used 10 fad cut whch names @ madde defines. ets a fortotot ergs. >>> import time >>> dirttiea)| Coe ry function. minmax(25, 6.3) “Tocatine’s kt csurfting, sorpeie’, Si ie ire Module internal 10 documentation jou con eo banal auras nila) of 8 module name by lokng a >>> Inport time >>> print( time, clock. —doc__) clock() > Flosting point nunber Ths oxamglerexus the CPU tie oral tine sinc the tt ofthe process o ince the Fest to cock. Tishas a5 much pression ashe systemescords Passing arguments 11 toal cri Fyn lt yu acne win Fe pod oascpttiacargh he omar ieonurtiesoedntwoeaeris Stoort prine(sysare0 Loading modules or 12 commends at startup You cin ead predefined modules of commands at the startup of any Python ferigt by vara the enviorment verse SSPVTHONSTARTUP You ean ast endronant rable $2YTHONSTARTUP to fla whch Contains the istuctens lead necessary reds orcommands, Converting astri 18 todateobect nuee te funtion Datel’ te convert ngtoadateot fron DateTine import DateTine a ‘dateob = DateTine(string) Converting alist 14 toastringtor di Yeu can comer alst sng in ater oe ‘longo Siylist = Cena D>> print, * JoinGeylist)) Son, han, C682 bop print(“\n? Join(aylist)) Tab completion 15 1on interpreter You can adie ao compen ie Pon verter by eddrg tee tes 0 er oxtre il bryour fier Pyton ores oh peti ingore rlcmleter, reaitine rendi prse a ind: caplet’) ‘Reval rae Pye cpl preyed ficten ted and arable rates wa ou presse Python 16 documentation toot ou can pop 8 genta tens ‘nacre Pton oreo ang 8 pydoe - torn nerd biortkpsclagtor tito wa Python 17 documentation server ioscan sat ot HTP sera he gen pot on teas arhre Ts reveo ence rg acount a Python meron ‘oud ry modi soon, Sree Python development 18 software Tae ae nt 2 a a wh PTH seatenent Hvaatoteramores TBE The Python tuittin IDE, with utocompetion, function senate pone hap, rata ostng ‘nother enhances Python shet with tab-completenandetherFestres, '2.GUl Pron IDE with sutocompleton, ass one bult-nahel anddebuege WHREDE: Conercia Pytnon De wth free leerce seiable 10 open-seuce r | developers everyahor ‘The Python Book 27 Buitt-in modules 19 Frterpreterterginaton ef sunt) print (as) ef message) rint(“xecut ing Now") Import atexit atexit.register(sum) ‘texit register (message) Executing Now : Converting from integer to binary, 20 hexadecimal and octal seb hed ardocttoconer from reget ‘ran decimalandctalfermatrespecvely >>> bin(24) ‘ab11009" >>> hex(24) “exis? >>> oct(24) “20” Converting ai 21 charsettto' {buon vate Bloneg hncion homey Grosetwutr dats decod(“Snout_charset_here) Seoaecutt) Removing 22 duplicates from lists Fos wart vero dufsas For 0 Wt [isp evry amare ait a a oy Sor ‘rel wt ronan then check. from operator import setiten oof distinct) a0 mapceetiter, (4,)¢2en(1), 1, (2) return d.keysO 28 The Python Book 23 Do-w ‘Sroe Python has ro dowhle o d-al oop crrctnets Got, you can use the flowing wile True: o_something() SF eondstiond): break ‘excite pater specie Kineton ee seul detoc tho pateronwhionthePython Inerpator suring You can uses plato rofecauttocrnt platform, >>> import ys o> sys.platform nwa" ‘OnMacOSXSnow Leopard 53> iaport ye >>> sys.platform ‘carwin’ Disabling and enablin 25 collection tt ou tay wat erabe © as fags colertor at runtime, You can the meaule to erable or dable the >>> import ge d>> gevenable builtin Function enable> >>> ge.disable ‘>> import re b> s= *Munal is a bad boy” >>> if re.search("K", 5): print Snatch!" # char Literal fate! >>> If re.search(“T@t-20", 5): print “Hatch!” # char class 4 match either at-sign or capital letter, hatent >o> If re.search("\a", 5): print Hatch” # digits class Working with bzip2 (bz2) compression 33 format ‘ou can use the mode Bd to read and wre data usirgthob2e2compreston alert. bzz.compress() : For bz2 compression bz2.deconpress() + For bx2 decompression File: br2-exaeple.py ingort. 22 MESSAGE = “Kunal 1s a bad boy" conpressed message = bz2. compress (HESSAGE) fdeconpressed message = b22 decompress (compressed message) print “original:”, repr WESSAGE) Print ‘compressed’ nessage:”, Fepr compressed _nessage) print “deconpressed message.” Fepr decompressed.nessage) [-/sre/python $:1 python be2= exanple.py original: ‘Kunal is a bad boy’ compressed message: “BZHSLAYESY\xc#\ HOFO\x98 x00 \x00\x02\x15\x900\400\ xO\R084E\xB | \xGO" ABO \HBC\x88\" n03¢\xa2\xb0\xd\xa5\xb3VK1 91400 af 8\xbb x92) \xc 24x86 2<\xct econpressed message: “Kunal is 3 bad boy" UsingSQLite database 34 with Python eee ee wparareaiad deeurbemuseatecoceepaia sciaiadapetrianclpetreca'ta ConusePoreuiccqned now ovorath Sturceaene 53> import sqlite? >>> conection = salite.connect( ‘test. oe) 55> curs = connection. cursor() o> curs.exccute(*""ereate table item (ia integer primary key, teen0 text unig, semcode text, deser text, price realy") ‘qited.Cursor object at exiee4az53e> 35 Working with zip files ‘xeaonthmodte se tro metas HinFile,2ipileFlenae C, ode C, ‘compression (,allowzipes]})) Soma flgforote floc sot Zipfile, close Geant ara i oust cl ne oe tstngyow peo or cota rt tomrtion Hifi extract(enbert, patht, am) Eevee menterfontteachieothe caret worrgareroynembe mtb fe Gra aio eee), att spats a dee flonan ora poche dete paso raat Using UNIX-st wildeards to ech 36 for filenames You ean uae the module ‘ot fred al te patnares matching a pattern accocing to the ful used by the UNK shel 7 ae character ‘argos expressed with] wllbe matched >>> import eb >>> glob. glob(*./[0-91.+") CaAgif?, |. /2.txt'7 >>> glob. glob(' gi") [Lgit", ‘card. gif") de> glob g10('7.6i"") bigied a Performing basic file operations (copy, 37 delete and rename) Yesconun the rash pros Ds flo oprtin a ight Ts dl ore vt your og fas an ol not wrath {onus fies ba named pes ockdeoes a hutscopyare, dst) Copestetio rts or Sect et shuts. copynde(sre, dst) Coplsteflspermistons tom std Shueil move (ere, ds) htt scopytree(ere, dst, symlinks Etgorel Fecurveycopenntre ects shutilsrmtree(path Cy nore errors E, onerrordD Date orev dry. Executing UNIX commands from 38 Tie not avalable in Pybon’ ~ watead you ects themoc'svoprooess! >>> import comands >>> comands getoutput( 1s") bz2-exanple py\ntest py" Reading environment 39 Vanables ‘Youcan use the modu oie ether opeang system soatiinermation: >>> import os 53> os.path 9>> os.environ {'LANG: en IN’, “TERI. ‘xterscolor’, ‘SHELL’ “Pein/oash’, *LESSCLOSE" “fusr/bin/Lesspipe Xs 5", X06_SESSTON_COOKTE” 254644597¢79 1c TOAESES430 S606 1257673132. 347986-1177792225", SHLML?: 1", *SSHLTIV": “deur pts/2?, ‘PwD': */hone/kunal”, LESSOBEN': «| usr/bin Lesspipe > “posix >>> 08. Linesep in zz The Python Book 29 4O Sendingemail Yeu can use the module mpi to sad erat Using an SMTP Gee Ma Transfer Prtoet csentitrtce sntplib.suTP(Chost [, port) import smtplib ‘se your om to ond From email adress fromade = *fromogual. com toaddr's. = *todguail.com” sg = ‘I am 2 Python geek. Here is the proof!” credentials # Use your oun credentials and enable ‘less secure apps’ in Gnail “frontgnail con! 4 The actual mail send server = smtplib.sMTP(‘sntp.gxail. com: 587°) # Google ail uses secure Connection for SHIP connections server.starttlsO) server login(usernane, password) server. sendnail (Fronader, toadérs, 8) server. quit Accessing 41 FiPserver st a fly fas clan FTP me or Paihon Tela on FP cmon, ou Chrsetetlourghneton feplib.FTPCGhost C, user C, passud Tyscet fy timeout 33) host = “ftp. redhat.con” Username = "anonynaus” password = “[email protected]” nore ftplsb import urilibe Fep_sery = ftplib, FiP(host username, passvord) # Download the file = urllib2.urlepen ¢=Ftp:// Ftp.redhat.con/pub/redhat/Linx/ READHE”) # Print the file contents print (u.read(>) 5 python Ftpelient.py 30 The Pchon Book Ober versknacffed Hat inate been mane ftp:/farchive.download.redhat.com/pub/ redhat Launching a wel with the defautt wel 42 browser The wekbrowser mec OAS & Oonsiere way 10 launch webpages using the deeut web brooee >>> import webbrowser >>> webbrowser. open(‘http://g0ogle. co.uk) True Creatingsecure 43 hashes Tre Tash ree Ss Bao a secon gyn >>> taport hashlib # shat Digest >>> hashlib, shal (MIG Classified {nforsation 007") hexdigest() ‘ex24b1543"229ec0eb935a1689593 sahatb20ces # sha224 Digest >>> hashlib.shaz24(°MI6 Classified Infornation 007") hexdigest() +b 162F741000602240844824905=9%7097 Tasabaeaa0eab355e2<0" #sna25é Digest >>> hashlib-sha256(°NIS Classified Infornation 087") hexdigest() * 265733" 7R672FCb3972599189 bass0707ebFtcE403e fab 3201c19825e" # sna3b Digest >>> hashlib-shaab4(°NI6 Classified Infornation 007") hexdigestO *Sc4914160"02dfidi9e14d3ecle7Abb09 ‘de192edc138a9"768200098248864006 ‘se0esFe383465¢8063595724" 4 shaSI2 Digest o> hashlib. sha5l2(ME6 Classified Inforsation 007") hexdigest() *aTOsaeiebe58234578482831659629825. 2e4224h4973#496850222edec04250099077 oea87oo4See4f 8018566140667 Fbat7 SaldelfF192Febe71362" F Ws Digest >>> hashlib.i5(-MI6 Classified Inforsation 097"). hexdigest() *Be2F1e52ac146F109990670082647125" Seeding random 44 numbers “ean use the mela Tandon sera 2 ide writ of random rumor The mast tod one is tondomaceaba! fe intlons the bac random number gineaton cmt or Nere, rer yet tne ns caer system ines aso eed ois the fonostoraton tne nodes pete Working with CSV (comma-se} 45 values) files Sins te vryppr fo cainochargowe thee Usng the module ycucanreadand veto Fe5 import csv Awrite stocks date as come- separated valves weiter = esvanriter open stocks sv", wb", buffering=0)) weter wel terows(E Coons", “Google, Ine. 585.24, 0.47, 2.99), (CWNRD", “Wahoo! Toe. 27.38, 6.33, 1.22), COET, “OET Networks, Inc.', 8.62, 0.13, “1.49) D ¥ read stocks data, print status essages Stocks = csv. reader (open( ‘stocks. a) statis labels “unchanged”, 1 status. labelsfewp¢Float¢change), 0.09) print ("ts is %5 (3sR3)" % (nane, status, pet) Installing thir modulog using tu 46 tools “etuptoolss a Python package whi letsyou donricad, bua, instal, upgace aed uninstall packagesvry oily. You can install thd party mockes using the Pi package marager Use the command ‘sudo aptntal pthond-op tinal Pp and sua yourself of tsvoluminausrepostones 5 pip install. simplejson Collecting simplejson Downloading sinblejson-3,17.6-cp310- ep3l0-anyl nur 2_5.286_64.nanylinuxd. 86.64, manylirin_2_ 12.86.64, ‘many inn 2010_386.64 whl C378) Installing collected packages: simplejson Successfully installed Simplejson-3.17-6 Processing dependencies for simplejson Finished processing dependencies for simplejson 47 Logging messages to the systemd journal Scan oe the moda ‘jog to wit The torr a The uch cig progens trersoranytingesoyoirsrogam met. hooters so no UNK tong tray ovine Met Gate Creepin jour agg eves he nts entoteltent aurlets fre carer inport syslog. syslog.syslog(‘myneekapp: started ogsig’) for a in ('3", *b', *e'3 b= ‘aygeekapp: 1 found the letter syslog.syslog(o) syslog.syslog('mygeskapp: the script goes to Sleep now, bye,bye!") output: 8 python mylog.py 8 jouraletl -b -e Nov 8 17:22:34 ubuntu pythent31169): smygeekarp: started logging Noy 17:22:34 ubuntu pythent31169) ‘mygeckapp: I found the letter 2 Nov 8 17:22:34 ubuntu pythent31168) snygeekarp: T found the letter b Nov 8 17:22:34 ubuntu pythent31168) tnygeekapp: I found the letter Nov 8 17:22:34 ubuntu pythenC31168): ‘aygeekapp: the script goes to sleep row, bye, bye! a Third-party modules Converting HTML 48 documents to PDF "POR sa vey poper mode FOF teneaton tom Python eanendera OF fom ee ete suo pip install (ollecting python-paf Downloasing pythen.piF-.3-py36-none= any.whl (16.818) Installing collected packages: python vif Successfully installed python-paf-0.99 Example: >>> Inport pdt o> pd = pd generate pif 'chDothis is an heal. string’) FF open File for writing in binary node >>> with epen(test-doc. pif", "w") af ‘write out POF >>> Faveite(pa) ‘The gonerate_oof function cn take a whole lot of optional arguments, cove everyting from OF and quality stings to margin sis See. the documentation at Mtpeypior/ projector more information, Under tho heed Py uses he whtritopdt brary to-do the conversion. And f yu want you ean pase any of the more exe options for that Boar to Pyst to. One prebam with ‘wanton speed, Kean oly generate one document per process, so if yu ave ats of ‘documents they are generated one by oe, each ina soparato process which takes tina to start, To work arund this, possible to use synchronous VO to spawn rutile processes ndparalele POF ouput The Py recuishas 2 class eyrePy fr handling this use case ‘sin, 220 the documentation for mare tals nth, 49 Using Twitter API Su ean comet ote ung the Prior Tht ree Sit clone giti//thb.comboar/ python-twitter 5 cd python-twitter § ke dew >o> import twitter 1 Use you oan twitter account here o> mba = twitter. AolCconsuner— Keyes CONST _SCret=, E858 token ye... acces_token_ secret. p> friends = nyt. GetFriends() >> print Cu.nane for u in friends] [u'Mate Legend Gemel1’, "ono wells, u'The HON Big Blog’, nish Wanda’, Utisnay, IndlnideoGaner con! UrFaketaron Hiegass’, u"haostade! Urnileste’, u'Frank Jemings",.."1 Neto that in order to uae met features of Pytnan-tter youll needa generat an Access “Token and AP ey for your twtr acco. You Find instructions for dong this at https. ‘witteraomioa.thiovervewapplaton omer sccese tokens. Th il gue you the 4 mage rumbarsfor twtr Fetching the latest news ‘Youcan ute a rapper forthe Ntpsrensaniorg env to got headins eva om Pythons ‘nth te attr marke above, yo edt st Upan 221 before tl werk Se psp. arglreectnens-pythanfor mare formation, S pip install newepython ‘Example: Ingortnews_pythen ons = news_python, Global (key=9PI-KEN") rens_content = nes. Bet. rens(querye"inue, soureecan") print(P-Title: (sons contont.tithe)\n" FARL: (rens_contant.ur1\n" Fexuther: (nenscontant. author") The Python Book 31 ‘Allon the Python scrigt ‘toruninaterminl, and outside the DE Human inputinthe form ofintogers i sed or comparing moves and, timate, playing the game Use deductionto determine ane of tree outcomes Loop the code over againandstart fromthe begining Append tointoger varibles keep wack ‘of scoresand more Codea game of rock, paper, scissors Learn how to do some basic Python coding by following our breakdown of a simple rock, paper, scissors game ‘his tutorial wil guide you though making 12 rock, paper, scssors game in Python. The rough to adapt and expand as you see ft adding rls nd eels a rasmentaryAl you nish, Resources emer acty Python Python 3: wornpythenarolont com IDLE: pytencryie re usedin 32 The Python Book funesonswetineestorthecode—the stl pats of the stander Python irae ust rotparto! he defeutenirnment Python essentials Ml t—{itess: cise he veo cand 02 Tentinie eis ors on sed here Thetheevarables weve using ‘hel restionshp is defined We ao grove 8 \arebasonecankeepsoxeoftnegames 03 werner eb) ete stertofaschround,Taendafeach psy ssi comes beck trough he, whether we wanetoplayagsinornet 04 rer et send ate hare. ashngfor the player input ting ‘he computor nput and pass hase ono gat ‘horosuts Atheendof tra trenasks yous We topiay again OB Fo Gets def Go Be playr information on ho play th aricular version of the gare and than aon thei choice tobe ued nthe net step. We 0 have seething in pce in eae they exer an Imvaisoption hae ae fen ths gong wren we shaw the rests Fat wate puringling olay sidsome enson, sppendnga\arable to some rad tent, and then comparing what the player and computer did Trough an if statment, we choose whet outome t pri, andhowtoupsatethescores 06 eres araenanne | 0 ‘We now ask for text input on whether or or ot someone wants to play asin, Depercingentharrespens, we gobackothe star orendthe gameandsplaythe resus The Python Book 33 BA Python essentials The breakdown O11 Vormesesetmintrezaniote (2 Wsteinnrinetnomtramaaionn (J vin snttntens now especie Python interpreter here.This allow top ofthe standard Fytnon code so umber so that once a selection is Us to run the program insige a terminal of we can use some extra functons throughaut madeby the player dung the game, wll be ‘therwise outside of a Python-speciic IDE the code. Well use the random module to equated to that specifi variable. This makes Tike OLE. Nete that wete aso using Pyton 3. determinewhatmovethacomputerwilthraw, the code alight easier later an, as wo went rather than Python 2fer this particular sogt, andthe time mule to pause therunningof need to parse ary text for tis particular ‘whi needs to be specified In the cade tothe code at kay points. The time modula can function fyouso wish, joucanaddadltional make sure calls upon the correct version also be used toutiise datesand times, ether moves. and this start here fromthesystem. todisplay thom orotherwise &, 7usr/bin/env python3 | # Linux User & Developer presents @ “import random’ import time Rock, Paper, Scissors: The video Gand ‘rock = 1 paper = 2 scissors = 3 "names = ( rock: "Rock", paper: "Paper", scissors: "Sclssors™ rules = ( rock: scissors, paper: rock, scissors: paper }) G player_score = 0 computer_score ~ 0 OG terveszectrnertn tr neane. (sii e tae amen ot (GS Yr sna isco arate at and the text represortatiers of each thevaiblosaredefinedarcusedeny can be used througout the code t2 rmovefortherest ofthe code Won cal upon, when needed, ho ules are done nexchanay keep trac of scores We ned to tart at ro urscrigtwilpintthonamesofanyafthotyes that when comparingte esuts, ourvarables row that k ess, cherie fe dined rmavee,mainytotaltheplayerhowthecomputer are morrantarly modified Further donn inthe it ina function, would only eit inside that ‘moved. These nares are ony equated these code wel explain prepay what’ happening. function. The code ads a pint tothe computer Norabls whon they ore needed = this wey. tre but Daslealy after determing whether of orpaverdependingonthe outoome atheroun, hurr ssgad%o acho! thom smartsned not theresa te, wel sow ifthe computars although we have no scrng fr ted games in Uo’ reedod move wou hve lst othe player move. the this particular veson ‘computer move equals the losing trow tthe Playersmove youwn, Enns hare ar other modules you can import wth base Python. Same of tha mejor ones are ‘shown tothe right There ae alse many more that arncludadas stander with Python, 34 Te Python Book 7 tacresiretesetatceingc bcos. wth tetinctn weve calld ‘tarts qu cimpe printing ox gesting tho Player and tren starting whio loop tat wl lw usto keep plyngthe fame asmanytimesasine wish, The pass staterent allows te whoop tDstoponcewe\e finshed, andcouidbe eedtoperformarumbercfather tasksifsowished fed top lay the game the scorefunctonisthen ‘led upon wel gover natok does when we gto jef start 0: while game ( pass scores() jase game () player = move() computer = random.randint (1, 3) result (player, computer) return play_again() print ("Let's play a game of Rock, -ython essentials ll 8 ssetz nme entry srt ean akon ach stpatiteresaaiyntho code. Thisiscalled upentrom the startfunetion and fie of al tering the payer move ty calingupon the move funtion teow Once that's sorte sats the computer move ses the randem mode's rangi funetion to get an integer betioon one ‘and tre (3. then pases the player and computor move, stored as Integer, onto the rest uncon which ne seta fate outcome. Paper, Scissors.") jet move (): while True: print) 13 Ey? player ~ int (player) if player in (1,2,3): return player except ValueError pass print ("oops! [GAR Seb Dab_Gpans Wdors ee (eee 4.9.2) on tinue? . fates moves 3 ye = raw_input ("Rock = 1\nPay I didn't understand that. z= 2\nscissors = 3\nMake a move: |") Please enter 1, 2 or 3.") We start the move function of by puting it into thle lop. The whole pont of mene ito obtain ‘an inter batweon one and thee frm the payer, so the ‘whl oop allan us to acount fer the payer making an Unsupperted entry Net, weare setig the player variable te be created fem the playersinput wih ran_ipput Neve alsoprntod nstuction tart togoaonguithit The" weve Used the en ace a in break this way, he structions appear asalist. 1O tascam se onan wo ode nd ardleerorsorather exceptions We pareenhat the player ontorod by tuingitino an etoger using it Neuse ‘het statement to chock titisater 2,03 iti, move retums th valve Bsc upto the game ction Ito upavalueErar veuseencepttoda noting pits ener ‘reaeage andthe wha oop starts agai. The wil appen wilatptaneteae The Python Book 38 salty eure ends le. keearnnacanoe odd WeelanTancnipamsinoncous fen Sumas sesor nee ans 1] temecrenuarnerain hicontcnvaonan nara Dow rors temas , sivnecethaneunparrcnpretuere “iD Red ast we enous tow cleans siyrettoarrsntinnconuei ine DW rieccrgimannemane 1 wt cot: ary e gat cen Suinactlnhergocanom P80 sans yee ie marge esr eb So cht dl ie print nbon ov seo Mt woh pou are con. cet fw rte peta aha weedieoraninieptondatneresi Uedrmetareacliwninginces'® wariicnineetoeaarsoe result (plas print ("1 tine. sleep (2) print ("2 if roles{player] == computer: print (*Your victory has been assure: player_score += 1 By) Print ("The computer laughs as you realise you have been defeated.") computer_score t= 1 1G Meteo esis rt basicaly trougva process ofeiation (ur fest onc to oe the move th payer and coreuto used wor the same, whichis the ‘npost part We putin an tara 2 that ifs tv, is parentar soto fhe cos ends tere then prtscurtimessng andenes back tothe gametinctentorthenent ston. AB tiinsasesrenmsatcocneci ‘eitoodd tl be awin or aloo. thin the eae, we start ancher# etatement. Hare we use the res lst fom eae to aoe losing move fo the payers move isthe same asthe computor’ Fras the case. we pit the message saying 29, and add oro to te ayer scorevarabetrom betes 1G teen isco team tsi We print the losing massage, ge the computer a point and it mediate ends the readttuncton tuning thogara function 36 The Python Book | V iertorob baled a clay agin furcton. Lie the moe function, we how hanan np akg the player ray woud ikea lay gan visa tt message thea input th the serpy sugpeston ration! tocotanexpected espone ‘def play_again() 1G Sicgeesencvionctyntoveroe shoud expect a reaper in kd. The iFetatement cvacks to ee any of our defines postveresponsashaebee antered.ASFython oesitdifferentato bebwoon upper or lower ase, eve mado sure that tacoptsbthy ae ‘athisithe ca, returns a postive roeporee ‘ogame, whihallstrttagae 19 trriztenenwcensnaznsene villassume the ayer doesnot ant to play again, Wel print goodbye massage, and that wierd ti feton, The wil aso cause the game funesontomove etotherert ection sedate global player_score, print "HIGH SCORES" print "Player: *, play computer_score yer_score Print "Computer: ", computer_score Gis noe — pin start 0) LS [Be Seinen non He FFalsotastheEUF(alseif operator. whichcan bo used in place of he soca I statment we employed ts usualy used to koop code ‘ear, bu performs the sane function 20 sereeace te sa ncn ater imefinshes we moveontotheresuts ‘hissecton cls tho scree, hich aries, andthenprnsthemindivcualysferthe names ofthe players, This etheendof the sort a far as tho player is concered. Curette code wort prranorty ave ts coos, but you can rave Pytonrtatetoa ietobaop fyoumien QD Bet zr ton esi wo be used in two ways. Firstly, we can frteuto in th command tne ard Rl work fine. Secondly, we can impor this nto anther Python srt eras ifsou wanted to additas game toa oalecton. The way.twont execute ‘Mecodeuhanbairgieorted Tre Python Book 37° theyre sul parts of tho standard Pon rae, just rt pat f the Code listing Wereagan providing arate swe : an ke sare afte ara playes, pane ‘ndheyreundated each on (ur ery basic phi imo AS trot the gue’ stoges, ped out seroerytum Programa game — of Hangman Learn how to do some more Python coding by following our breakdown of a simple Hangman game ne ofthe best waystogettolnow Pthonla than rock paper-siesrs. Wepre bybuling lots of simple projects so you ean arcund vith a lot more variables this te, undorstanda bt morsabout the programming, Hovover. wore stil loking language. This time round, wete locking st random selections and human Hangman, a mutiround game rayne on it i nd whoops and dealing wth tinge of tt Resources Python 3: wwm.pytoncr/donioas IDLEtwanpytonorgtise 138 The Python Book ‘The actual ame starts here with whl opto ‘et you continually play the game until you decide rt: Code listing conti thernonthenendingtoprogram Site gee 7 * oe ern mo Ee» tutte Linens} ‘The game rule te decldes here, a8 wel a the wer Seictnes setup forthe word and keeping ack of es an Te iet slenoord ach round ofthe gaa i played here, aing for SST cept sare, laerscre ninput.tentelingyouifyouwerecorector not ie tare rng re) sd Cea 1 [Ron out the raphicandchangsany erates Stormer eed) ‘at ree tobe upeated espetalycerrect ae 1 itedeeret tte ah, —oeert| = Sa ras oa Aurenche ever! Ten Sry ee (Stoo: vamicondon inept goss areas Sra Sitnannercbes pater sacs rims wether) nerd on) Pine el Frinton letters trie) The human input forthe game takos the lotr and tun into somthing the cade can wae. ‘eid nthe previous Blok of ede ar then ‘efered beckta you've entered an uteuppotes raoasy used character ‘he sume class last ne, whl allows you to snloctwhetherorntyou wie 0 pay again pene? ‘pon auiting the game, scores ae ge fo the duretonaf play escon Wealssenatnesergt withthe nama codethabeore FP See Ie ty tom rink you ery mc fo pre cr ge, Sen yu et i") IDLEautomatialy gente cadeto SAE pha sre, come sre ‘ake eatngyour werkt tl it eas. a alesis youtnetange these obars and Brim Cer! Soe er) hglrengin LES Preference, case ape youre colour bling oraejust ved taciferent jo ‘ooursenems ingenra | Tre Python Book 39) Ise ASCII Here's aclse-upofthe seven ‘sages weve veaor ang’ tephiesYoucan change there Youre butyouneadto make Sethe quotomarksareatio ‘hecorctplaceso that heart ‘sconsderedatertetrngta be riedout. ‘40 The Python Book | Gf Husrrbin/env python3 fron random import + player_score = @ ‘computer_score = @ def hangedman(hangman): graphic = [ + | | I i I start0; Gor while game(): pass scores() 011 si 2zen ovens eno tw ot to the Pythen interrater This allows ut 10 runthe pcg sie trina or otherwise cutside (of Python-speie IDE ike IDLE, Note thot se so using Python 3 for thie partessar erg, a 2 ‘etaled by default on rot Lux systems and i therefore enaure compat, 2 singin rrr me ty ierenty ths time, importing the act amas ofthe functions fom random athe than ust ‘he mock se. This allona ust use the furctens without having. syntax Uke random functor. The fasteisk imparts al the functons trom random. titheugh you can swich that for specific ramos of {any of randoms functions Wl be sig the random ‘ction oselact worsforthelayerts gute, 3 vert tis cess ratio tcan be used throughout the code to hep track of scores, Ve naed to start fa zero now 20 that t ‘xaterothewise we defneditina function, woud print(‘Let’s play a game of Linux Hangman.” ‘Athoug nevemovedsomecttherulesto ‘he gu function, yucan way putthon backhereand call upon tho sing tele vrata ese wl with the ssre. For ‘hewerds yosrauldalzrestes separate ‘ie andimport em the herandor mule Cnty entire that funtion, Te code ads point tothe computer o player depending on te outcome ofthe ound OG roe 23s cont eno SOI hanging man stages. Were storng ‘ese na functions sto separate sting abects soe can call upon thm by passngon the ramberof ‘noorect guosoes toi. There are aven graphics nal. Wein the pn-and.paper versione also include the pntcommand wth thefunsion, so whan icalled villcompieal handle the selection and dla ofthe hanging an, withthe first one being print after the firetlotorisgueeses OB tes tee acatbaeniry te cede, ith the function wa calles ‘tart Ite qute simp printing our grecong to the payer and hen sartinga while eep tat wallow uso Keep laying th gare as many mes as we wh The pass Satara alls the nha lop to stop once we finished, ard could be used to perform a number ser ganeo: word = choice(dictionay ry) word_length = len(word) clue = word_length * tries = 6 letters_tried = «” guesses = 0 letters_right = 0 letters_wrong = @ global computer_score, ol while (letters_wrong er) player_score I= tries) and (“".join(clue) letter=guess_letter() JD if len(letter)==1 and letter.isalpha(); if letters_tried.find(letter) != -1: print("You've already picked”, letter) of other task if so wished. we do top playing the fimo, th score function than ells upon we go ter wnatthat oes when ego. OG tenet amet ame ce inthe ‘game’ Functon this tine tour, a6 theres tae much that needs tbe plu. You can spit up furtrer yeu wish, using the sty of code ffom last issue. wad make the code deaner for you or hep you understand the bulling bee @ 7 Be fein tse we wor forthe player to guess Weve got a small tnlacton af werdsina ithare Hae hase canbe imported a HTML or expanded ncn. Crice is used taselecta random lament fam the it, wich comes from the random medule we imgertsd Final, we secetin how eng te sng isc ho werd to guoss fand then create the Sue variabe wth a number of Underscores of that argh. Tis is used te ds the \weréasyou bull tupfrom guesses. O8 wesstessutenesantte nit rabies to x09 tack of cng the gare There can eny be six eorrect guesses before the hang men fll dawn or our case Gepleye, 09st he tes variable fos. Noll Kop rack of the eters trough lata tedto make sure that not oni the player kro, but als the coe for when ite checking aint letters already slay. Final, ‘we croato empty varables forth ruber of ese ‘ade, laters coroct and ators coro, fake the code sity easer. We also It the global 9 Wes et ste es prt 0 layer selection an chock the status ofthe 22ne. Tis oop catinues unt the paver win ores IRstats by checking al re tos have ban wed UP by seeing eters. wrong snot equal tres As eoch ‘ey wil ty add ae pant to wrerg wl never Bo fbove 2c thn concatanates lus and ses fits the ‘samo.stheworthe computor slcted Hf bth hase statorensare tue. tgeasentothanaxtturn, 1O Ws catenin wate usw input alettor and got the variable Wo chock wht it retun by frat ofall making sure its only @ single Inter, wih lenletor, then by sing issih tose’ one ofthe 25 eters of the ‘ight. these conditions are satisied, we start, ‘new if statement to make sure #3 8 now guess ‘and tothe plait sroady boon chosen they ‘an start agai al this is acceptable, we rave on totherext socten ofthe coe to soe fits a corect suessornot i: WhielOLE witheep wack ofthe indents inthe coe, youre using _terteatortowrt rome Python, Jeallhavetomaka sire youve ‘sing them corect, Pythons ‘ery Senstveto whether rt Inert areuredoorerti anit oosaidinradabtyas ml The Python Book 41 EES Soe seein eee) ome seems aes oirnit es: if first_index letters_wrong +1 Print(‘Sorry,",letter,"isn’t what we're looking for.") else: clueti] else: Print(*Choose another”) hhangedman(letters_wrong) print (* ".join(clue)) print (‘Guesses: ", letters_tried) if letters_wrong == tries: print(*Game Over.") Print(“The word was"yword) ‘computer_score += 1 break if 'join(clue) = word: print¢“You Win!) rint("The word was",word) player_score += 1 break return play_again() a AA scenes nsx the fast thing we do's od Ito the ist of eters trea. Tis & dove empl by adding the stings together We then use the find ‘command to aareh the era ating forthe eter frtered, which wil then tu a rumber of the Placement ofthe tar inthe sting Ht does fi a ate tretumsa 1 value which we use inthe ret tatemont ogo tho frst indo ‘aril 7. ade one tothe number ot letrs. ror and than ers a message to et thplayerlreuthatitwasanincorectpsss. AD trie i tan eset ioarect, than we can ery assume ie is comact. Through this sirpo procs of ‘42 The Python Book limination, we fst pint out a message to et ‘he payer row thatthe bon surcestuland ‘monmaoarecodott 13 Weresinge sr sat nn tere vse can upcate te oi th the erect lear ale added Wl woe th ange fron 2 rte cue by using the nord Langthvariabi We then chek to sae which eter inthe word has boon guessed earecty and change that Sspsoficpartoftheclue tobe thet eters ican be printed out forthe payer to see and for uso chockihetrererstthe games. 1G tertnssinatseret ting the player to chess again they drt entra supported input. Before we a> ont the ext ound of chies, we prin ot te Rare, ise: af letters_tried = letters_tried + letter first_index-word.find(letter) printgrtltin eters caret.” FB For i in range(word_length): if letter == word{iJ: letter rman graphic a it stands, by caling the graphic 1 te bt that corresponds to the umber of ‘eowoat guesses hat vebeon mace Wotan pret how the clue curenty looks, wth a space 5 betwen each character, sd then prin the rumba of guesses thathavebeen msde 1B coe we ver agar, frst ofall comparing the leters wong to the number oft. at's ‘wus, we pint a message that tho game hes ended andrevealthemystayofthehiddon wera Weincreasethe computers sore ard reak he lop. The net cop checks to soe the ful cue concatnategietnacame asthecrnal word ‘ats iecase, eprint he winmesspe, the fl wordandaddane port tothe payer sore before treakrg the ep agin. Tha can ago be done vith fserdelts tome usingtroaks O{ det guess_tetterd: print() letter = raw_input(“Take a guess at our mystery word: letter.strip() letter.lower print return letter OF der play_again0: answer = raw_input(“Would you like to play again? y/n: “) if answer in Cy”, “Y", return answer af aise! def scores(): global player_score, computer_score Print(*HIGH SCORES") player_score) ', computer_score) print(“Player: print(*Computer: wf it rane start() 1G Maerstenss ee ncn calingupan tum agsn which we il thenpassal beway uptotestarttureten once itstrsted 17 eran fin tet of fk pente out & raaingut mecsage ‘nce the player enter tho lta, the funtion parses it tobe used with the rest ofthe code, Fraty, stip used to remove any white space from tho input gion 3 woe not gen ay fra parameters. ie hen commer i io lower-case letters, o¢ Python wil nat beable to corecty compare an upper-case character wih loner ease alternate. We then ratte lection for he racord and veturn up othe ne function 18 meistestsimenmeteciena the player if hey wish to try again “The play-againfrction takes & human it wih a simple message and then analyses the inputsoitknows whattosond back \__main__’: 1Q Sire ess an op of vn te ne rave shou expect a rospanse in in ‘The f statement checks to ooe if any of our