Future S Series Coding Academy 5th Edition 2018

You might also like

Download as pdf
Download as pdf
You are on page 1of 161
CODING eat ® 2018 LEARN TO CODE FAST TODAY! * PYTHON * RUST » ERLANG * MONGO « REDIS = GO = RIAK — | 164 PAGES OF TUTORIALS LEARN CORE CODING TECHNIQUES AND ADVANCED SKILLS ‘You n your hands a gateway to the word of programming. tn an era ‘hen the online word runs the wend, the people that can code that world, ‘ule it. Just take few ofthe biggest online namesin the ot ftom the ‘reator of Facebook, Mark Zuckerberg to the quartet that created Tits 10 ‘Google founders Larty age and Sergey Brn ~ they are all programmers. futyou don’ nead to alm to create the next billon-pound startup to have a lust for leatning to code. Coding can be fun and entertaining; ican open the gates to creating amazing projects used onlin by entire communities, down ‘to small physica instalatons running at home on a Raspberry P the only limitis your imagination. Coding Academy 2018 kes you through the fundamertak of learning ta code, oflersa hefty coding referencear the back, and helps you flex your new programming muscles witha host of practical Python projects introducing the bases of database interactions and covering ‘the cutting edge languages of Erlang, Go, and Rust. Let's get coding! CODING ACADEMY 2018 Contents CODING ACADEMY 018 Fundamentals Projects 10 __ Different types of data 32 Python 3: How to get started How Python handles various variables We're moving ta Pythan 3! About 12 More Python datatypes 36 Python 3: Using functions Beyond the previous ones, of course The essentials of modules, mor 4 ity by abstraction 40 Open your coding mind and think differently 16 Files and modules done quickly 44 The ea things avart 18 Write your own UNIX program 43 Rewriting cat for fun and (na) profi Es ig of complex dates 24 Neater code with modules 52 NumPy & SciPy: For science! Use thern wisely for super-ciear jecomne a data scientist 26 Embrace storage & persistence Deal with persistent data in Pythor 28 Lock down with data encryption Look after your data and it will look after yo “Coding can be fun and entertaining; it can open the gates to creating amazing projects” Contents Databases 58 Python and SQLite3 started using databases 62 Get to grips with MariaDB The open source alternative to MySQL 66 MongoDB: Using native drivers NoSQL mixed with Python and Ruby 70 MongoDB: An admin's guide Mik maximum power from Mongo 74 Get your words collectedina database 78 Riak NoSQL Just what is the big deal about NoSQL? 82 Redis data store High-speed. in memory NoSQL Reference 140 Get to grips with Python lists Its one thing after another. isn'tit? 142 Understanding functions and objects il about things and what things do 144 Adapt and evolve with conditionals Because change is inevitable 146. Variable scope of various variables There's avariely of variables, and they vary 148 Recursion: round and round we go Repetition is no had thing 150 Super sorting algorithms Got everything orderly, and quick Do more © Program in Erlang: Introduction Gat to grips with the Erlang language 4 Erlang: Functions © Rust: modules and cargo Get started with the hipnew language Rust: functions and modules Go further tackling error handling Rust: file 1/0 Speed up your transfers 12 Rust: networking Buile.a TCP-based client/server toot Rust: concurrency How ta use Threads Go: Master Google's new Programming language Get yourself familiar withthe fun Go: Data types Get to grins with Go's composite data types Go: Explore functions learn haw you can develon and use: netions 152 Hidden secrets of numbers Integers thoroughly demystifiec 154 Using loops and using loops And using loops and using loons 156 The magic of compilers How thoy translate your code 158 Avoid common coding mistakes Gotitright the frst time Coding Academy 2018] 7 Using Python, we'll take you through essential coding steps Different types of data How Python handles various variables More Python data types Beyond the previous ones, Reliability by abstraction Open your coding mind and think differently Files and modules done quickly The easy way to break things apart Write your own UNIX program Rewiting cat for tun and (no) protit Neater code Use thern wisel modules F Super-clean programs Embrace storage & persistence Deal with persistent data using Python Lock down with data encryption Look after your data and it will look after you Coging Acedery 2018] 9 Fundamentals Different types of Python data Functions tell programs how to work, but it’s data that they operate on. Let's go through the basics of data in Python > Wile we're looking only atasie data types. in reat programs getting the wrong type can cause problems, in which ease youl see a Typetrror ne lundamental concepts cf coding. Here we ook at basic ata ypasjin later ates, wet oot a er nore advanced topics that bull on what wodo here data abslracton tency structures such as trees, and mer. What is data? Inthe word. nd inthe programs that velit there's cn amazing variety of dierent types of data. n'a morteace ‘allt or example the value cl he mortgage, the interest ote ans the termat he isan are alps of ats inashopainglst program, there areal the cerent Syoes foffood anesthe st thet stores them ~eachaf whic has I this section, well be isis Python to broach many of tsownknco! data “The computer's wari sl more lied t doesnt laow the ference betcen althese data types, but that oes stan it rem working with hem. Ths compte as ‘afew bosic ones itcan werk wth and that you have to use ‘reatvely to reprosentall the variety the wo. Welibegintyhighightrg three cata types. st we have numaers 10,3 nd 2580 are alleles ofthese The particular numbers are nts or ntagers, Python Anows ssou llr typos of rumen toa neuter Gone integer) oats (qumbers wth a decimal point such as O35 (0 0.8413) and complex (complex rumibers). There are also stings. such as Helle Worl’ “Banana' ard “Pizza’ These rekdentiied asa sequence of characters enclosed within untaton marks, Yaucan use ether Gauble or singe ucts. Finely there aalists, uch 3: [Bananas "Oranges Fish’) ‘accidentally caught by code that catches exception propagate up and cause the interpreter to exit Changed in version 2,5: Changed to inherit from tase Raised when an operation or function is applied to associated value is a string giving details about the ty exception UnboundLocalerror Raised when a reference is made to a local variable | has been bound to that variable, This is a subclass of New in version 2.0. exception Unicodeérror Raised when a Unicode-related encoding or decodi 10 | Coding Academy 2018 Insome ways, these are tke astring in that they ae a sequence What makes them diferent that the elements that make up alist ean beef any type Inthe sample the okamentsare alsin, tx you could creata another et tat mixes ferent types, such ae [PBananas; 10," List areidntied by the square brackets that enelose them, anceach tem or element thin thems saparatecty acomma, Working with data Trae erty yu cdo wh heclteront pest Catan Python Fr tone jue oed subvec Stare rug trorumcers ans yore here mare S San 2 Hesionttertentt ypc atbresctsstt and fot tre le etumedy Phen beef whatever (erent est tat tity you aaa ares re eureka et ‘ovcantet bis ange ypeO hrton teks tre aatatype tuner aqumet yout ott “pe i> neo) se a> pet 2300 spe tt Nova aso we the sar operations on stings ands but eyhavecifeert eect the oper cncteate tats conbnes gather to snes tw wt? cperaor repeats re cortenisf re srgoris Stilo “Won” “eto Wok >> (Agpie'"2 arse Ae Sega ss atohave Pe ow welt operation, rethgstces ese eae youtoclct a pero part ote square by snared wenbesne emo Indexes workin reverse, oat you want to reference the last lement of alist or thlast character in a sting. you can uso the some notation vith aa the index 2 il eerence the secone!-to-lat character, the third and soon Note that when working backwarcs. the indoeas dont stat at, Methods. Lsts andstrings also ae range of other special operations, each unigueto that particular type These are knowrias methods. Theyre sie o functions such 2s Atyped)n tt they perform aprocedure Wht makes ther Afferent is tht theyre associated wath aparteular piece of data, andherce have advent sitar execution For example among tel lype's methods ae append snd insert >>> stappend chicken) >>> lst (banana, ‘cal iin "chicken >> st insert, pasta) >> at banana’ ‘pasta ‘cke’, ii, ‘hice ‘As youcan cee, amethed is irvoked by placing a period between the piece of data that yuite applying the methoet ‘toand the name of the method. Then you pass ary arpuvents between round brackets, just 2 yeu wuld ‘wth amoral unetion, works the same with strings anc any other data abject to: ‘> word ="HELLO™ >> werdlowrs() “hale ‘There aelots ol diferent methods that can be applied to lists and strings. and to tuoles an dictionaries (which wee ut o oka). Tose the err ofthe arguments ad the fulange of methods valle, you need to consult the Python documentaten Variables inthe proves xanpls. wo wed the deo arabes 2 ‘roe exce to work th our Vrs re ay name cferent values ~ ferent pieces of data. Tey make iteanytomanage athe its of data yeire working it nel great ede th coment of velopment (nen youre sense rare). Assan above. Pylon youre anew variable wit anaesgament statement Fest comes the nar fhe variable then a sige equa si fotoved bythe pace af data thatyeu wart te asin to that inl. From hat pont en, wherever you use the name assigned tothe arable you are actualy rete tothe daa that you assigedto nthe exarpes we sath acton when we referenced the secondeneracter Nasri or the hed slementina ist by appendngindex retain tothe viable tame You canals sets 2eton youeopy the ype furetontoa varabienare: >>> pelo “type t= >>> rete) type ist Other data types Trea to ther conmontjes of dl tre st by Pyle ae coats rose Tienes sequre cata ype ota econ tlanersofmbetypes The bg cerence ta ties re (revutable- tat tos once jo sate sl a = Charen! tuft ‘cannot changeit —and tat tuples are identi by round brackets. as oppose to square brackets: ananas; "tif; “cereal Detionaries are sim tos ota tuple that they contain a collection of related tems. They ciferinthat the elements are'tindowed by rumors, but by hays and ae created wth curly brachets: t's quite he an English Inrguage dtionsry The kayis te vod that you relacking up. and tie value the definition ofthe word, With Python dictenaries,nowever you ean use any immutable data type as the key (strings are immutable, too), slong asil's unique wttin that detionary. fyautrytouse analeady sisting key. ts previous association forgotten ‘completely and that data ost for ever. >>> english = {tee ‘a in ber imu ‘operating system’) poe engin ee! ‘asin bose >>> english ree) ='a5 in bey > ens! ‘asinlbers? Looping sequences One cernen eperaten that youray watt parte on ary ofthe saquence types ilooping ov thir contents to2ppl anoperaton a exery element conared wt Consier tis sma Python program: lat = [banana tli, buto forte nis print item Fist. we create fst 2s we wad naxmally then we wed the forse consrutto peor he print retion ‘oneachiteminthe ft The second worn that constract ‘oesrithaveto beitem, thats usa vanablereme that fgets asigned tempor to 2h element contained within the sequence species at he oe We cout ust as we te win for letter in word ari yous he weed iustas el ‘nce you hove mastered these base datatypes yeu be ready to lok at how youcan put ths krewlede to use when modi real- world problems noe articles. inthe meant ead the Fyoncdecumentaion to become ferisr tn ame ofthe ther methods that provid for the datatypes ve ve looked atetoe. Yell ats of luli suth 5 sort reverse! Coding Academy 2018] 11 Fundamentals More Python data types Learn how different types of data come together to solve a real problem as we write some code that counts words >Horaly surprisingly ‘ur eounting program, after being sorted, be the most ‘common word in The Time ‘Machine, by HG Well common data ypes:rumbers (ints nd oats). strrgs tes, tuples and citoraries We cemonatated ha ey work ith differant cperatars,ancexplaned a few of ther ‘rast useful methods. We dint, owouer, gve muchinsight into how they might be usedn real tutions. Inthis article, eee goingto tx that ‘We're going to wrtea program that counts therumber tines each ungue word orsursin tet le Puretuation ‘ratks wll be exchidad anc ithe sare word occurs balin titferont cases for example, the ard The), re wl 99 taken toreoresent single word Final, the progr wll prt the results to the sera, I'shoultok is ti: the: 123 your 10 2600 [ee tutoral we introduced Python's mest ‘san rample, wel be usr The Tine Macive by HG ‘els, which you can cou-doad from Project Stenberg, ‘sang inthe same older as your Python te under the rams timemachine tt. ‘As the aragram description suggests, he st thing well re todo erik the test seas rm inside our Pion program, This done with the epen0 function flea: is but fies: came with uta: so for a2: upon at fiz: into as jirz: Little no ft12: one 14: not fas: att fue: ne juz: have iz: they hia: from |iz2: there 129: his 132: then 132: you fa7: on 51: this ji57: were jige: time laae: but 12 | Coding Academy 2018 tun = opentimemachine.t Intas exarpie openg)is passed two vaiabies. The ests thename ofthe fet open: it were in aterent cicectery trom the Python script, tho en path would have tobe sive. The second argument species which ode thei should openedin: stands for read, but you can also use ior nite orew for read-wrtte Netice we've algo assign! shel ts. own variable name, fm. so yeecan ete tat ner inthe program. With telerence to the fle created. we also need a way toccess ts contents There are several ways todo ths but today wl be using foram. loop To see how this works ‘tryopening timemachinetet in tn interactive interpreter ndthen yore >>> for nein tm int ine The resut should bs every tne ofthe le print to the seveen. By puting this cade nto apy fl, say ewepy, ne v2 got thestartofcur Python program. Cleaning up “The ogram teserip tion also specif th we should ‘exclude punctuation marks, corsice the same word but inciferent cases 3 one wore and thet were counting inchvdus words ct nes.As sande te have bee ale reatonly enti ines as sts, howee vith punctuation, strange whitespace characters (such as Wn) anderen coersinoct Locking the Python string documentation (ind t Inte: /docs python org /Wbrary), 2: 22 that here four methods that can hep us comet ine tangs ito ‘format loser tothe! speedy the description 90, ‘wanslate lower) 2 spit), Each of hese ae methods ‘andas ch hey functions hat ae apedto parece strings usngthe dot notation Fer exam sti. which rereves specified characters fom the begining ad end of ‘sting. used ths >>> neste) Yn passed with mo arguments tremovss a whitespace characters, which sone othe jobs we need to get cone The fureton translate is 2 metrod that canbe used For removing ae of characters, sch a allpunctuton mares ‘roma sir, Touseit mths capacity treedsto be passed ‘wo arguments the rst being None and the secondbeing thelist of characters tobe deleted 25> linetanalte(None, "AS97600" tower) speaks forse realy ~ i converts every charter atta loner ase. split spits tine elements insde a shing into separate stings. etumingtharnas ist. Bypaseng.an argument to splits possbie to spectly ‘hich character tentifias the end of one element and the start of anther. >>> linesplt’) Inthisexarole, weve passed single space as the character te spit the sting around With all punctuation removed ths val create lis with each wordin the strng stored as separate element, Putallofthisin the Python ewe started ‘noting on ea, tse the for lop, ane we've made considerable progress. It should now took ike ths ‘m= open(timemachine 7) forline in te ins = ine arp) line =linetranslaofNone, #574541" it) line = inetowecd ist = lie split) Because alll the strng methods retum anew, mactied string rather than operstingon the existing string, we've rvassigned the tro variable in sac ine to store tho work of the previous stan Uniqueness Pre: look atl that work weve ust done with dtl Byusing the string methods, we've been abe to remove al ‘he its of data that we werent nterestedin. ve ao spt cone lige string, representing ln, smi chunks by comertzgittoaiist and n the process got the exact. Sbstact concept vee mostinterestecins words. Our sunning ogres a, hae til some werk to bedone We now needa wayt entity wien words ae unique andnot stn this ine, but ee ine contained vat the entre te “The rs thing that should pop into your head when ‘hina about uniqueness adstionay tek vee store ‘wesaw nthe pravous ace doesn alow dua keys se by ertecing each word aa key wins tionary we're susan hare Won tb any dupes ‘Whats ror, can dss tho wu fo stone the umber times esch wordhascccute.ncrementes ashe program comesaeross ne instances ofeach Key. Stary cresting the dictoraryandensurirg that persist forthe ene fle rot sta singe tne ~ by placing hime belore the stato the Fr kp: i= “This cates an emt dictionary, which seedy to receive sur words Nev, we road think about away tot each wordinto the cicbonary. As we savas time. orinany 2 simple asslgnment statement woke noah to 6a ‘new word to theaetionary We could hen iterate over the st ‘weereaed bone (sir anatherfor loop), sdng each erty tothe dtonary witha vai of (represent tat thas ccouredonce nthe fe), for wort ist vor) =2 But remember the key already exes the od values ‘nervition an he emunt wl eset To et aroun is, vwecen place an ite clause nse the on “Another data type wrestled with, another step closer to our goal” More Python data types yea vee Changed version 2.22 Supe Retum a et of pa verge nthe sting. using aap 88 the arer et I ‘ost mange sate ar done (hm the lat sl Rove & me wan ae fot speanea or, thentnere ene iit an the number ot sles (al posse I Sep quan, conseevive aemters we ret grouped tageer ae ae 3 empty sings (or exarpe, hoa" Faure U2. et). The sal ‘cone: of mie charactars (fr example, "inant aiti-wt retue Spkeng an erry song wan a specne separate retur 1 I sep cnet spaced mm, a cret spitting agorthn is aplect rnf wasoace ae ragardec a 9 chee sepraer, wrath rest wl carta no tha stat or end fhe cthg har dra &trlng whtespace. Corseau feely ering or 6 Soin ceratng of us wheespace Wh mm separate e enti ame ca ar by ee —— wees : rr fe tao pe ster Rope dicted] = 2 invaluable source ‘This isaile bt conlusing because detfword] sbengused for discovering Tacdtwntwerhivacrsinetwatstesie Seanebea Minagutttenusccruementctrned weektien! Sowthinescomteniiowengredtsbaie/s —hwtouwe thew vol, re=pactiely Neti toa that fa werd aeaey inthe ‘ictionary, yneincremert te county 1, represeriing ‘another ccurence, Putting it together ‘Another deta ype wrest wth srcter step cose to ‘ur ae Atri point al thats to dois insert some code to prin:the dictonary ard put tal together andrun the ogra The prin secon shot ke ti lb tho very and ofthe fie. ou do the Ineoopng code. ‘or vordsount in dict tertomad) ‘ia werd +°:"+ sie) “This for oop lokscferentto wnat you've seen beter. By ‘ung the eritema etnad ofthe cctonay. can access toh the ey werd) and vie count) 9 sinle loop What's race ' ha toure het lrcton to convert count aninteger int ring, 28 the + operstor can't concatenate an integer anda sting Iy rurning it ane Youshoule your ermal sree ile vith ines he ther 20 fice 2 wetting: 2 Data everywhere! “Thats slannecto achiov inthis partir aerial andits actualy turnout tobe quite alt. As wellas have Hara ceance to ee now sora itera types a ta {and their methods canbe apoieto soe real orebiem, ‘wehope youve noticed howimportantitis to sel the pproprate ype fr representing cferent abstract concepts Asa further programming exercise, shy nt lok ino sorting the resulting ebconary i acer tose wich ‘words asc most ecuenth? “au might also want te consider wring the result le cone etry naling, tsa the rt of your tbo Coding Academy 2018] 13 Fundamentals Reliability by abstraction Think your code is solid? Perhaps it’s a bit too lumpy. Creating abstractions can make code much easier to maintain ee Jrrcirsececntoraterte i arco a ormeanstor tor exapert aes sfersctretalrendn: enatonsrensstp vert orcs caro ibe glo ceetetnny or bomnngerenta astaplete roses So stv we tae abet Fats eral erreur re ‘Square roots Towel ou heats around the concept of abstraction t's start bytinkng about 2qre recs and ferent techniques far fring the. Oneaf these was scored by Neston ais this inaun a eaten seth waka Newton's method states thal when ying to fd the scuare oot ofa number (0), we shoul start wth guess (/) cfs square root: we can then improve upon that esulby averaging. aur guess (9) wath the resut of dng the numb (Coby ou guess (As we repeat this procedure, we et closer and closer othe square root. Innes attempts ‘we raver reach a datrite es lol rake ol guess ‘rere end roenecoraie Everts wl each alae ot ‘accuracy thats good onough fer our neods ae then give Up st tobe car about ht isiewotved, ake a ook the table below for how you would epply ths metro to find the seuare ootof2 (for example»), itealotofwork past find the souare root of anumber. mage fen youwere n schoo very ‘ime you had tofind a square root you had too altnese steps marualy.Sebing problems ivoling Pythagoras’ theorem, for instance, would bbe much more unielay Lucky, assuring | when you wereat school there's another, much easer ‘methai you can use to find square roots Caleistors come uae rot symone a were alowed touse calculator: onth abutton marked Qn (133+ 1572-14167 (ate + La 1417 ya = alae 14 | Coding Academy 2018 “This is a very powerful technique that makes programming easier” you have todos press this button once ~ much easier This second approach i what's known as an abstraction, {When working on problems, such as those rong Pythagoras eorem we con'teare snout hawt caleulste the square root on that we can doitare got result. We can treat the square ret button on cur asabiack 3. — We newer look side we doxrthnew how does what does a that matters that me knew how 2 use al thattves the comect result This a very powerful tecnigue, one whieh ean make programming alot easier because theips us tormanage ‘comply, Te demonstrate how astrection can help us consider he Python code below for frding the longest sie of ight angled wiagle impart math ‘el phan, a2bo= faa) +0" D) uess= 10 hile (ath fabe(guess" guess) ~ 2262) > 001) guess = ((azba / goes) + guess) /2) tum guess The fest ting to Suro, ita piece of cade tis short, you can read trough i reasonably quicy ad figure ut ta m sane its not obvious, end it wer longer and wrten tke ‘his youldhawea terrible tire fing cut what on earth ‘nas dong \woulabe very cific o test the diferent parts of tis des yu go along (a reremental development, ‘tal for ling rout thats nat ntheteast it encable softnare). For stance, how would you break out the code for testing wheter or not a guess is close enough tothe actual resutor the code for ‘ocheck thatit works? tunetion dt rtm the exoacted resus ~ how would you start testing allthe parts to fad where the error was? Final, there's useful code here that could be reused inother funtion, such as that for squaring a mur or ting a average of two rumbers. and even for fn the -quare root ot ruber bul ne a ts eusable because ofthe way its writen. You could type tal out asin. cr copy and pasteit but the mare type you have todo, the moxe obscure code youhave to copy and paste, andthe more ely mistakes ore to make itn to your ogramning de gain, this be wth some he problems tect. Wishaw the contents of each new function we've creat leaving them for youto fin import math: ef square ef eloseEnough(s, guess ef improveGiessts, ges ee sar, guess ef pyrnace,b): ‘aha = squarla)+ square) sun at(aab2) Hera we've spit the code nto several smaller tunetions eachol which usa partcusr ole Thshas mary benefits For starters, how much esier i the pythagO function to read? inthe fst ine, you can see cleat that 2b s the result of squaring two numbers. and everthing below that hasbeen consolidated in ta.asingle function ea. te purpose of hich also obvious, Whats more because ach patel the esi hasbeen split into a diferent untion, we can easly tstit. For example testing whether improveGuess() vas doing the ight thing would be very easy -come up with afew values for xand guess.do the improvement byhare.andthen ‘compara your results with those returned y the Ration I pytagd ise was ound not to returnthe coreect resull, we could cuicy tes al hese allay functions tenarron enn uherethe bug we, ‘And, ofcourse we can easly reuse any ofthese new functions fyou were finding the square root of a nuber in ilerent function fr instance, you could just call the st luetion ~ six characters instead of four ines ears there's farless opportunity tomake mistakes. ‘One nal point: because our sgt code iow abstracted ‘ve could change the erplamentalion compel. but slong si wekeptthe function cal and arguments the same, all “This code can be improved by taking advantage of scope” cod thatreles ant would continue to work properly ‘This means tat you corne across much moro fient of ealesating square root, youre not stuck th working throug thoussncs of ines of code. manually chaning every section that rds a square rot: you di ‘nea. adits done everywhere. This code canbe improved sil farther by tong adage scope eloseEnough) ) There ae layers of abstraction undemeath everything You do ena PC — you ust don't often think of them 5 § 5 & g = Reliability by abstraction inport math ef square(x) : esturn x * x ef sqrttx, guess) : def closenough(x, guess) Lf math. fabs( square (guess) return True else: Fetum False = x) > 0.8) def improvesuess(x, guess) return (((x / guess) + guess) / 2) while closeénough(x, guess) : guess = improveGuess(x, guess) return guess ef pythag(a, b): ‘azb2 = square(a) + square(b) return sqrt(a2b2, 1.0) print pyBhaa(2, 2) > our tna code arclimproweaetsarpaticiar Sth sar funcion- farting tne thatstoeny ees teens reunite on Tonget ede of thee sevens ote io “tepleep curcode lean acrakethereltinshp lange than vetoantncetutensande cer vecanlcetar awed Seitonsinade te dtr of rt setae el sat guess ae ‘more robust and generally better of irspreveCinaa(, goss) ‘These functions are now wise only to code wthin the sat) finan ~e say they rein the seope of sqetQ. Anything ‘utside of thas no des that they even est “Ths way fwe later need to Gein similar functions for improwngaguess inaciferent content we won tfarethe issue of elleiyg names o the hesdacne ct fgurirg out ‘at improveGuessig a improveGuessZ0 cs, Layers of abstraction Hopetly thsexamplehas demonstrate how peer technique abstraction i. earn mind thatthere are many ers of abstraction presertn everthing you ‘ona computer that younever thnk of Forinstance when you prograrming do you know tom Python presents integers in the comauters memory? Oro theCPU perorms arithmetic persion such 25 cian ana subtraction? The ansver is probiy no Youjust acs the eet that ‘typing? + 3into te Pvtnonintepreter returns the correct resut andyou never have to worry abot how it oes this “treat as ablack box. “Think how mich lrger it would take youto program ifyouhad to marualy take care of what data wenn which ‘memory oct, o werk wth binary numbers, nd trance ‘alchabetic characters nt their numeric representations ~ thanlegoodness or abstraction! Coding Academy 2018] 15 Fundamentals Files and modules done quickly It’s time to expand your library of functions and grab external data with just two simple lines of Python or the majority of xogremening prec. you don't get fa before facing the age-old problem othow to fPtdatsintaanceut of cur appieaton Whether t's Using punched cards to gt patterns nto It entury Jacquard texte loom, or Googlebot skring webs for data to fedits search engne dealing wih exernainput ‘sas fundamental 2s prograrening sel Andis problem and concept that you may be more fair withon the Linaxcommand ine. When you ype i ist the contents ofthe current directory for ‘@armple: thecommand is readingintne contents ofa fie the current drectory ~ then outputting the contents toanother:the termina, (Of course, theinputs and autauts arent fest th Dhan you sost cle not ecg betta shee Ln tend themost fesjtemhorbnen does eenngina ie Ianeages wil Ths ip ien yu ent ose ne poco Step rough oper ct athe patter poclariabor! You rmay already know that typing Is >listebxt will redirect Detling the ye ito Me corers ai cales na hk sad crs ou cantte ts ruc turer besause tre ou can be RELY renter he aes aor rv pe tha the SESaEI «vires barenureten the apts herp sort hoatatine | Worestearersedapebetalst after scones 16 | Coding Academy 2018 “Tf the filesystem knows the file is being changed, it won’t allow access” The complexty othow data input and output can be accomplished ently down to your programming lervicrement. eer language wince furctions led and savediata for instrica but this can ether be ctcut or fey depenting on how many assumptions the language isviling to make on your beha However there's aways alogieal sequence of events that need fo cur. ‘You wl frst needto open le, creating one fit doesnt ces, are then cher red data ror thle or write data to it ators expt closing the teagan so that ether Most guages require youto specty areas mode when yeu open a fe because this asthe flesyster whether to expect fe madifcationsor rol Thisisimportant because mary ferent processes may also want to access the fl. andi the lesystemkrows the file's bang changed, vont usualy allow access Howser, many procescas can aecessareadenly ie without needing to wory about te itegity ofthe dat it holds, because Pothing sabe to changeit. you know about databases, it'the same kind of problem you foe with maltple users accessinethe same tale inPyen as with most eter languages opening feta vite or as read-only can be dane with 2 ste ine: >> f= open Ist", "1) Ith fie doesnt exist Python will generate a’ Na such fe or rectory” eter. To aod this, we've used te output from ur cemmarc! ine sxample to create txt flacaled Iistibxt. This swat theflder rom where we launched the Python interpreter Environment variables Dealing wih paths folders anf locations can icy become complicated, ands one of the more tecius sues youl ace vith your ayn procs You find ha leet emirrenertshivecitrentsoktons fo nr Ses, th some creating keywords for common iecalions are others leaving ito te programme Thisisnt so bed winen you ony deal with fles crested byyour projects butt becomes cifcut when you need to rw where to store a configuration file or ea default con. These locations may be diferent depending on your Linux cistrbuton or desktop but with acress-piator language sucha Python, they' lsa be eilferent foreach eperating system For that reesen,you might went to consider using lervrorenent varianes, These are sma tovarable ath global sconein mary programminglangunges, out they apy ta ary one user's Lux asian rather than whi our ‘em cede iyoutype env onthe command ine fer instance, youllsevalisto the environmental variables curerly sat for your ternal session Look closely, and youl se a fe ‘that appt to detaut ocatons and, most mnportanty one called HOME. The value essigned to this enstonmental ‘exible ile the lcationo' your home foker on your Linux system, and if we want to use this within our Python sep, ye fist need to addline impert the operating syste pectic mode. Th ine todo this is impart os This commands aso opening a fle, butt in thesame wy ve pened itt This fe sown as a module Python terms, and modules tke tis port functionality including statements and definitions. sothat a programme doesnt hove to keep re-nventing the wheel Modules extend the simple constructs of alarguageto sd portable shrtat andsaktons, hich why ether languages might cal them Hares. Litranas anc modules are iti Ike copying anc pasting somenne's ox research _andinsiht ito your orm project Onlyits better than thet, because medules such as as are used by everyone turing ‘the way they do things inte a stander Setting the standard ‘There are even staves calle stant these embed stander ‘ways ofdong mery tings alarguage does provde by default sueh ascorimen mathemstial anctions. ta types and string services. as vel fle nputautput and support for specie fe types. Yau wil inthe documentation or what ibrar does wit an APL. This wilt each “uneton ‘wha it des, and whit requies a an input ene an output Yushoudalsa be abeto find the source es usa the import er by nelude nother languages). On most Lise systems. for exams, b/python2x il cade athe races. you lac ospy ino tet youl sree ‘cod yauve ust ako to your project as wells wich functions ne naw secesbekayau “There are mary,many erent modes for Python ~ ‘one of thebest reasons a choca ever anyother lneuage ard more can usualy be mstaled with ust a.couplec ccks fromyour package manger Bulthsiswbere he uy spectrect dependences can slertto have an elect on your project, pecaute fou wane {one your cove tosomeone else, youre tornske sire ‘that personas also got the serve modules stale you were programmirginC or C+. or exam, where your codes compiled and inked ageinst binary ibaves, those brary ioranes vil 0 eed tobe preset on ay ‘ether sytem ht rns your cede They become ‘decendencies or your poet nich 8 what package ‘managers 6o when youinstal complex package The os module ‘Getting back to our projet the os odes designed to preside portable way of accessing operate system permet functionality 0 that you can write rul-ptorn applications witheat werryng about where fies shouldbe eced This includes inowie where yous home directory might be To see what we mean ad ths code: “Tf you load os.py into a text editor, you’ll see the code you’ve just added” Files and modules done quickly > Binary thes f= penfos etc HOME fistt*e) have no context ‘Ths ine vl pe thee st ben your home fold: Pytnon without an rows home folderis yours because theesenwiron sociated fe function fromthe as mode returs anne ‘ype and away of ‘rom an endronmentalvrinbl, andthe one ve hove asec! aig them. ittoretumis HOME. Sut all we ve done is oven the fie, fiery wwe\enet yet red any af ts coctnts. Ths righ ner igs a oo counters, butit’sanhistoncal twoubacktothe way San that tes use be stored whichis wy ths is also the way near allanguages work's only ater ale has been ‘openedthat youcan start to read its contents Eceaaline) ‘The above instruction wilread a singe ln ofthe text ‘ie ard output ths tthe mterpreter as a sting, Repeating the comman willed the next ne, bscause Python rornembering how far trough thet it has re Internal, thsis boing done use something called 2 pointer and this, too, cmenonto the vast matonty of languages Alternately you wanted tread the entre ‘ie, you could use read). Because our flecontars only ‘te copying the contents toa Python string isan easy cormersion Thesametant tnof binary tle. Rater than beng tested as text the organsation othe bits and bytes that make up abiary fle ae orgaised according to the fle type use by the fle ~ or no le tye at life's raw data As a resi, Pyton (or anyother prograrnming language) would be unable to exact any context rom a binary fle, causing an error yout tread into string The solution at eas or etal pte ‘24d bag men you first open thee, because ths warns Python toaxpoct rw iy, Whon you than iy tread the ‘put. youllsee the hexadecimal values ofthe fle output to thedlsply. “Tomas this dta useful you" nesta do some era ‘work, which we'llook at net: ut fist, make sure you cose the apen leas this should ensure the integrity cf your ‘eaystem Az you might gues, the commen looks ie thie eloee Andis as easy 2s that! Coding Academy 2018] 17 Write your own UNIX program Try re-implementing classic Unix tools to bolster your Python knowledge and learn how to build real programs “You now know more zce | than enough to start ish Sandor Lary and writing real programs” 2xrts-£ serine rein base input $ signs at re = ur chosen languages each tine: and hich wl mae tpt the eurant ‘nvithreal nor rrumter atthe beginning of 9c ine Thst ing to creat vith ary rum ffs want to feow along, ake rr bet compatible wt argurrentto the open Lineton which ected that the fl should be openedinead-onty mode cess tthe fle now provided tough the newly fe object. the next task sto dspay is conte, ine by ine, on standard output. This very easy to achieve because n Ph terablo objects erable abject, such 2 a, sings, ples aid at atime tye puting tin a for 09. a al ‘orline fle The final program well be implementing. t's not long, but it makes use of alot ‘of core language features youl be able to re-use time and again 18| Coding Academy 2018 youputallhis ina fle, make t exccutable ae craato hella fle nthe same directory, yu see that it weeks rather well Theres one oct, however ~ there's an ompty Ine batien each ine of output ‘The reason ths happens i that print automaticaly addsa renin character to the endl each ine Because there's lead a nawtine character at the endo each ine Inhalt (there i, even if you cant et othernine everything would be on one na! the sacar newline ‘havscter leads to an empty ine ‘ou can fixthis by calng print with a second. named sreuent sh a: pining, end="") Ts tle: pint to Du en emay string, orne character at the end of each ine ead ofa newline character. Passing arguments “sis alright bu compared there eat commane theresa glnngomenon her we waulé have ae the program code isa to change whch fis bone delayed tostancard aut What we need issome ny tones arguments onthe commandline. o that we could cll our new progam by typing eat.py hellott onthe commer Ine Since Python has al atteriesineuced ths 3 fare traierwar ask, 2 The Python interpreter auoratcaly copes a arguments passed onthe commandline, and a module called sys nhich spat the Standard Lzary.makes ths salt your code Eventhough sys part th Standard bang. its nt avaote to your code ty cela rstead, yout have 9 imoottto your program and then access its contents wth dot rotation — con't worry. texpan this naman Fist.to mpertitto your prowram ac Inport 8 tothe top ofyeur eat te The part ofthe ays mol ange objec. Ths ct stores alt te argumonts assed access and manipulate using vaneus techrwaues Weve Senin previous tutors areal show in ute ones “There are only two things yourelly need tke bout th. They a The frst lament of te were interested inthe lstisthe name ofthe program tse al arguments follow t D> To acces the st youuneed to Use dt notation thats to-say. ans stored thin ays, oto access t yournaed to type sys.argy or sysargvf] to get te frst argument to spur program Knowing this you should now be able to adjust the code we craated preveusy by replacing ellos th sys.argv (When youcal eatipy from the carmandtie you ean than ass the name of any tot Wo, an wil work just the same, Many files Of course. our program is meant to aczept moc then one fle andcutpu alter contents fo starcaré cpa one after another bul a things stand ou progam aan only accent ele a carga Taft partir prober, you nee to oop ever flesin the ary ist. The only thing that you need to be of when yeu dothisi that you exclude the very rs elem the ret “The part of the sys module we're interested in is the argv object” Write your own UNIX program Acthitier [fermi 9 The output ofthe real Unix cormmand, eat, and our Python reimplementation, ‘are exactly the same in this simple example because thisisthe name of the progr te. ou thin. loackto our previous artele on dats tyes andicommon list operations, you reals thisis easly dane with as Th ist one ine foe Mein sysargvt Because operating onal fies passed 2 argurnents toa programs such acommen operat Python provides a shorteut for done thisin the Standard Library ce np. Inotderto use tis shortcut you must stimportitby putting import fleinput ath top of your code You w then be abe to use it to ecrate the rest of our eat prograr soir a5 flows Jor lin in fleinpt input: printing, end="") simple shorteut uncon takes care of eporre file ture a aking ities aeestinle ro a single iterator ‘That's about all that wehave saace fori ths ttre ‘Akvaugh there has not been much codein this parteular ‘example, wehepe you have stated ta get a sense fer how ‘much is avalabein Pyhen's Standard Library (and there how much workiearaabiefor you te recy) and nom 2 med know of ts contents can save you a of work when implement rew Frogs. Ths Coding Academy 2018] 19 Fundamentals Enhance your UNIX program Our tour of the Python programming language continues, as we continue our clone of the Unix cat command previous tutorial showed youhow to baka serge I Tecrcnen Pye nti pace ne gogo fomernore festires to cur program including the aba to road fom the sara input pipe, jst tka th road cat, ra the ability to pas eptions to yeur eat cle. So, pr without further delay e's die in tomork ike last tme~ that, by concabenating the files Fortunately. you already know everything youneedto contents together:ft's called wthaut any arguments, we interact with he standard input pipe. In Linux allppes are want ourprogransto workby repeating each ine entered into Standard. Me could ‘easily co this with what we “Python provides us with (rocoto cme amuch more powerful | :is2ysmyransy=1i spoon alternative to sys.argv” greater than L thon do at lessons version. atheraise In Python, the sameis true Allyou need to get to work with the standard input spe acces to the sy Roary. wich [Retue til then prt evrything that come standard output, Right, new ws hove two modes that our pega reitto cperalein but wormed to put the togethar inte a single Ifwe callour program wath arguments, we want t trea ie es ~ you can pass ale as anargurent to command oryou can pass apipeas an argument It dosent maar nich you do because they're basically co this version sflen(sysangy) > 1 you flowed along last te, you already have. Lat’ rite 2 (ast month} ite sample program esto demonstrate cae: lipo sys (his month forline in ays tin Prety straightforward Te any paint ef ntrest ner isthe inti, end") se ft tng function, seing as we eon a jour to Tho rst ine enpnrtste sys module The nes that flow are cover ferent Pytnen functions This unetion i bul to slmest identical to these that we had! last ime, Rather than ying the name offi, hawever, we specified the name ofthe file-obect, stn which found inside the sys mole lust He ae fl, Po the staring pipe an erable object. wove use for lop to walk thraugh exch in ‘You might be wandering how this were, though, because standarcinut stats off empty you un the program, you \wilsae whst hanpans, Rather than peeing cu everything that’s present straghtaeay wil simply wat. Every tes ve ne character is passe! to staan oy pees Python and canbe eppied to ary typeof sequence obect (a string tuple orlst) or aeman (ke a dictionary). and itaays tals youhow macy elements aren that object. There are more usefl functions ike ths wich you can fn at Mai Adoos sxthon.org/3/Rorary/tunctions iim Parsing arguments and options hiss quit a simatic approach however, and Python actually proves us witha much mare powerful altemstive to sysangy. To dernerstat ths, we ae png to a 9 ‘optons to our program that wil moi the output generated byeur program. ‘You may not nave realised it but eat does int range of options, We're going to implement the-E, whicn shams doler symbols 2 the endo lines, and-n. which Ceplays ine numbers a the begining ones Todo this, welstartby sults up an OptionParser. This Isaspacal object, provides as part he optparse rrcul which will do mest ofthe hare wer for you. AS wells automaticaly detecting opens andarguments, saving you a lott hare werk, OptionParser wil automaticaly srerate help fx for your user in the ever hat they use your program incorrectly c= pass “help ti ke this: ) The Python language comes with al the bells and whisties youneed to write ‘ionarosaut “i, Jeatgy -help useful programs. n this example you can see the replace method applied to uu rs IGeTNONT [Leh 2 string nore to remove all white space — inthe tori we used the strip Oe ae ‘method fora similar purpose 20 | Coding Academy 2018 Enhance your UNIX program >The Python 3 website provides excelent documentation fora weath of builtin funeions and methods Hyouever wonder how to do something in Python, het docs python. (rg/37 should bbe your first port of eal “ty shelp show this help message and ext BE Show$ at ine endings sn Show line numbers el pregram To get started with OptionParsr, you frst naed tolmport the necessary components ‘fom optparse import OptionParser ‘You may nate thal this looks aba ferent rom what we sawbefore. Instead of rmportng the entire module, we're ‘only mportng the OptionParser abject Net. you reed to create anew instanceof the object add Sore new options ‘oritto detect with theade_ option methos, and sassita usage sri to dspey usage = "usage pro option. fe." araer~ OptenPrser{usage-usage) paced option(-E", det="ehorrend action~"eore_ true", alp="Show $ a ine cedings" ‘parser add option(=n", dest=" shown’, action="store_ true’ elp-"Show line numbers") The Meprog orto the usage siring wll replaced wth the paiefyour program, The dest argumant species what rrame you'll beblte use to access thee an argument once te pars has been cen whe the ation specties what that value should be nth ease, the acton store_truesays to set ‘he dest vr able to True he arguments presen. and False ifs You canreadabout other actions at hitb: /Adocs. python ong/3/irany/optparse.ntn. Final wit everything set you just acto pase the arguments that were passed to your program and assign the eeu totwo array variables (options, rms) = penserparser_aret) Te options virile wil contain all user defined options such a5 +E orn. ile args wilcontan all estsoral arguments ft ovr after parsing out the options. Youcan call these variables watever youlke but Ue two wil abrays be setin the samecordar 2 dont confuse yours yp ‘he waribles the other way around! With the argument parsing code writen youl next want to startimpementing “Don’t confuse yourself by putting the variables the other way around!” v:is:cveaitiemoe te code that wllrun when a particular optionis st. in both cases, et be modifying he sting of text that’ outpat by the program which means youl need toknow itl bit abou Pythons bli sting ettng functions Le’ think about the or showend. option fist. Allwe want ths todo Isremove the visti ne bras thats at the end of every fle {or every line ofthe standard input pipe, as imple by pressing Return and replace with 2 dali syrbol Followed by ine break The fest part removing the exstie ne ne. can be achieved by the stringsrstripQ method. This renoves a whitespace cheracters by default atte righthand etgeotasting Ifyou pace ating toitacan argument itl sip those characters rom the right-hand edge stead of we space In our ease, just white space wil Completing the job The ecg part ofthe obs a spl as seting the end vera printsateen to esting Sma he fe is almost compete. Vie say “atest comple because ne stllnsedtovrte sme mare legit further contrat ow of te programbased on what options vere set aswel 35 whether ornot any arguments se passe The thew. his ose compicaled than it orinaiy would be because we need to raintan acumaative count of lines that have been printed the program rans to implement he second -n or showmti, aon We there are severly you could actnewe this. inthe next tutorial we'e going te intreduce you toa bit of abet oriented progremmingin Python and implement this furetionaltyin acs. Wel also introduce you toa very mpertant Python convention ~ the main ution an he mame varie ty Ue meantime you cankeup yourslfbusy by westigaing the sting format mathe! and see whether you an figure outhow you can append a number tothe bes mnt ofeach tine. Coding Academy 2018] 21 Fundamentals Finish up your UNIX program Our guide to the Python programming language continues. This tutorial, we're going to finish our clone of cat ve core te along ay verthe st vo We aang parted yo cchothe cons “It’s a very natural way of thinking because it geesonestyteue H mirrors the real world” Ite careful though, implement the same function wth some este for loops. though thay weroteay a8 readable as ‘object-oriented code ‘When tuking complicated programs, figuring ot how to ‘organise them so they remain easy toread, easy to rack Which vanables are berg used by which uncon. and easy ‘of mull es othe screen, the ably to echo standard int to te screen and the ‘ably to detect and act upon 'sforusto implement he ine rumiser opton andte gather together everything else we've writen intoa ‘ingle, workirg prewar. Objects Laster een sgt here are many ways we coukitelatantte ne curkegerer hou roan Wee gangtoshow yout too tin nce ones Sole oases us an eae vue autos topes of Pnnpreranmng You cou honeer nthe to update, extend, or ad new eatures, can be challenging, Tome tis ease, there ae varus pari gms tat provide techniques for managing comalony. ‘ne. these paradigms the concent af object overt programming. In object-oriented programming. the elements Co he program are broken down ntoabjecs which contain state variables, nother words that describe the curent condition the abject and meted, that lla sto perform actons on those variables or wth that obec. Wa verynatwal nay of thinking, because it mirors the realworld so closely. We can describe a set of properties ‘bout your rane such as nawng fe gers tata in certain locates, and we can desrbe certain methods or ‘things you can lo wih your hand, suchas moving one ger to press ake. orhoking 2 cup Yourhandis an obect compete vith sate and methods that at you ers wit \We'e going totum our ea program inte an object. where ltsstate ecoxlshow many ineshave been diselyed, ard is ‘methods parlor action othe ea aragram = realspaying le contents tthe screen Python objects Fyn moments rougha cls syst A css ‘ements aertcue etaer ot atl mredeladentte tele We cene sre ces ah keyed chile we define anew trcton Seca Inte hcl we spect heres (nce) and State tet we wart teste wth eey sarc he teicher ste soe speci ethos however ete resend) ved Or of ace stent retin won the os ttinsanttctos ore ejct ard aon outst sec varales hat ou var Pehnats that bet ‘def _ init _(eelf): eine nth case we ase the cout vari. Seuss mracrd nou tfary Resin bees depot Youprbb) rocedthe etre pases hein Zarenttotnemethed swore near hat » Just to prove that It works, here's our eat implementation, with all ofthe ‘options being put tose 22 | Coding Academy 2018, was about Wel tsthemain stnguishing feature between methods ancordnary functions. ‘Methods, even those that raver cther arguments, must have the self variable isan autornatialy populated variable, which wal always pont othe particular instance of the object that you're working wih, Soselteounts acount variable that sexclishe toindivdi instances ofthe catCommand oc The run method We nextreed torte a methodlthat wilexette the appropriate logic depending on whether certain optors ere Set Weve else the man method det runtsl pons) ‘set dfait options inti, end) Notice that weve passer the self aria to this met, too, Thetwoother arguments passe to this unclon ara arguments that wl pass when we eal the methed ister an, {ust ike with anormal function. Theirs ts going tobe a Feforenceto whichever fie being sisplayed at this moment, while the options varables 2 reference tothe options \ecovted by the OptParse mci. ‘Thelogic alter thts clear—for each nein the current fie. modify the line depending on what options have been set Ether we do as last time. and modiy the end character tobe $n" oF we modiy the ine using the Format method thet we suggested you reseaich last me to append he count ‘nab defines inthe iniémetnce tothe est ofthe ine We then erement the countand prin there. ‘Tremost important partis th use o sel. Its us er to variables stored within he current instance of te object. Because ts stored as pertof the objec, il persist after the currant execunon ct the rum method ands. As long 258 use the run method attached to the same abject each time weeat nev fia in the argument ist, the count vl remember haw many bres were csplayedinthe la fie, ane continue to count corrects. might seem mare rtial ~aventhe deseration of methods as indvcal actions ‘hat can be takenby our objects ~tosplteach argurentintoa diferent method, and this sane way te aporaacn the probe, ‘Trereacen we've done this way though, is that we ‘oud it meant we couldreuse more code, making more readable and less errar-grane Nowa that’ lett to cos tobe everyting together. We are gorgto do this by wrtnigarmain function Ths sat actualy required in Python. but mary programs flow ths idiom, so we wiltoe “The last thing to do is call the main function when the program runs” Finish up your UNIX program (exe > The completed program ln’ very long, but Ithas given us chance to Introduce you to many different aspects of the Python language forainans f= openta, *e) ceruntentions) lee: runes, options) ‘Ws avert iled inthe object parsing ods rom the prencus ‘tora bacaune that heen changes What snes the @ = eatCommand9 ine. This show we create an instance of ass — now we cate anew object Thee cbject now nasa veriabe. count, vn fs acessibe by alts methods asthe _selfcount verse, This 's what wil enable uste tack the line numbers, ‘We then check to see whether any arguments have been passed they have. then we cal the run method of the ‘beet efor anch fie that was passad 2s am argument, passinginany options extractec ty OptParse along the 2 Itthere weren't ay ‘arguments, though, we Simply cll the rum retort itn syst insted ot = feabject. “The nal thing we need todo are actually cal the man function when the program Fur: t_name_—"_ vain” ain) ‘Thosalasttwolines are the strangest of al but quite ustulin ‘altof circumstances The name vases soeciel— hen the program s tun on the commans line or atherwie 2s Staneaioneapaicabon, is sat to main, rower, when it simportedas an external roche to ather Python programs. its not In this ve ean automaticaly exscute maim when ran ‘28 slandalene program, but nat when wore imoorting tas ‘made. a Coding Academy 2018] 23 Fundamentals Neater code with modules Untangle the horrible mess of code that you've made and add coherent structure to your programs. “et. ifyou ve wien aprograr of any length even st ‘fen hundred nes. this 2 loo you rene doubt desperate for in along feof code, you'll raverotced how cuicky it becomes more cfu toread. Functions seam te Blur into lene another andl when you re tying ta hunt dawn ne ease cl the test error you find ficult remember exactly ‘here you defines tht alrmportant waradie, These problems are caused by alack of structure With al your cadena single ile. more fil ta devermine the ‘Cependercies between elements of our program ~ thats ‘ich parts rely on each atherto get work dane andi’s more cific to vetlse theflow “As your programs grow {e231 in length, there are other 7-7" problems that occur” ere ton tere ae ther probes tha begin oeeur for instance, you may fed yoursel yh nang confit 35 ‘we diferent pars of your program requiefurctions called add (or example addr integers or aden Factions in ‘mathematics program), oryou may have writen auset function thatyou wat to share wth other programs that youre walling and theenly tool youhase todo thats boring and error-prone copy and pasting Untangling the mess Modules aga eye se ott hese problems trou yest ut scare back your code erg ‘pune ramrg conics mere exer bre fre so chunks face Detweon rarer Tove io del bons Pema neue your eae asyeue ied on Frye bulinor party maades to prove elect era turcloroly Asan ecm temeber {reoptparse noade ve wad beta Wercled true progemaong wih helmport Satara Be sr iearoanee Aerputng thereat he op fur Ft pga we Imapely ft access oa who kod fee tuners that ‘ctoatcyprsdconmancine gprs Wecous 24 | Coding Academy 2018 coess them by typing the medule's ramet te functor we wanted to execute ‘ptparse. OpionParset) Tis wos great ran 2 eadabiily erepectve Ir our eat clone we ee have to wa through lots of code abot parsrat commandline arguments insteacwe culefocus ‘onthe cade that eat with the lle of echoing fle contents ‘othe sereen arto the stant output pipe What's more, wes thave to woery about using names nour ou program that might cold with those nthe optparse marti, because they were ll hiceen inside the optparse namespace and reusing tis code was as easy as type Import optparse —no messy copy and pasting hore How modules work Mocks sound fancy. re you might tin they're commited oat ~n Python al least ~ theyre eal just plain ol les. Youcan try itout for yours Create anen disctory ancinsie create a fackpy fe. side. define a function ta return the factorial ot 2 ven number et factorial} reat = while n> 0 fa: result se result Create 2 secon Python fie cles doMathpy. Inside ts, fist import the module you jst created and then sxecute the factorial function, printing the reslt tote sereen limpet fact print ac factorial) Now when yoursthe daMathgy fle ye should see 120 printed on the screen. You should notice thatthe name ff hemodue is just the name ofthe fle, nthe some rectory wih the extension removed, ‘Neca then eal any function fein tha oe by typi the module's name, flowed by adot followed bythe funtion rare The Python path The cuestin thats tis, how does Python know where took fd your moles? Tearaveris hat Phan has apredstnedsel locations that alsin ef fest mate the re seectedin your pert statements. rst ols ins allt thei modules, the neato af which are defied you fst instal Python: it then searc ttectones ren a the tn, much he the Linx Bash shells $PATH hroughalistot Ths pot cesthe same syn and ves exactly the same function, It varies, however in how he conkers ofthe Pythan path are generated It, the locatons storedin the path cons st ofthe following to locations The directory contarning the script doing the impertrg 12 PYTHONPATH, which 50 of eirectoi detnedin your dotautstlaion You caninspect te path in your Pythan endironmen byimportng the sys mace and then inspecting the path altbute yee syspath il do the tek). Once 2 preeram has started ican even mediy the pathtst and aed other Variable scope in modules adolf nd start merry writing your oun rors tring that you neste kn Before ‘mediles tere on about: variable scope We have touched upon scope as concept before but as a quick etresher, scope eters tothe part ofa program fram wich particu yerbles can be aocessee For stance single Python module might contain the folowing code food = apple”, “ranges”, “pea"] jon@Adarn:~/ixt-example Neater code with modules By splitting your code up into smaller chunks, each placed in its ‘own file and dlirgctory. you can bring order teyour projects pnt ood (ef show. hee) food [Ponickrs, ila’, "ly ie) print food show choad pint food Hyourun that, you see ble food reers 02 itreers toast of chocolate bas, Tris demonstrates two stor rent mal, whic leodrelers toa ist of at and be local sc at ouside te function te ist rt, whi sie te neton, songs te gabal scone ofthe Astin, inch food reer tchocoiate When locking uo a variable, Python starts wth the Irnermest variable anc works ts way ou, stati wth the immediately enclosing urcton, and then any unctns closing that. and then the made’ global scone ard re bul names, abd ia to put lta scope. tcan cause contusion and subtle erors eleewhere incur program Using maul can hep ith this problem, because each module nat sia, wher we part a mada tes ofthe mode's ts nfl iwllook at al Insimple.sirgle-fe programs it veriebiesint slobal scope. As we itscontants are a storeclas atta dat notation. This makes global vara nat less troublesome, although you shoul stilbe Whlerany peepe thik Python ae pratlems ana madernianginge ts actualy been ss oak sure nt:/ python net/“goodger/ arcurdance meaty 19908 fewith —_renabletr ea worse ane anvanes clse proeets/pjean/2007/iomate/ irypregrimminglangungsthatsbeen werk withyou Grchdrg handout hid breunelforany length aime. necple who your are sl) maton one/dew/nens/ tiseitefen have lesred at aot the ur out more pepr0008 bestwmystadsthngsinthelanauge shout thesebestpractessn Phan, ed hese ancyoure sie tozin Intern ofthe ensest wy tere strom someckeper neg nt th langue Coding Academy 2018] 25 Fundamentals Embrace storage and persistence Deal with persistent data and store your files in Python to make your programs more permanent and less transient “Almost every modem application stores data in one way or another” Lrg ca youcanty 0808 eter oro: canter 8 Sore “aod avait aloe oper tact Seon oan) brmeerto open vee cone species which mad the fle shouldbe epenesin~ ints aso i's ite bul ober val options clude read-only (6) ‘capper (a). In revcus tutorials, we've shen you thatthe abe sin fat aniterator which mans you can use the ln keyword tolcop through each inein the lle and deal wth ts contents one nea ame. Beloe nvening thal nferaton, however ie’ lokeathow towne data toate. Writing to files Suppose ules you own PS open tl sn yur avourtatee uw area otsrn ay A sarc ener ats rtp gap, creos usinga woo fora Ca bur now yao Sle at ttefeedson sks acne use ar when Joe chechrafr ten unite Ate neers mest creda Rhone es aera oar RA RIES taonton poet -hipRew dro" ‘oases othe else rele rooms. ne wre ret tefl nfs ewe een) 26 | Coding Academy 2018 Easy! Netioe how wo used the format sting function toadd anew line to theanc eteach string otherwise we wouléend up sth everything cn ane ine ~ which would have mado harder to solar Re-using the contets ofthis le would ba just a simpie Using the fe as an iterator lead each nein tur inte a ist strpaing ef te traling new line character iN eaue you totauretns one out. Latyouret bem fries Theft eto nedte comvatwhetvryocwert owe lote toa srg tt THtiseny thou because youean juste Stroturcior fr earela srt) =>"2" Tho secndisthtyuovele ste He afer yuh teed sngit ita soca yosklesre cata at youtrougthadbeen crttedto dk ut at hadret Jeibcen shed Yc dothorrarualy nthe dese trethed of fecbpcis eur exe tis woadtrrateto feirg macomed toe prem an toon voethe wi ty seth pen a" le feds este} fo ne inf) Thissiote pare of Pen cote hanaes sing te Aeob ad unenve bockrsde the wth cateent isthe rata ceses torus a el ges are Uru vtat theese ine ons yk vp Pen st eoascaie auloutganescmerhnciora sie Serialising ering wh tes would be much ess oui tho meter) eto ast nea oars pri isco get sy Ferny Phen pesto ees toratotiseaser or Theatre toes the ple mex Pele accepts mary eiterentainds of Python objects, anc can then comer! them toa character sting and hack again, You si have to do the le open and closing, but you na longer eve to worry abou (aur out an apronrate string represertation or your data simpar pice with open Dest. “a a le: Pickle duis, le) ‘wih open test tt", “1 fle: food = pile lode) Embrace storage and persistence ZODB - a native object database for Python Dnt squeere your objeto abies sore amin an chet database Overview Pynonprotams are win wih ie objet ered paradigm You use cet hat efernce each ote haste achore toa speci schema aneanhot aay ormaton ‘String those objects in elation databases requtes jou to ge upon the eedom of rerence a roe you abit fo wil bce code “The ZOD8 tga mate ebect database that ors your abject we lowing yuto werk wih any para cade becomes spl, more ebust ard east fo understand ‘Aso, ee sno gap between he database and yout progam oe code to wie, fo mappings fo Some ete estes hat ZOD tings to yo ‘ransparertperstence or Pybon os * FulAGI compatible ransacton sppart incu savepoes) * sonido aity + Efficient supp fo bray luge objects (BLOB) * Puggabesterages {Seale eetecre DH you're interested in persistent data in Python, a good next stopping point the ZODB object datahase t's much ‘easier and more natural in Python than a relational database engine (www. z0db.org) This is much easier anit has other applications uside of persisting data ines, too. For exer it you wanted to Transl your Teed st accoss the netwe, you woul fst have to make tintoacharacter sting. too which youcoud siowitplekle ‘Theprobir ith this that twill aly work Pythan = that sta say, other programminglangucges don't sport the pickle data formal. Ifyou Ike the concept of piling (crore ganerialy. sors), tere'sznother option that does have supportin other languages. to: JSON, ‘You may have heard of ISON —it snes fr JavaScript Object Notation, andis away of converting cbjects rte human-readable string representations, which look amost identica to objects fourd inthe JavaScript prograrnming language I's gent, because t's human readable, anes because’ widely spoerted in mary siferent languages largely because thas become so prpuier wih farey wes 20 applications In Python, you seit in exzetly the same ways pele — the above example. replace pieke wthjaon througout, and you'llbe wrtng interoperable, serials cee! Shelves Or course, some code bases have may erent object thet you want ta stoe persistently between runs, and espn, ‘rackot many erent pickled fles can got tc. There's nother Pyinonstanare module, however, at uses pee Underneath, but makes access te the sored obects more Intute ancconierient-the shee mec Essentially a shel a persistent cictionay = that isto sa, a persistent way tostorekey-value pats. The great thing boul shelves eves. thal he value can bean Pion fbject thst ple can sariaiee Lats saa fot haw you can use it Thinking back to our RSS reader appication. Imagine that a3 walla the lit of fae to cha you yates tokaep trackothow mary unread tems each feed had and ‘which tem waste last tobe ead. You might do this wth tionary fr example tracker = ("bbe.couk's "lasted" “uaanead”: 1) “tnaxtonmat.com ("lastsead’ "bar, pum resd= 5, ‘Yeu cou! then sore the Hs eed andthe track deat foreach ns singl ile by using the shelve module, kes Import shelve shell= shelve open(IxHest) shel[Yaed| = feds shelf wacker" = ake shelloee) ‘There ar afew important things tat you shouldbe sare of bout the shelve ecu: The shelve mode as own operations for apening and losing es. so you cant use the standard open hunction, Tosve some data to the shlf,yourrust frst use a stancard Python assignment operation tose the valueof a partcularkay tothe object you want to save As th tes, you must close the shal object once fished ‘nth others your changes may not estore Aecessing data inside te shel just ae eae Rater than signing a ey in be shel estionary ta avaiue, you assign a ‘vale to thet storedin the gictonary ata particular key: feeds = shelffeeds"T Iu vant to most the data thet was stored in the shelly tin the temporary value you assign to. then reassign that temporary value back to the shel bore closing it aga, “Tats about al we have space frtietutori at keep reading. because we'll eiscuss ene frat option for persistent te relational datahasas (lor example, MySQL) mL Coding Academy 2018] 27 Fundamentals Lock down with data encryption “The first rule of data encryption is this: never — "svewse Tuite nat. to try to create your OWN” — ene thatsieie Learn the principles behind encryption — we unpack the details of how it prevents snoopers from reading your data y Ye dont carting a progr the ober rally ty ta de our ata ret \wenormally rt wrt our fs so that other pros ssumathat but the ba toma Howev inter puts ica, anwia0 iether strings of det by XORIng eachitem inturn provides al vere for cur eneryption fetstarted, method which wellgetontoin amirute First we'llook at snever the nlormation we're going to encrypL 2 that the fist rue co data ener fut own Unies ths you have PhD inthe Tex kel computer data estore in isary 218 aed of mathematics and pientyofewenence, 0s, ASI text encoding stores each choracter as a string ot umber of anda that ar gene feightbitsof brary information For exampie, 2 clurbreakaole and most arguageshave agcod _01000010.e'is OLO0I01 and is ONOUIO. ASC tet of encryption brates thet suppor these. These libraries then jst chain f the ‘one ent bts web far mare: just: ne to hide tethen cola unneadabie that only he orl us tha possword (when: 4 t'sretered| bck? Actua. seal simple Backin Asymmetric encryption iota it a arena For sayolstaringth Goes vesthep. get mrmunicate wth oterwee they bo erate Anythes thal is problems won securing encryted with the pubic he can any be des ood a wih the priate ky unicaton wth, orexare 1 nee to ota ake. and tobe diferent for very prsr erro implementation, se Net Bathonces uteri 3 _mtectradarcom/nens/interel/data-privacy: 28 | Coding Academy 2018 Lock down with data encryption ‘ORing characters 2 We can encrypt a stream by XORing each character in tum with our key school you may have learned that a+8) +e=a+(b+0) Thats with ation at least, doesn’t matter which order ‘youd the adaiton:you slays get he same rest. Wl tums out thet the same thing true of XOR But before we can use that, there are wo mors thins ne nee to know anything thats NORA with sel 80. nd anything KORA with Oisunchargec ‘So, hey KOR key ic O and text XOR itor. That means that tee KOR Chey NOR key) ite and we ve just ieamec that thee the same a (text XOR hey] OR Key Since our cyabertent is just tet OR hey. we now know that eyphertent OR kay sour exgina’ tax, Basically that's just away lone ‘way of saving thet we can cecryst something excl the sae way we encryated it Statistical attacks ‘Wenow have our maha of encryption and decryption but isnot very Seer Fst fal there aan 255 pease ys (i we retucealleg it srs, and not tthe ones that have ASC charactors) ss perectyfeesibe fran attacker to check everyone tum. However. tums out They dont have to InEngiah ax, sore charactars are erycommen and others ar ute rare For example te space character \susly makes up 15-20% of al tie cheractees na plece of test and the ler case sbout 10% wis loner sase Zc beastie 2s 002% and capital Zamost never Sco ghen ceiraeter mat tot il veys vate to the same character nour cyphartert these pepartions wll coro acres For exp. ven the cyphrto ‘9901001 o0021110 00000013 01110001 oc110010.00111000, coxeceoon222001 00110100 oor60011 ooxooOi0 oxiti0t (1110001 0100001 00100010 o130001 01000 00111110 2610003320001 02100010 09130300 0110109.01111101 (1120001 oo120000 09100013 120100 01110001 00111110 01110 an00101 61110002 o2i60010 0010100 0130010 0100100 0100011 0110100 ican See that hesmost common & bt ti: O10COL OR truth table [ma Input2 0 © Q oO 1 r a 1 1 ° ‘We can take a ques tat this the encrypted form of the space character. ‘We know thet tot XOR tet O and key NOR ska Trecesore we kn that (ext XOR hey) KOR texts ey. ‘Sat we XOR the most cammon character wih space (00100000),we get the kay. this case.’ 1010001 ‘which comespends tothe ASCII character"Q: Using this ‘wean decrypt he whole tent to: XOR ciphers, as you se, are nc secure ‘This known 26 statistical attack ads one of the ‘most common ways of atacking eneryetion, The simplest ‘way te prevent your data aig etn fo ts tous an encryetion method that’ wel known and been tested by thebest mindsin the business. AES. Twoish eee Fsh ‘and Serpant ae a good choices. As we mentonsdat the Sart, you should finda txay that implements onwor mere cf them in your language of choice Yeu may have noticed sight Maw in this plan. How co you ind out servers public ke nthe frst pace? After al ‘fan attacker could Wik you touring tet pub key they ould read the supposedly secure communicatons, ‘We get aroun this by using ceticates. When you instal ‘2web bronssr it wilcome with public heys for aumber of trusted ceteate authocies. A website can then got one ofthese autotest ign ther pubic ey. When you go to ‘an encrypted web pape, the server sends youacarfeate ‘uhveh contains both the pute key, and te senate rom tha authority) the enerypled method. Since you trust the authority you can now rust this certcate, ar! ead the page sao inthe knolego rat's baen secre transmitted andnet tarmperee wth Thismethodisn' perect Fist. itrequres you totrusta range of authors jeu can see how many authonties you tras in your webbrowser Fr example Fox, go toEdit > Preferences Advanced > View Certetes > Authors) Its qua few. and most sre probably commanes you've never heard of much fess trust a hacker or asgrunted ‘employeo gots into the computer systems at ary one of ‘ther, they coud intercept almost any encrypted web tral ‘hey wanted. But thats the ony way these cerita can be suerte. If anattacker cen Sind away of forging the gia signal. they canteck a computer into thinking ‘communication comes froma parteuler source when ‘e05n.In ac, tvs tis method tat allowed the Fame malware to getint rian computers Merosoft had used ‘hoinsacure MDS (athe tan the mare sacra SHA) hash, fend attackers wer abe to use thie to make the compute think something was signed when wasnt. Be eal at Coding Academy 2018] 28 CODING ACADEMY 2018 Projects 32 Python 3: How to get started e'removing to Python 3! About 36 Python 3: Using functions ‘The essentials of modules, classes and more 40 FTP: Build a client & server 43 Python: times, dates & numbers Essential processing of complex dates 52 NumPy & SciPy: For science! Become a dala Scientist Coding Academy 2018] 31 Projects Python 3: How to get started Join us as we investigate what is probably one of the least loved and disregarded sequels in the whole history of programming languages ayback nDacenbe 2008 ten 30(abo does aby rane ect br programas as abun Wee S000) mnsmicwed. fctonitn erepece tics rg eel yee ‘iron wearutunjest te andmestpeople lovey crwrten raking kd of Uncd nrestlotunrarorhemesparinsiartorane ”detraelapoes nce Yul! Pon Python preparer enicsrbuicnrabtaneeares _progarhaud hae Beat Declines ante sustonsery mento, pean wo) Fromenpenifsalivhlinioigmetacin® — repemdyerummnwn mionzents nia nda? chines For oethiy ton2iwhle.—_alnolusgacoeacl ec of yar states catiily the endof the 2xlne isstllregularly mantaned, (to suppress the rewine character), then sad news: this and probably uilleortinueto be unti 2020, Furthermore, larger works. Instead, we use te end parameter, which by because many ofthe major Python projec also many, delautisarnaw line For exarple ‘many minar ones) havent been given te 3 treatment, ‘print (Allo ends") anyone relying on tham i forced to stick with 27 pint Cone ins’) arian acauplee! big proets~NumPyand prgo-— ‘did make the shit, and the hope was that other projects Print in Python 3 woLk flow aut leasingtoenavaknehe fet ‘sini proportion of Python proaramscada be made Uncunstels his didn thappen and most Python code you compatbie with ius by changing the print syria, ut there fir out thee wil fail under Python 2 With few exceptions, are mary ther fares ral, things that coud go won. Python 27 sferwardscompatise wth. inmany cases ‘Tounderstand ther, wemus fst be au fat uth what really pessisietacomeupwincade that wiluerkntth but changedinPythan 3 Lcktothe old ways Indoadaronin the Mostol the work ect speak Engh n fact most slilprogrermers fealent monty mepzzine Lin Forma certain aor, the work doesnt everuse a Lan character se een these ether by hab gnerance or atfecton forthe past,continue regions that do tend to use diferent sts of acoents to to pronde code that isentelyneomaatile with Python. decorate the characters, As result, besides the ASCII Ween dothatinthisamicie Ne proms “standard niamerots civerse and incompatbe character oles start with what might have been your fistever encodings have emerged, Each grapheme (an abstraction of Python progra: 2 characteris assigned codepoint and each coveponts ‘eine Hello wow igned 2 byte encoding, sorties dency nthe pas Guess what ~¢doearit workin Python 3 rt you ityou wantedto share a document wih fragn characters romise.?)Trerasson doesnt verk sat pint inPython 22s e statement, wine in Python 3 prints afuretion and futons ae, rtheut exception, cal vith bracts, Remember tat functions dont need taesurs anything (hese that don’t ae called vo unten), 50 int is now a voc function which, nits simpest orm takes astring as input: splays that tring as text to stout, and retuersreting Inasseree you can proton print i function in Python 2 since you can callitwith brackets but mace oar its own spacial yt bracketless shorthand. Ths athe le the honour one recetves in mathematles when something named aftr is creator sro longer captalsed for But these kind of excep exemple, abelian 0.9 ae not apart ofthe Python canon Special cases ugh to break the nes’, soi's brackets > The Greek kryptos grephla, which translates as-hidden the vay.Onadeeperlevel having afunctor-proper print writing: followed by a new line using the corect sept 32 | Coding Academy 2018 Trina, text was encoded ASC wich coach characteris encoded a at codencint which pres you28 characters ply wh ‘Some there characters ae imate teehoe codes (ASCilonghates inthe 19605) donee Because welt thngs o be bytes, several 2ot- character etansre ofthe ASCl encoding ‘energed The most notorious thes 150 ‘S250 sometimes cab Lato. Ths dey aed charac et (a the ated ‘iro 1252) conan arent al he aeons requ for thoLatrerpted lnguagcs a wo Python 3: How to get started he Unicode revolution other arguages. As a result its farlyeommonin thewestam hemisohare, but est aly she theprobin esgerno Thecorret soluten woud a standard encoding or maybe couple othe) Eat characters argencon earth mht coneevrably wshto ype, Obveousy thie wilrequre many characters <0 welihave todo ‘ay wth onecharater encocing toorm te (ence divergence of codeponis ands ceoodings) bts fora greater goed. erlunteyal te manlng, aing re crarisaton of ther rigmarclehas been done and we have an ‘nner: Uncade Thisaccounts fo oer 100.000 charactors bidrectoral doa order, gat forms ard more Current tha ro codes muse: UTP which uses one te for oro charactors (akg it entre bachuards compatible mthASCI) arcu te fourbyesfer the more cosmopolian ones: 3d UT which uses two bys fr some characters and fer bys for ors, Utd has beer wily adopted both 2s atrage secon standard and for ner processing testa The rnin send treo Python is thal te predoconer didrot dotholater, it then plain ASCII vauldntholp You could use ono othe iterative encecings, tyou naw the peopia you were sharing with cou do the same, but in general you needed toturn toa word precessor wih a partcular font which just ‘aves the problem elseayere Thankful, we now havi 3 widely adopted standard Uncede (see Mh Unico Revolution box above) that covers athe bases, ans bbasovards compile with ASC and(as oraz cocepints are concern) ts Latin extension. We eaneven have LUnicedeincur demain mes enough internally these are alstilencoded as ASC, vag system called Punycode. Python 2 far om devoid of Uricede support, its handing of ts done fay super fciaty (Unicode strings are Sealy -encade! behing the scenes) and same hires party modus stilwon't lay icely wit it Strings in Python 2 canbe of type ste (hichhandles AASCIItng but wil behave unprecictaly for codepomts above 127) or thay ean be of tyne unleode. Strings ctype st ae sored as byes and. when pind to a terminal, are converted te whichaver enced your systernsocala pected (though the LANG sc L€_* enwonment vranesin Linu). Forany modern lta this is prbaby UTE, buti’s defintely not something you shoul take for gran, The unicode typ: should be use for textual ercourse ~ fining thelength of slicing or reversing string ‘example the Unicode codepait forthe lowercase Greak letter pis 0260 i hexratation, Sowecan deine a unicade string rom the Python console He so eroded au terminal tanhandle Unicode autpul and sus suable fen: 35> pl=uNetsco o> pn) >> ype) ‘type ‘unicode so> en) 1 However itwe were tot this ona terminal bout Urea suport things wil wrong, Youcan simuiste sucha Seenari y starting Python wth SLC_ALL=C python Now when you try to print the lowercase character p. you wil run ia UnicodeEncodeError. essentially Pion s 39g Ans faling to coerce th tan ASC character (he only pe supported bythe pxkrtve C locale). Python 2 alsa ties to 2 The PyStone benchmark wil kly be slower in Python 3, but the same won't be tre forall code, Don’t be a Py3k refusenik without fist trying your code perform his coorion (eparcess of curent lcs stings) ‘wen printing tf or 2 pipe. 50 dari use the unicode type for these operations, rsteaduise st. ‘The strypain Pytnen?2 i relly just alt bytes correspond to ow the strings encode onthe mackine This is what you shoudluseil yeu wnting your strings to dak oe ending them over a netwark orto pipe Python 2 ‘ity and convert strgscf type unieade to ASCI ts ‘tendatae default eneodng)inthesestistene whcheaudresutin —_euafyfent tears Sowecanasogetafuniypichwrecterbyusngits stl UTP byte representation det here are es fr enter converting UnicocecodepontstoUT-S(er UTF-i6)tytes, aug Dut wi suticetskrply accept hat the pi character cadens frcodestothe totes CFBOMUTFA We canescape terete ‘these wth an rotation n orcerto make Python undertones: o> spi= "CF ws? => types) sype'at> >> lent) 2 Se wapparentiy nowhas twoleters. The ports: your Python 2c is dain stuf with Unicode characters. youl need tava kinds of wrappers and checks inplce take account of te scakzatonof wher machine may un {Youll also have to handle your own comersionsbetween 2 Coding Academy 2018] 33, sr and unicode types. and use the codecs edule to change sneoding 9 rected Aso you hove Unicace strings your code, ou! nee to add the appropeate declaration at y the top ofyour cede eof these arejust the remo ie coking code (Python 3, nike 27 doesnt need to be compatible “The main diving force for anew Python version was the reed wrth 20), same of them provide new features, a! some of toreqnte trom te ground up how the language rings and thelr representations to simaliy tis Some argue tt oy (see Amn Ronacher's deattwith them farce prograrners to Go things citerently But wat there's mere: for example, funsbons can ow De passed they use te tags process rent t httm/Zbty/UnicodelnPython’), iy ‘nto th argument Sets, and estchine ddeounds on your puracses. Python J dove away with theckd eontios via variablonow equies the as keyword Ako unicode type entirely since everything abeut Python isn yeu ean nolanger se teu <> eomarsen operate Unicode-oentated The str type non stores Unico test for inequaly — nstezd use the mach more stylish f= caceponts, the language's default encedingis UTF-& (sono whichis also availabe in Python 2 need or the coding decorator above) and thene bytes . og abject stores byte arrays, tke the old str type Thenew str Automating conversion with 2to3 type will ood ibe corwerted bytes i's tobe usod fer For reasonably sol projects and those thal arnt going to any kid ole VO, bt thisistrval via te aancadeg) encounter any frei characters Bey that your Phar method. youre reeding Uncodetertfles.youllreedto ea iymade Python 3 compatible usre en ther in bnary mode ane convert the bytes to ser Sane Aleph, be ‘ome. The cereus pace erteur) Sono ere faced casa (ie cruris Python 3. Shalom ees aa 5d0 meh) ox icy ieee Eres yy re oahacur ofthe cs ints expect ar) ey implicit FTae ests implicit FUE ee creed ech ech toh Perc pant art Crests) her cri - imaraor a oat and 1 re uses the expt foo garments 6 Yost (o eal). tenth mene chisenopertor 7 whieh wetum the avoursunehonged 16 ded con resus aoa oan. Thismeans the / operator snow 38 >a epercingon the arguments, Te tier mathematica distr prone as Ye can Nope ao pers was acualybeckported te 27soits ana ssues ching unexpected rt wine ie shows he tt command operating on we inger cause harm 34 | Coding Academy 2018 your Python 2 code, withthe goa of eriting bona fide Python 3 code Usngit canbe as sirple as: $203 mypy2eodepy This wl output of ary changes agains the orig le ry. pecty them exalcity. using the -oation, An exam butfer which wilrelace al buffer types with memoryviews Thase two acer't entirely compstibie so some tweaking mgt ue to-w option to averwrta youre = dort Sp rat. Some fers lor ecessary in ardor to successfully mira. Using 2008 save yoU a whole heap al tort hig and replacing print statements moran, for instance 2 drudgerous task. The pictured example (over on te lett ‘np shows the changes 2. simple thes ina program the wniehr function snow ee), because Unicode s senate pene en Parlez-vous Python Trois? wath both Python target one spec Python 3 Welayouseud really only Python version, this mc ground is very ttl won youre porting arc testing your code. Yourngh needto reworca few things in Python 2 wie sil enjoying te nev features and lerng thenew syntax Many Python 3 features and reaready been backportedt 27, and many more canbe enabled using the ‘uture_ rode Fer example yo can go he new fate pelt sex by using the followin 25> rom _futre_import pint fanetion hiss used withthe from in th vay. snc_fuaure_ doesn't Python 3: How to get started > The popular matpioti> been Python 3.compatiie since V2, forall your graphing ‘and plotting requirements standardrodue ~ instead it cts asa comer which in this case provides the modern pent imecrt disionte thenew style sen, tormake strings Unicode by deat. There fs ature, wh y. but can ansion sue was released, When Pt being about eneraly sower than its edscessor. Tis was rot urpnsing because see was net relly apnonty forthe "251 (wnichvwas lensed n December 2015). rice performance had sce been improved, y,Ahishant been the case, which you ean very Fox yourse using the PyStone benchmark We testa its ne previous spread) on an agg machine nthe ofice which has now come back rom the dea! twice and he fer beyond what ould suggest PyStonetests various Python rione togeta pelure. You can always use Cython Inte: /evthon org) to spe up co nooas, math ray access) or the bttineck mode ‘Guido van Rossum, the author of Python says that Python 27 willbe topestpone earning tie new version paw. Python 3 sdaptionisinereaeing, 0 yu went be lane Hal the work sree oad perentheses. sported unt 2020, but the Coding Academy 2018 35 Projects Python 3: Using functions Everything you need to know to start using functions and developing classes, modules, packages and objects in Python 3 a "wanda cee aston tehathe art yor nck crates ote baste arm cis Soines cde trston Ts sn scetetr o ama) ‘esses, cbjects, maces and pockets main purposes to clarify altheve terms by using small ‘earns that istrate haw to create and use them alana large part ofthe tuteralis about namespaces. which ate used ‘eryuhere in Python 3 Functions do two very important things: rst, they enable uste reuse code ans therefore recuice code repetition, which, intur, afiows us to writ les code. Second, unetions offer yt soe abi pragram by saking smaller campanents of that pobtem. “The lowing Python code decaves anton thats named aFunction: ef aFuntiond- rine”) T his tutorial wil teach youabout ython 3 functions, > This isthe output ofthe myFunctions.py Python 3 script. The lat statement ofthe script causes the eror message you see onthe screen because timesString() cannot use a string variable as an integer 236 | Coding Academy 2018, As youcar see, a function dattion begins withthe de eynorfllowedtty the furctionname. fs not mandatory {or aPython function toreturn something or ave a naber ‘of arguments. Youcen now use aFunection a flows: aPunetiond Despite the fact it prints thesarne message athe tne, the praous function takes no input ar eturns nothing. However, most of the time function takes one er more parametars 2s input ad returs one or more values. “There function wevecaled timesString tokes to parameters: an nteger anda string, as nput and returns astrng ef ineeStingttimes, te) ‘sing =" for xin range (, tines) sting t= tet telurn sting ‘Youcanuse timesstring 2s lows: snySting = GmeeSixing(, Hil”) penttimeesting2,"HU") However cline timesSting() 2s tineeSting HI" Hil) ‘wl cause an error message because the fst pararneter ‘cannot be used as an integer inside te tuncton ‘As yournight be aware when a unelion tures somthing you should take care oft andi quite common ‘osavethe return vsiveafa function using a variate The proper way for a function toretur a value swith the return heynor t's very enpertantto remember that Python has no rules about the types ofthe arguments and the retum value ‘ofa function. hey canbe whetever you want. However, itseasy te forget that when a function works withinteger ‘ales, itll now work en you pass a sting instead You shouldbe very careful because improper argument types.can be the source of nasty bugs, Although t's not mandatory to “declare the ypes al the uncon arguments You are tee to foc (See the serene, et fr mere formation ) Now quick mention of function dectatons in Python 3. rat the det heyword doce ts crate anew object and assign ‘name to it So det creates a new function object ands ramets used for referencing it Now that you know the basics ‘of functions. we can str tang about classes. A Python class Python ses sa ay cf grouping functions asvarsles using an objec rented method. A Python cass provces all theexpected entures of objet oriented programming such azinhentance and method averrda ot. The flowing Python code defines arew Python clas that we ae cali Linus clase Linu ‘def _init_{sef version) ‘al. version = version ‘As yoircan se, class definition begins with the ease eywordfolloneby thename ofthe class When the ‘efintion of lass contains amethedl with the name of — Init the —init_Q method is automateally erecuted Tor very instance cfthe clas. The _init_0) method can also have arguments tke anormal function You can see aul ‘cmp of the Linux la in myClass py, Its now time fora warring. The folowing class dation contains cas variable that's shared by al nstanees of the class. Ths quite apowerfuldevelopment as means that can also be changed by alinstances ofthe class class Line ‘data () ef sdData(et amber: saldataappendlaNumber) So, imagine the faving Pyton code, saved as sharediariable py. frame = ‘main ‘d= Linux) ‘ew = Cin) ‘daddData(L.0) semadaDat.2) printf Ole, ol data) print New: newdata) Fs output willbe the oir 8 yon’ sharedVariable yy Oi f.0,12} New: (10.121 “Te correctcsig for such avanable woud ta declare inside the _init_ method. 20 that it would not be shared byalistances ofthe eles Now another be secre ‘everything n Python 3's class! A Python object Putsitpon obect vob ofa ger des Wiles Gare got aciraer: ance sore gene es tt est anem be ec rng ets ag rratrods Sa vitout ncbiectoestra acs ecertely Itatneay As joussu fine peviag econ yuan loctre wichita aly tre Whe programming snot as cfu 2s yourmay ‘he Remota tial atk, eapaiy wher you nave toprogtamevteal appestons. You should Jean the bose tres est and then iy told someting reaon your oan The-ne thing rernerber that yu shoul tbe ated of ‘earning boas, as ong asyouraen making ew rmstakes and cevlesing new programming ‘hl, you wit fal far how code {AS programs tensa cortan enors eerie 80 a) Ir the preerariner Fst ofall you navetoknow tat cebaere code tat ovr someone ese rote is more perpen, Programming and debugging and dic than be actual iting ofthe code butitcan also be very cia. The hardestpart the debugging preoess sang he bugs i's ‘eorecing ther on your machine. Thee, Paris usa the exsist art ofthe process ‘When debug code self ofan the ‘olowngthings mmind revercetng code hen youare seep served or atausted and that ernebmes tie better toleavedebusg for tomerrou or tae awalk to get some fresh ar ‘ust Addnonaly whe you sould ry tose abu as eal 8 posse. sometimes ts better ‘vente a program. or apart of tor scratch Python 3: Using functions > Thies the arwetory structure ofthe famous NumPy package, which contalns| about 1100 files an directories! l= Linx new =Linu(23) Lets move orto modules. Amodle in Python isa single fle Imported uncer one import statement. The presented Python ‘edule, saveo 2 myModule.py, il show you nowt eroun different elements and put them into.a module that's named Le. def helo: rint( Hello Wer") smyVersion = 123 A Python module ‘Tetra assae saeco aod vate Aste tft cadet es tamed mM te namect the moa le pry Youcan hn sel nya grams os: impo myctle ‘myModuleballo printf MeduleryVersion) It you execute useMyModiulepy hen t's wil goneratethe folewsing output Spyibon3 useMyModulepy opiates but ery oracte instead of tying tnd aut why tees ‘work especialy when youve 5 deal wna Felatvely small aout of code Las youshould avays hearin mind that the code tat the hardest fo dbus thecooe tat Yyutrk cara posse oe wrong, ovoush, the best Geta technique stryiy te wae clean code rem the begeving because clan ede contains ss bugs ands easer te debug. Pytnoniss rest programming anausge to lear programming an crest vet nmakeyoua Oopsonie prams pontenoe ‘ts ae titer ‘we pagentg image Coding Acaderny 2018] 37 Projects 2» Helle Wort 13 ‘Aer using myMockle, you might find 2 neve directory rammed _—pyeache__ The _pyeache_divctory contains Python 3 iytecode compiedand ready te be executed and is automaticly creted by Python 3 $ls-1_pyrache_j toad swwr-t~ 1 mtsoule miso 293 Aug 23 1017 module coython 4 ye Sfile_pyeache_/myModulecpython-24pye —pyeache_/n/Modulecpython-34 pyc: python 3.4 bye It yourytnon program cannot fin the requester! module ) This screenshot shows off some ofthe Python code youl find Inthe _Init_. Dyile of the NumPy Python 3 package Object oriented programming InPythen 3everythingts an object so beet rented programing pays a lay ole Ts kind af programming sa ery sell pra a care Your Ife cae because t keeps beth fata an cvien te same se, which Isthecbject Faces) Aationaly the deeloperis alowed to change the Implementation af an exiting clase ‘method without waryngbecause the actu! moiementaten doesn't realy matter as gas you Heep the metic ‘Yous ea lonedtoreurean bdetngcines aeerenta abiger one ting inertnce, Tesh yu ‘epi the atrdutes and the methods of me ormeecestingenses calles super clases inarcer trate new ‘ame—the new cseean have fecitona sets ane metas The food tari that yu ean atthe Implementation of sore othe methods ofthe super asses needed ile heeprg the implertetation ofthe rest ‘wil generate the folowing kind of errr message: pythons useMyModule oy ‘Taceback (mest recent call las: File “usaMyModule py’, ine 1, n module import mytedule ImporErrr: No module named ‘myMedl! Python doesn't look everywhere on your Lnux system for modules. The folonng Python code presents a ‘technique that allows yout dynamically adda directory to tholist of crectories that Python uses to look for medtules and pacsages: import sys €iatath nt inyspath: ‘sys path.nser, fps) Adora you ean nd the ul path ofan imported module or packages flows 35> import mampy >>> printinumpy._fle_) ‘arinfprhondist packagea’mumpy!_init_ yr This hagpens because each module has 2 fle variate thats see te hold the relative path from the current wortang dectory, About Python packages | package might ok sir toa mosule but t's aiferent beast a packages acalection of medules stored n iferent ‘Orectories ara as reauta package has a erarchy Adkitonaly. when you importa package ony wha s declared inside the _In_py eof that package is erect vsbe to ‘terest ofthe word Asthe documenition of Python 3 slates Technical a package fsaPyton module wth 9 pat_atrbnte: The _palh__atinbuteot a package i used during the import poses ofits subpackages, The mage (lop preious page) shonstheroot rectory of the NumMPy age ae wel ae the sontents os polynomial =r ‘andom subrctories. The noxt output ws that Name ‘contin ait Fas ned abcut 2 rete $l AR sulibpvthon3 ist packagee!numpy | we 10797482. 55087 $ ind fusibvpthonadist-packapesimumpy “ype d we 1 al 67 As youcanrealse deopigsucha powell ad handy cage rqures alt f wore Taseeersnot (seb) shes aportof te Pytnen code tthe _iit_py tie othe NumPy package However decuesing more deal about Python packages is beyond the scope of tis tutor Python 3 namespaces “Anarnespacelsatechige fouré n mary proeramming larguages for generating containers that map rams to ‘objets As you ight expect. each namespaces iolted from the rest ofthe word Put spy. namespaces alow you to use the same funeton, variable or elass name ralile times without causrg any problems. ‘when Python searches fr sombng. eat chacksthe local namespece before pong to search the slbal namespace. However you cannot use same varieble nam multietimes nthe samerarespace—a5 yu ca jabobiy nage his wit ether cause a conti or be the toot of polenta bugs. Thies can be very icky wth namespaces yo can se by looking athe fwing Python 3 code name the ame ofthe methees the sae Glabal=2 38 | Coding Academy 2018

You might also like