You are on page 1of 26
Beginner's Python Cheat Sheet Holo word prine("velio worse“) Het word wih vores og = eho wort” prince) Concatenaton (combining tings) pena velmtciny pelt fata nee) Make a st bikes = ['trek", “reotine Get the fet am iy ale ‘First pike = bikes[9) Got tho lst tom in ‘ase pike = Bseee{ 1) {Looping trough st or bike in biker pried ‘Adding toms to ast sues = 1) bikes. apbend(‘tret”) bikes: appene( neon") bikes: arpens glam") Making murda its ‘saares « (1 fork in earge(t, 38): ‘aunres.tppendcet=2) List eompronencions sauares = (x2 for x An ronge(2y 18)) Sting ait finishers » (san, ‘bob, ‘a6a", ‘bea') ‘Airsttua © Finlehtest3] Copying a it copy_of blues = st: ed ‘Making a tuple ‘inonstons = (1820, 1080) ene ‘Conaivaral tests ovals fan s frester thon > Rereient toe or eqat tos Condional set wa ite veree” sn eieoe *Soriy" mot in bikes ‘Assigning boolean values gue active = true eon att = False A sino test AF age 3 38 ‘ranc("vau can vore!”) itettobe staiomons SF age ce Cicket price = @ out age cithet price = 18 elses heter price = 35 ate ‘Asimpi dictionary lion « (‘eoler's ‘green’, ‘points’: 5) Accessing avalue Dprint( "Tee alien's color 4s * + alien color’) ‘Adding new key-value pair ‘alienl x position’) Looping through alhey-valve pics ay oubers = (erie! 47, ‘ever’: 4) ‘orang, nuveer in faw-nunbers.1eens(): Grint(nave 6 Roves = atedrunber)) Looping through alleys ‘fay uers = (eric: 17, “ever? ay forane in fa" sunbers.4@ys0 felne(nare +" loves = munber*) Logping trough athe valves “or ruber in Sovcnnbersvalest. Peneietrmecey st Is a trite’ romping fr a vaue nano » tnput("wnat"s your rasa? “) print-Aellog "+ mame °1*) romping for merical input see + Lnput (How old are you? *) See = inte) PS = Snput(ahat"s the value of ai? *) i = Hloat{ tp ‘Acimpio whie loop urvent value = 2 he’ canrent_value ce 8: ferint(current value) Ehrrentavelue t= 1 ting the user choose wien to quit ore Cie me Ie Saute: Tsp = inpur(runat’s your message? ~) Creating a dag cass lass 20 -tRepresent @ dog." ef _init_(self,_ sane) Setfnseisitte aoe objece. selfinore = none printcan) print(setvnane ¢ ffs siting.") sy. » Boe"Pes0") ringaycdog.nane + * 45 4 pest og!") ‘Asal uncton fredeesit) fer grwe were Inheritance poy time grestiog. f ey prine(tteltot") He opresent 3 es8ren 69. sreetwer() f init_elf, ane): Passing en argument weifntaltee the soe supar()._init_(rame) areh( 3030 eeeSinelate, searching. prlnt(self-nane #"* 15 searchlng.*) ereet_user(" Jesse") Defaut values for parameters le make. pizza(copping="bacon"): wake single-topsine pee prane( ‘have a" + topping * = p2z31") ake pisza() Make_pleza(‘pepoeront*) ny.soe = SAtoeC‘Wiltie") otuining avave 2 youre learning to program, ts helpful to tink about the reah- wore projects you'd kof create. ts 8 cod fabio keep a ideas" notebook that you ‘an rler to whenever you wan! fo stan a new project. you havent cane co areacy, take a few minutos and descr tes projcis you'd Ie to create son = 936_nmbers(3, 5) riot sai Reading a fe and string its foes ‘lenane = ‘sidohartta, xt" With apen(Fbdenone) 25 File object ines = filevooject.rexdliaes() peinei dine} Wiring to a fle ‘lenane = "journal. txt" itn apen(ralenane, "wy ae Flle_cbject: "ie oujectanrite(“E love programs ‘Appening to Mle filecane = “Journal tx with open{Filenone, "a!) 2s file object: ‘eer objectswrite("Qrd love naling. gates") Caching an exception Drone = "Yow mony e1ckets do you need? ~ in tickets = inputtoronot) ‘nae tickets = Ant (oun elekets) ‘except, Valuer Span eae ty Drint("Yeur tickets ore printing 0.7) I yeu havo a choice botwoon a simple and a complex soluion, and bot work, uso tie epi ealulon, Your ode wil be easlr to maiman, and vik be easler ‘or you and others bull on that code ater on. (More cheatsheets ovalable ot chmatthesithublolpee! Beginner's Python Cheat Sheet - Lists Cinna ‘Als stores a series ol ilems na partular order. Usis alow you to tore sats of formation none plac, whether you have uct afow tame or miBons ‘fies. Lists ae one of Pyions most powerful fealures readily accessible fo new programmes, and they ie together many mporantconcepis programming. Defining alist rent Preemie reine taar ey iareaet ss Pape ‘Making lst sore = Uva", eco pacer Dee ert ree EL aes bere pereigeed Getting the fst First_user = users(0) Getting the second element secondvser = users{3] Goting telat element mevest.user = wserst-2] Peas tied onal CEs ernest ery ‘Charging an element sersi0] = “yale Users[-a] = “Fone reed apseetiny ep repr Eom severed ‘cing an sloment io th ond of the lt users. append( any") ‘Starting with an empty ist Inset elomers at a paicular position serscinsert(3. jee!) 0) Removing elements eee ee eae Gaeta te Deleting an element by ts poston el users[-1} Femeving an tom by ts value ers. cerove(‘nia") eee etn ent eed arene eee ey ere reenter tres Sack By seta pon) fetus he at ferent te Deine eee ee Pop the lat tm rom a lst rost.recant_veer = users.2070) Prine(oee racent_uter) Pop the fstitom in ais) ‘soet_ueor = utore-pop(@) peintiFiest_userd Listlength eee eee Find the length of alist rum.users = Len(users) Print ws have "+ FerCnum_asors) + * users") Sorting alist oer aereae por eee eee ead ‘Sorting 2 it pormannty sees, sort) Sorting list pomanenti in reverse alohaboicl ordse sens. sor(reverse=true) Sorting 8 lit temporary print sort Print sortedcusers, reverse=true)) Feversing the order ofa tist sore roversa() hierar ate t eerie ere eee eee Tete) Printing altems in ist, for user in users: prine(usar) Ping a moseago foreach om, and = eoparaio message sterwares rint( "Welcome," + user + *1*) print Welcone, we're glad to see you oll!*) Python Crash Course Lee ‘Covers Python 3 ond Python 2 nostrchpres.compythoncrashourse ‘The range() function Vox can use argo incon to wrk wi 2 set of ere meter Irae eres Peirce rebate reprise ale tale ed Cae a) Priming he numbers Ota 1000, {for rusher in ranee(1801): rine (nusber) Priming he umber 1 to 1000 for rurber in range» 1061): pele(nsnber) ‘Making let of numbors for 1 10/2 milon rasoors = list(renge(2, 1600003) Sneed Frncing he minimum value in alist, ages = (83, 98, 66, 12, 85) 4, 35, 82, 2, 77] soamgest = adniaget) Ficing the maximum value ages = (83, 28, 66, 12, alee Ventanas) Fring the sum ofall vale sues = (93, 98) 66, 17, 85) 4, 354 82 2, 77] tStan years = bun(Sgte} 438,02, 2, 271 eras See eer er ered Bee rrr metre ard Poe amen tenets Perera reac eer aed maria ements ‘Gottng the fst tree tore Finishers = (kat, ‘obey fintlies # Findéneret: 31 GGottng the mice threo tome ‘nisile_ehres = fanssrers(2:4] ‘Gottng tho fat tro toms last thvee = fintshers{-3:) oda" “aus, "208"] oom ert ett re era Ten erate very bier raeerntinse cicero eer Making a copy of st inishors = ['kat's ‘she's ‘ads’, pis’, "200"] Copy of finishers = finisbers(-] Perens eee rer erent Pe ee ar oe Ere Sty manent iy eet eee Peretti eens eiprahonaione utorrent eat eter art aaron Using loop to generate ais of square numbers sauces = 0 Using a comprohorcion to gonerats ait ot equare rumbors fuaees = [1072 for x An eange(ly 3) Using a oop to convert it ot names o upper caso. res = [Nay "abe", "aga", ‘gus’, “z0e"] ae le “pper_rones.append(cane.upper()) Using a comprehension to conver a listo names to upper case rames = ["ka3", “950, "960", ‘gus', “z0e"] upper rons = (nane.upper() for mane Sn nants) Eee oe + Use four spaces per indentation level. + Keep your nes to 79 characters or fewer. 1 Use singe Bark Inge te groun pate of your program vsuay ies aoe etitare eine eaaE Pecieer ree a meyer ied Caan es tt ee Sea erat eee Eee rea aneera eer ieee oer) Defining a tiple Anerstons = (88e, 560) Looping through a tle ‘eint(dinensson) Overerting a tuple incrsions ~ (890, 600) print(ainenssone) sinenstons = (1200, 908) Ea eretetenre forenr neeteteter ne eee eee Pilea ad eee ae aa ee Renee eo eee cera Bold it and pr he ors in te tt “0 pent ths pent haste) Spent pss pe ssa) on cog 30 cogs: print( "Hello * + dog + *Y print("l love these coget") ) printc*\ntnese wera ny Fret two doses”) Bid ioes = doest-2] ‘for dog in 014 do print (snag) ogst0) oes ranoret peso") printcaogs) Beginner's Python Cheat Sheet — Dictionaries rome etaberte renee em Prrertimnnteer cesar ane ty ieee eee a eee Earner enenhene aan) eer ec ee reer ee Fes ths neo Python's dctonaries alow you to connect pieces of related nformaton. Each piece of rformation na ‘otorary sited se & Key value pa. When You provide a key, Python reums the value associates With hat key. You can bop through all te key-value pais al the keys, oral the values, Pennie) se uty bea re ed etd eee EA ie ieee Een Making a deionary atten.@ = {"eolor": “green, “punts: 5) eens ot eee eet Perera eer eee etree ie Se a pera L Pree eaetet gettin ac ead erent erent Bere eee errr ‘Gottng he vaus associated witha Koy Altorie = {"eolor": “graan', “points”: s) print(atien ¢ Srint{atteret soins?) Going the value wit get) steno = (eotor": "green st ten_cotor = alten 6.get( cater") SLisrcpodnts = alien Grest( podnte", ©) print(stien color) Print( aiden. pete) atsen.s « (color Ae Lien chlor) = ‘green’ Stiercelpoanee'y = 5 Tels ene eee era) Pare ead basi ot pop seinen opin iaran Mocttyng values ia devionary ier = ("colons “green, Drint(atien.2) “points: 5) the alton’ color and potne vate sealer’) © ‘yellow’ Loman) Perce painter (oeec ery meg paar eens Deleting « key-value pa Slee = {color prine(anien 2) een", “polnts': 5} ed aiten print(atien 2) inte" Visualizing dctionari Duets Logping tough a key-value pai 1 Segal s foros anne sow each person's fevorive language. ray Language in fav languages, teens): Brine mane 88:9 5 Yangaage) Looping through al the koys Srine(nane) Looping trough athe valves 4 Show ald tye Languages that hava boon chosen. for language In f0 prine( tage) Looping through al the keys in order 4 Show each person's favorite langage, 4% onsen by the person's rane {for rane in sorted "ov Languages. Keys()): Drincinare e "1 "3 Tonguage) ues): Dictionary length eres Finding « dcionarys length rnun.responses = Ten(fov_languoges) ey ‘Stonng ictenatea inact # Seare wasn an enpty 14st ‘Stoning lets ina cictonary {Stora multiple 2anguagoe for each person. teers = 1 fav languages. = ¢ | eke a-new user, and add then to the JIst reuse = veiese's Tearsea", > ’ 4 Sov all cesponses for each person. ‘or ney. Lange in fae Languages. tens ()¢ printnae 9 2 7) ‘for dang’ in Lange: prin" 2's dang) send. apenacnes user) £ Woke another now user, and séd thon 3¢ wel. ery dictionari reer 2 ser$, apend(nen user) 1 Show all inforsation about each wer for ky vn user ict. ttens(): prine( ess" sy) pane) ‘You can also doting a ist of estonaries cron witncut sing appends) 4 Define a List of users, were each user fas represente by 9 dictionary. foneet * a ? so ram are asa b eatin lo eel sey = + Gull-nave o- eser dict Nasty Aoeation ~ user diet Location’) prine(-\truld nan 7 2 print(-\tocatlon 1 futl nana.titie(9) wy igeation eiteG) for user dict in . print(k + pine“) ‘rosering te order of keys and valuce from collection: inert GrdoreéDiet # Store eazh person's Languages, heaping 1 tack of who Feapided first Say languages = OrderedDict() ‘Fav anguages(‘@RiI") = (python, “Raseelt"] f Display the results, tn the sane order they Fortine esp for tose ttn) ‘Arion aliens ‘wien = 0 4 Yoke @ mtT2ion green aliens, worth § points 4} "seen fave thes all stare in'ere row. foc‘ alenvim In range(aeeasee) tewslien =") temcelten{colon") = “green ewalten{‘solnts'T = 5 trex siten{‘*"|"s 20 * aiden rom hevcaltent'y"] © @ ‘Tenet Sppena (nae atsen) Prove the List cantaine a million oliens tuncaiiens = len(sttens) Dprine(Mumer of alsens created”) Print(nun aliens) (More cheatsheets evalabe ot chmatthesithubolpee! Wee Beginner's Python Cheat Sheet — Testing equally and inequality ‘Smpio tf satemont Tecra) and While Loops re old enaigh to vote!) HW siatomenie alow you to examine the currant tte ‘of program and respond appropraily otha stato. Youcan write 2 simple statement that checks one colton, or you can create a complex series oli ‘statements tat deny the exact conditions youre icosna for The i-ettelse chain ‘While oops nan along as cetain condtons remain ‘rue, You can use he loops fo let your programs. run as ong a8 your usere want them fe Checking fr eat Asnoa ‘among yao saver Accu ens! sing oro check multiple corltors Testing ita value'sina ct | Python Crash Course Covers Pt While loops (cont.) While loops (cont Tectng ia valus 6 notin a et Latng 0 user choose wren oq Using cain wa kop teioecven eon olay!) verso * a Checking ita ist is empty I eenseeste laeetCereseh Aintte troe ries <0) i : tue = Sooo Eee ee seetiaaO)) Using aay Se PE (pie oo as tae Senet Af messaee ‘Accepting numerical input ales nesconak noe = irene ad are yn) Using break ext oop annie eop Print("\nvow can't vate yet.") ‘Acooptna inguin Python 27 oar (sso rou Ptr 2 Ts ton ete ain = ‘Siro ptt re ces Py 3 Removing all cas from a Ist of pois pets = ('dou", “eat, "dog's “fish, “eat Cees facbie's “est printtoets) Counting t3 5 otesronove( eat arcane = printipetsy Print( current. numer) (More cneat sheets ovatabe ot chmatthesgithublolpce/ eens foranes Beginner's Python x "i Cheat Sheet — : : oumng a eai va aU lara (ola) Te full rano(fieet, 1360) ‘one specie ob, Furetions alow you to wee code brine nuit ‘ee that can then be run whonevor you need fo Fetuming & dictonary ‘Sccomplsh the same task Functone cantata i0N® dexertbe_pee(“mancter“, “harry Information fey noes, ad relurn the invomaton they esertte-set{vaoe's wit2ie"%" ‘ererate. Using liretions ellecively makes your wild person(firat, Last) Droaramo eas towne, toad, tot and 1 Using keymorserguments pet(aninal, nate rson = first, last: ast) Pome nrorsation sect» bet ete a vane musician = bulld_person('sinl', ‘hendedn') IME, cate bay"? aiming @ ovonary with optional vedios et oul personctirst, 12st aking function print vetior erest_oser() def describe pet(nane, aninala' doa eiitimelcian erik me pane FS Using Nono to make an argunont optional de describe petCeninal, rani neCcAnt hve'a s aninal 25) Python Crash Course Pecan Print("Ite mane Le * 4 none + °.") Covers Python 3 ond Python 2 Fe see erences) ezcrabe.pet(‘naneter’, ‘narny norarchpresscnvpythoncash deserdbecbetC'snake) Parra serranas = [onaonan’, “ty, rect users(usernanes) ‘Allowing a function to medi a ist ‘iy semanas aie reso ea kreten og The gris ere ante oco its od 60 print models(unprintse, prin Frssa print a set of sodels." vantte tnpri sted: current model = unprinted. 090) fpeine(Praneing ""t currart mee) Printed: appenet current-noas]) ‘argor'] f stone som unprinted dostane, ond pret each of th Unprincec = ("prone case", printed = 11 Print.rodels(ungrinted, printed) print(“\rtmrinted:", unprinted) Print(-orinted" printed) Rass ten road alt ge The lor eae he ame Pape. oe eet et print. ocels(unprinted, printed): Binge pein s tet of model le tnprinted: Current model = unprinted. p09() fpelnt (Printing “> current me) ‘printed. appara currant acel “pondart’, “eing'y f Store sons unprintse dociane, original = [phone cose"y ‘pendant, ‘rin printed = 1) print modeis(oraginat{:}» privtea) Prine" \rorigs etna) Print(-orantee™, prantea) Wheatus Collecting an artivary numberof arguments ef make pizza(size, *tocpings) ‘opptngs: Sy Ropotne) 4 hake thee pizzas with oifferent toppines hia puzza['enall", "pepoeront Make-pizza(*erge", "bacon bits! have-pleza( medion, "mushraons" > ontons', "extra cheese") ‘Coleg an arbivary nub of Keyword arguionts def tulie_profite First, tase, userinfo Tredeat's Hest, ast ‘id ey other bays and values. for heyy value in Ueer toto. stene(): brofile(keyl = valve sora = baile profile manic", ‘peatione paris" prknt user. 0> brint(user_2} teorie", lelde"chendsty") icin core eine\mencing 3 * 4 et3e 6 pasa bein Topatnes" ‘ae matry nes or Ero fac nie ree ariade hepexran le Amport zz piace. noe pi220( ‘nods lize. ne pizza(‘see1t Importing a speci unction {Gah posed noone asin oa Se ‘fron piazza ingort make pizza sake pizza ‘nediun’s, pepperoni!) (ce_plzsa(-enal)", “aacon’, “plnaapele") Giving a module an alias saport piss a6 p rake pi28a( neal’, “pepeerons”) noke_pizeal' snail", “pineepple") Giving a function an alias rom plaza inport make_plzea as mp no‘ nactun’,.‘pepperant”) mot'snall",“bocen", "pinesople") Pee on ee eee ee ‘tron prin ingort © (More cheatsheets avaiable at chmatthesithubolpee! Tel an eee) a) Cheat Sheet - Classes programing Classes represent rea-wors things You want 1a meda! your programs: for example ops, cars, and ebots. You use a cass o make ‘objects, which aro spec instances of doce, care ‘re robot, A class dofmoc th goreral Berar that 2 whol calogay of objees ean have, and ihe Information fat Can be assocates wih ose objects Clzsaee ean invert rom each other you can \wrie 2 ess that extenas tne unisionay of an ‘exising lass. This slows you to cove eficienty for a We vtiely of sustiors selffuelievel = 0 Coating an object trom a ciase Aeseesng attribute values rint(ny_ear.nske) brint¢nj-rar adel) Caling methods Creating muitple objec en ear tayersy 7610) Win a mein to update an atrbutes valve \Witing a method to Ineromont an atirbuto's valve super()ee date Gente, moasly Soon ‘Adina new methods othe chs class charge the ventere Srincectre while te fuLdy charged.°) Using ene methods and parent methode sy ecar-charge|) ier Python Crash Course Covers Python 3. Python 2 ‘Overring parent methoas ‘class Eectrd Seifibatvery charge tevel = 100 Drint(cThe vehlcle Us fuly charge, Using the instance sy scar = ElectrSeCar(*tesla", ‘model »', 2036) sy scar.charge() Prine my ecar-pattery.got_range()) ycecarcdrive() ‘Storing clases ao “orRepresent gas and electric ears lass cae) tecersecar(car): A simple model of an electric car.” snips poring ndvdual ass0s rom a module ‘fron car import Cary Eleetetecar sy beetle = car("volhsuagen', ‘beetle, 2616) pestle. 1131 fane() Syrbeetie drive) fgg < Bestriscereate, “nour 9", yrtesia.cnaree() yikesiadrave() Importing an entre module ¢ vanlawogen’, "beette’, 2036) beatles Fill tant) syipectie seivat) Syxestelanive() lnmporing all slaseos tom a mocile {Danton at ecomze we ou So) ‘fron ear import * ry beetle = car(‘yolhsuagen', “eetLe', 2016) ‘Cleeee choulé inner Hom objoct, lace Classnone(odfect): ‘Tho Car lass n Pytnon 2.7 laos Car(abject): ‘Chis class._int_ method i dierent lass chilaciasstiane(ParentCloss): aor inst (crit): Sioer(lessNene, se1f)._snit_0 “The ElectieCar cass in Python 27 clase Electr (Car): ot inst (aol, make, model, year): Giper{Bisctriecer, Seay. “Hah tnoke, meee, year) ‘Afiet of rental cars From car taport Car, Electrietar 4 Poke ists to hold # Fleet of cars. fee tleet™ 1) Slectrie_feet + 1) 4 woke 800 gas cars and 250 electeic cars. for in range(s00 far o"Car( ford", focus", 2836) fas fleet, aopendicar) ton he anges Tear = Electetccor(‘nisa Slzetese_fiset.appone(ecar) Fan the gas cars, or carn gas_fleet: ear. tak) cars chorget) + “leat, 2015) nd charge electri cars. int("Ges cars:", Len(gas Aleet)) prant(veiectrte cars", den(eieetric.feet)) (More cheatsheets ovatoble ot chmatthesithublolpee/ Beginner's Python Cheat Sheet — Files and Exceptions mat are "Yur programs can rea information n om files, and ‘hoy San wre data to lies. Reading trom tes alows you to work wih awd vaity of nirmaton: wring {oles alows users fo pek up where they lot he ext ie ey run your program au car wit ont 0 fies, and you can Store Python structures such 26 Tein data tls. Excoptions ate special objocs that help your froglams respond to eros in appropriate ways. For ‘Scamp if your program tris fe open a le that decent exe, you 6a uso excoptions to deplay an Intormaive oor message instead of having mo ‘rogram crash Perrone oacing no by ins ‘irene resotmanar aie ot orenal Storing the thee in ast ‘Oporing athe using an abeouto path sdth open path) 28 Fob) 1Shon 2 Fon} reaelnes() ‘Sparing ate on Wows Todos emt ee omar ses ncorecty deine (ine-rstrd90) evant path) 25 ft fsb} reaelsnes() Wiig o an ety fle \Witing mutt ies to an omy te Handing the ZeroD\iionEtrr exception Baer el agers oe Yeti Appending oa fle we Henating to | jeNotFourdénor exception iteiopenCt-pemey estat ene aby rea Tox = can't Find Fite {0).*.Fornatl taccase) Strita( i ais Love working with data; nm") ‘ we nacing sppstas wellanty | e#cert Knowing which exception to handle Opening fle trom a subjolder tantaalen/ebieer st Python Crash Course | <=stt fn reaalines( ‘Covers Python 3 and Python 2 meer eet aera nes rer Ary cade at Sepends one ny lock tig poe erereyeosne ots Using an else block print("enter two nusoers. 1°12 divide then X= Anpat(-rirst nuaber: *) ¥ 7 Anpst(Second minbers resuit = 1neGx) / aneiy) except Zerabivl stoner Prine( "vou car's etvige by sorel) tse! ‘prine(recute) Preventing crashes from usar input Ceuklamen ten tos def Se ee Nando te owarracsuly adhoc rn. "A siaple calculator for dlviston only. rine( “arte two numbers. 1°11 sive thee.) rint(ventes "q" to cules") vite Tove Mo Snpst(\irst sumbers °) ay! ‘break y= Input ("secons number: yee wy: result = Sne(x) 7 int(y) cexcopt Zerebivistoneeror: ePme an'e lee by ser) Print(resute) Pere eee eters eer ee Serre ed tae Peet ee team rere povea ened (1s oy ta coer ero br sos, er eer ene en ncaa aon os eno Ceo ny er ern) Ree eee ane re Psalter reba ret Pari ra ‘Using mo pass statomnt nan 09 block nanos = [‘alice.tet', “sidshartha.bet's “noty_diek. txt! "Lette women xt" foe fnane inf nanos Wheport the Tentth of each File found. ww with pen(F-nane) a5 #003: ines = fob} reselines() except Hicietfounderror! pass a Tn-Lies = TencLines) mks Hf) hos (2) Lines.". format ‘Same, am itoee) prictince) end Ce een rere Pereira ene nner Peet ruses peace or eee ie ee ener UE ESD Pe eM ened epee eee eerie oad aon Dot use bare except Books > saneentng except pase Use Exespton insteas a 20 sovetning except Decent ont Printing the exception yt 1 Do sonething ‘except: brception 36 6: rintie, typece)> Pte ea eee Peet ores Pe ce etd Ac dnet therein chias pace t H oateneneer) Cecio eres Pee eee pee ye ee bee bre reer etree Using son. dump() 0 stove data restore sane nunbers,*=" mport json mbens = [25 35 8, 7, 4, 18) ‘ilenane = ‘nomoers Jeon" tn apen(Fldenane, "W') as £ obi "on-damp(nombore, #203) Using jconosd) to road data soLead sone previously stored numbers Amport Jon ‘Filename = tnunbers.js0n" eH open(FtTenone) 96 F003 Teabers = fson-Lsed(T-ob)) print (nbers) aking ure the Stored data exis Inport Json F.pane = ‘numbers json” iy ‘wth ogen(F name) a8 Cob Ter = json" 1c20(4-003) ‘xcept Heo founderr Sen on) frm trae) Beginner's Python Cheat Sheet — Testing Your Code ‘When you wie a fneton or lass. you can also ‘we tests fr tht code. Test proves that your You confidence thal your cove wil work eorecty as moro peocle begin fo use your programe. You can ‘ico ane atures to your programe and Know That you Navent broken easing bara ‘Anis! verifies that ane specific aspect of your ‘code works a fs supposed to, A tect caso © 2 ‘olecton o unit tet was very your cose’ ‘behavior na wide varety of stuatons fete fall pane stele0) ing ho unetion| ran Full ames import get full nane Janis ~ et full name 'Janis', "Joptin’) print janis) 09 = get Full nane"BoD', aim’) brine bet) Testing a function (cont. ‘Buaking atsteaco wth one unk tet Totes ata ase rae acne fa tet toe ‘tee ocate and Maen htop cee Sove the aot ot naman pore vattcest from full. pases Smgort get full mane lass ansTestcase(unit est Testase): eeSete for names se} .opsertéquoh(Full_aney Sorts Deakin’) unseeest ming) Ranromaten eo eee ie mesmatsacennemaiiame a=: Moding the function Un moa peru rma) £0 ges ct mes. Wet dk Si ma ens eneng bona et get full nona(f3rst, miele, last): turn» Fall nase, sullinane + *(@) (3) (2)"-Fommat(rirst, idle, ast) ‘retumy full nave t8t120) Using the function from full_eanes import get full.nane John = get full nane( "John", “lee', ‘hosker") Princezom). via = got eut1_nana(‘4avte’, “iee", “rotn’) prinvGeviey Wa) ‘Running the test. When cre race {9 tatu your sng (BUS fs yo ws ha cangoryco ae S03 Esau cost puree dant ‘ese names Tike Jonis 3. Traceback (gost cecent call asi Fite "test full naes pj", 1300 28, ‘1 test flrstatast opin") sypetrrors” per fu12_pame() alssing 1 required positional orpinents ast FASLeD (eerocest) Fina the code [Wher st cde rod su te ses aga Gc mate be sats rh as [eornowcom Howe car mane Pe mae ate opr! ama(flest, last, midéles"”): "all panes ulLname = *(6) (2) (2)*-forvat( Leste isosia, ast) case: Full pana = “(@) (2)°forest(taret, ast) return full nane.title() an i test in eee ‘Adding new tests “Tesing mike nares ‘nove Sur a gre vi rane) on tanga ona Latta waa rsa eaneoes a nport unittest ‘on Full-nowes Inport got Aull pane ‘lass, yaesTestcase(untttese.Testcase): ettests for nones.bye" aot fleet antl) fullname 2 get-fulliname( ha, “septin") self.asserteqval full_nane, Sante 2eplin") se mide): act anes Lite Dovid ta foitnae eet fal poe salfcosgrecpenL (fil meres “Davie Use Roth") unseeest.nain() uring th ists ‘eo de npn! ray abe an 2 tests An 8.0005 ssserteqal(s, 9) SSserneteqai(s, ©) erty hat xie Tua, ors False sezzesteueb) StaerttalseG) erty an item i nas, or pt in alist assertm(iten, 11st) SesertietinGter, List) ‘A class to ost ‘Sie easton “lass Accountant manage Bank accoune*** (self, polance-d): Angort unittest ‘hom accountant Import Accountant ‘lace, Teseaccountane(uniteest.Testcace ef test_inteial patance(selA) W befaute salence should Be tees accouneaneQ) Selfransertequal(acestalanee, 6) 4 Test on-default balance. deo aceountsne(198) Selrcassertequat (ac ances 100) amittest maint) Funning he est iene ‘Using setup) 6 support muti oa invort unittest +7 acceuntant import Aecountant as 3s TestAccourtant(unittest Testa) ef seup( sent Selfrace = Accountant) ef est_inttiaL palance(sel) ‘boyautt salance shoul Selfsassertequal(serfacc-balonce, 9) Seq Accountant(309), ‘Sele. atsertequal aee-balancs ot set daporte(salt): Wrest single depesits Sexe. ace.sepesse(i09) Selfcasserteqal(self.accabalance, 128) 4 Test multiple ceposits. posie(s03), “daposte(300) delfasserecqual{seifsace.balance, 300) ef test uithdronal( sel): sn(300) Seif assertzqat(sehf-ace.balance, 982) untetest.maing) Running he ests (More cheatsheets avaiable ot chmatthes ithublolpec/ stella ee Unel A) Cheat Sheet - Pygame hat is Pygi Pygame i a ramework for making games cing Python. Mating games ic fun, and ts agro ay 9 foxpand your proglamning kis and knowledge. Pypare takes cate of rary ofthe ower evel asks in bulldeg games, which lets you focus on the aaporis ot your game that make Xntresing Pygarne on unux Pygare 09 08 x Ts amano ous reverent non 3 Bosreeoee See tct Srromnepraanettnnaty a ne te pte ian at mates fourrin iyren Ronee aarti see aa om ese wat, o pb © ran) Prone Testing your instalation rg uta gol sy es oar at ‘An emply game window def run aavet) Fereen = pp display. sat noce((1200, 499) a) Soting a custom window sizo recap tree) trator opt st a es the crear = pgs display. set mede(screan din) Seting custom backoraunscoler Seer (Getting the screen rect abject Sear navn ster sec wo cnet ence 9 8 Ro sates th con Finding the contr of tho eorson Iarouec narrator oboe wiser he arte Pygat ‘Usotl oct att aay lave tect Pere a a grb of attest iat wber'ssonanrg sfc nd sae me poets Tes (Fa Sri ss are Creating act object Yaean rots 0S sraen or xanga ra ct ‘ijt fied mean pres sin gs To feet ths hes eccrine core en tec Stent oft" a ep tact bee ee Sone tr wane chen th tegen neh he uoneocr wilet_rect = pesRect(200, 109, 3, 15) color = (200, 198, 106) Losdang an image ship = pa: tnage.load"imapes/sh19. tmp") Getting the ret objac rm an nage ship.rect = ship.ger,rect Postioning an image ‘em 2 nt pton on iage raves aa! on be Fontone Sanp agate fERO Savor a scen ‘Covers Python and Python 2 Eo notarchressconVpythoncashcouse 5 ‘Drawing an mage to tho cereon “Sheen wih nf eed Tre nh) rams acte soe 680 ‘Sect sn aro to mage st nd apo ese uno Eoreansbls€(ship,.smip_reet) ‘The bitme0 method Gannon eu ripe etn wren eee. ant ‘Binoy Bored suiy sre wen ote ace 9S oF bisa sel6) Responding to key creases Pras non er sn estes aEYOONN een ay ire Sofa en pee aan sae faethe aay enon ae Responding to tre mouse button Fiing the mouse postion SSS ‘king a bution Ss mwa know te cari evr noc oh 2 ‘iron eet caaosont oedema toe wer Es ata reo icing the moo ‘Making an ing a group ‘vane tal Bo psoas oa ep mt inet ho Sets. dak énan buldet(catO) ef spate set) aldets-addoew bullet) Looping tough the kems in a group "ape ratnansene at he moot ore taldet.crow bullet) Cling updated) ona grup Siegen poate pe ooh a ‘Removing an om trom a grou Perr Colsions between a singie objet and a group ‘espcoticony) ncn fee arated an oi. ‘ete Tce Ye es ova ner ene 9 epee Colton bean to groupe ‘ire fe con ret Senay Stang arate ecrime rancer tar hee cet ts caaeer et par retorts anata marr of oe pave cod ullets, sllenss True, True) score += len(collisfons) * allen point value ‘alee sor ream ton re ad ‘Ses ten on wi afateect ia Teton ‘Sete aoc ape tt easaga he et Pe Intenec seouates whe nage he mercer nese ‘rhe aso ant Senay beseolor » (239, 230, 230) (More cneat sheets ovatable ot chmatthesithublolpce/ Beginner's Python Cheat Sheet — matplotlib Wh ‘aia wsualzaton involves exlcrng data through ‘sual representations. The malo package helos you make vaualy appeaing reprecertatons ofthe fata youre working with. malleus i exam flexkte; hove examples il Pelp you get started wth afew sinple visualizations Installing matplotlb ‘matgot8d on Linux matsotie on OS X $ lp Anstan ‘matpotb on Windows nets com The Carragnyeaon fea Ther > ikea onan oweyeraipces Ise ecg reps nd ots ne Making aline ora itn nena ‘Making a ecatr plot ‘he ter inhi a nal salty es rargs(ne02)) Souares © [92 forse in e-values] pit show) ‘hasng tos ana labo, and cealng axoe onge(1609) Toveres = (area forex dn eoralues) 1e.title("Squore Naber ew) {sing a coleman ‘Sted cous atte lr eacnpore Te vate ua rsa fea fs pond th % block content K}O% endblock content ) The chid template The cnuyonpe wes Pe ottende) larg put [Reuatirye ne art ome hen cates no conr or Sy abcts debs nope 1 block content cn) ‘Dotring a moset wn 2 foreign kay Ertry(nodels.focel) topics nodels:rovetentey(Tarie) tect = nogeis:rextstel40) Petar selfs text( 50) + UBL paareia aoe ri(e's8), dessin rams"indas") SrMge seapece) (roctopde_fanaed Using det in a vow Ravibedeshaie inthe eran eww Sserangacartes Seay mpi Cag es oa need dof topse( request, topic_s4) Restarting the development serve Building a page Using data na tomplate ‘Chg orp’ tae sea acasegnry ore ‘muon nnn ave ndcsovy ines 2) nce ‘teria ina car a emanate nets 9 ese cae tea nt et Bron 1 block content Gefen entry sn entriae x} entry date added |date:t4 &, ¥ MEA! 9) entry. texth inebreaks 1) ce onpty 8 ee ercror 3 ‘Stata shel sseeion| ‘Aco9se date trom the prooct (More cneat sheets ovatable ot chmatthesithublolpce/ Beginner's Python Cheat Sheet — Defining the UALS noe irae nbs 2801 opin eg at sat es rewutney ter insers abhi: Te bomen oad ‘iow ore yg Django, Part 2 pees a es, ‘Most web applications need et users create enolate faze’! *users/Iogia. teal ‘counts, Th ots cers crete and wor wih heir Topi 3. ‘on data. Sore ol the data may be svato, ar un ews Logout vie ‘Some may be puaie. Dlangos forme alow cars 16 {nter and modty mei data. Teer 1 ‘The login template inlagm ante The orice sow hee Senne samme (Str tbe aur tr and'nan awe ssa ea ‘epee Sav the eg Making a users app ‘Ar ing ape Be ae agus! Ww NETALLD OS Mite eet tiosorie noth ors The form ‘arom sre ra Pn cee Including UALS forthe users apo ioe 1 ovum Tent negra (extends “Leorning_logs/base.hial” X) sleet lock 4 (r seey edntnstte.wes)), pie woage' ,"Sneludo Learning ioge.urte', tessa 9 eee Penaie =) Clon="(2 url “users:logia’ 8}*> {{ forn.on-p 1) alues?@k wed earning loesssndex" ¥)*/> (onc “9 ‘Showing the curent login status Yoscan moat te tseen/tpete ron wher teu Const taondin ee yore nafofe wor ant foes Dr nao wer ch ae ory ene ‘ie eras serra ee ‘ot serssersnee 9) Dopo alms yar goers Tete tee teed une heer anaes moe poor a hrofe"(X or welto, ({ aser.usernane 9). Sa hrefenth wri "sens Logout senate seatng_Loes:tndex’ 39" {% block content 8](% endblock content The logout view Totagese cect) Ann ees Bango logit) eter natn mdoss thurs he Rar page: Seth ¢ oases (9 Oe at ved ows po ‘evarse( learning 10g tndex")) Python Crash Course ‘Covers Python 3 ond Python 2 rnostarchpres.compythoncrashourse ‘Tho reqistor vow from ajongo.contrib.avtn import 20g ‘fm afongeccontrincavtntoma ingore’ formate valid furcrroquece.rostt ‘poceunrd foein request, auth > Tevmrso( lenrning log tex") ceteeak = fteres lh Feturn render (request ‘Tho registor tompiato reese ore pc he egstar nr inpraanh (8 csrf token iaaesen enna ‘Making atopic boiang fo a sor Sirtmscfcteietn yearend ec “Aer mz odh yah ned monte abana Yet rnd eos tocomen och est vor fron dfango.db import nodels seat gue ceotrti serene ipa bear late Topse(nodele.toded) ‘Querying data forthe curent user Pavan he wpe! sjashas tier stings, You sno te Sibi vee arcs ef) trenton phe cbsects. Falter onnecting data to users (cont ‘Restctng aecaes to logged n ueors ‘Sonenaans ate ty eer patredacers Theirs or there fags Sun npemsan ny spiogin reared dose ey tit i ci ol asa aes en aged ‘Moan spcerate pgs sew on xara oy te elegin requires teh topic (rest, topic 14) Seftng the redirect URL Theelogin ages aba sone vansnen va oe Aagpage. as Ptonng ins you're ean py Re [SOfgowaon aw wa yar eps Preventing inadvertent access ‘Soma uges soe saa tedon apart ne URL. You anche fre corer own eqn, a ete 404 over Fy oat Hoesen arse on ron ajorgo.nttp smart Hteptee Perrone le ‘eating a form wth rial cata These raat ints atom Meciying daiabstore saving Tiemmmercamifis ow yout ab rete (More cneat sheets ovatable ot chmatthesgithublolpce/

You might also like