You are on page 1of 26
ee st eompronencions sauares = (x2 for x An ronge(2) 18)) Beginner's Python Cheat Sheet seopaie finishers « ‘an, “t', ey ‘rst tua © Finlshtest3] Copying a it copy of bikes = ‘Holo word aT print( Merlo werte!") ES Holo word wih a varie neg = "Mello worke!” princieoe) Making a tuple CConcatenaion (combing sigs) ‘inonstons = (1820, 1086) pene velmtciny pelt fata nee) cd ‘Conaivoral tests ovals xa moremat x ina prester thon x 3 a2 Make a st foraqual tok >a? bikes = ['tree", “reozine nee as Get the fet iam valet ‘First_ike = bikes[9) Got tho lst tom in te ‘ase pike = bseee{ 1) Leoping trough tet ‘or bike in biter CCondional set wa te eree” in eieoe Soriy" mot in bikes [Assigning baolean values ge active = trve eon att = ale pried A sino test ‘Adin items to ast Fone 9-38 m sues = Prine > bikes. apbend( trek”) itettoe stiomonis bikes: appene( neon") 350 « bikes: arpem "elon" eee Ticket price = @ Making nuredica its euis age ca thet pce = 30 ‘squares = (] i for sin rarge(t, 11): ee sctoc price» 38 {auaroa SppeeaCer"2) ‘Asimpi dictionary lion = (‘eoler': ‘green’, ‘points’: 5) ‘Accessing avalue Dprint( "Tee alien's color 4s * « alien 'coler’1) ‘Adding new key-value pair ‘alienl x position’) Looping through alhey-valve pics ay bers = {erie!: 17, ‘ever’: 4) ‘orang, nuveer in faw-nunbers.Leens(): Grint(nave'¢ * Roves = atedeunber)) Looping through alleys ‘fay ners = (eric: 17, “ever? a) for'nane in fo" sunbers.4ays0 felne(nare +" loves = munber*) Logping trough athe valves “or tuber tn Sevcnnbersvaleste Seneietrmecey st Is a trite’ romping fora vaue nano » tnpue("wnats your nana? °) print-Aellog *'¢ name + °1*) romping for remerical input see + Snput(How old are you? *) See = inane) PS = Snput(ahat"s the value of ai? *) i = Float) furvent value = 2 ce she’ canrent_value ce 8: aeons ‘brit (current value) Creating a dig cs lass, 2x0) Ehrrentavelue += 1 ting the user choose wien taut rnenstseet A ef _init_(self,_ sane) TAC ete Saute eps iaptrunat'e your nerenge? °) printcan) SeSfpseisitte ap onjece. selfinore = none print( self-none +" 1S sitting.) ry.soe = Dagc“Peso") prin ay. raonssit) Inhertance lass, sdog(00n): Shapresent 2 Searcy 0g snare +15 a great dog!) ‘Assmple function et greet user): Slsplay slate greating print( "Helle!" erect ser) WF init _(self, none): Pressing an argument 2 "nitiaitze’the sardoe.* supar().init(rame) arch( 3030) eeeShnelate, searching. pelnt(selfsnane ¥* 15 searchlng.") ereet_user(" Jesse") Defaut values for parameters te make. pizza(copping="bacon"): wake sirgle-tomsine pice prane( ‘have a" + topping = = p2z31") ake pisza() take_plzza(‘pepoeront*) Potting avave nyse = SAt0eC‘Wiltie") 2s youre learning to program, ts helpful to tink about the rea wore projects you'd kof create. ts 4 cod fabio keep a ideas" notebook that you ‘can rler to whenever you want fo stan a new project. ityou havent cone co aready, take a few minutos and describe Wes projects you'd Ie to create son = 93ers, 5) rine sa) Reading a fe and string ts foes ‘filenane = ‘sidahartta, ox" With apen(FLdenone) 25 Fle object ines = filevobject.resdhiaes() peine( dine Wiring to a le ‘ilenane = "journal. txt" wit apen(ralenane, "wy ae Flle_coject: "ie oujectsnrite(“E love programs ‘Appening to le flecane = “Journal tx with open(Filenone, "a!) 2s file object: ‘eer objectswrite("Qrd love mating gates") Caching an exception fronpt = "Mow mony t1ckets do you need?” fn tickets = inguttoronot) ‘nun -tickets = snt(nun elekets) ‘except, Valueror Spanley Drint("Yeur tickets are printing 0") I you havo a choice botwoon a simple and a complex soluon, and bot work, uso tie emp salulon, Your ode wil be easier to main, and vik be easer ‘or you and others bul on that code ater on. (More cheatsheets ovatable ot chmatthesithubsolpee! Beginner's Python Cheat Sheet - Lists Cinna ‘Alls sires a series ol ilems na patular order. Lets alow you to tore sats of formation none plac, whether you have uct afow tame or iBone ‘fem. Lists ae one of Pytions most powerful fealures ready accessible fo new programmes, and they ie together many mporantconcepis prosramming. Perry ey ertT Preece t aay arias apc ‘Making a lst sore = Uva", ned peseomrere iSite eee En red poser ee her oe acme erated renal First_user = users(0) Getting the second element secondser = users{3] Goting telat element mevest_user = wserst-3] CET ens erie ery ‘Charging an element sersi0] = “yale Users[aa] = “rons ‘Adding elements apse erry ret) Geocoin ‘cing an sloment io the ond of the lt users. appond( any") ‘Starting with an empty ist Inseiting elomerts at a paricular postion herscinsert(3. yee") 0) Removing elements een ee a me ete Deleting an element by ts poston et users[-1} Femeving an tom by ts value ers. cerove(‘nia") rae etn ert een ed Parone ceo pe ree eerste tres Pad pren ren eta rare Deere eee ee Pop the lat tm irom a lst most.recant_ueer = users.2070) Prine(ore racent_uter) Pop the fstitom in ais) ‘ieet_ucor = utore-pop(@) peintifiest_userd List length eee eee Find the length of alist rum_users = Len(users) Print we have "+ FEr¢num_asors) + * users") Pures oer era por eee eee ead ‘Sorting 2 it pomanonty sens. sort) Sorting alist pomanentiy in reverse alhaboicl ordoe sens. sor(reverse=true) Sorting 8 lit temporary print sort Pint(sortedgusers, reverse=true)) Reversing the order of att sore roversa() Reser catenin Lee eect ratte Printing alltems in alist, for user in vsers: prine(usar) Pring a moseago foreach om, and = eoparaio message sterwares rint(*Melcone, "+ user + *1*) print(*Melcove, we're glad to see you oll!*) Python Crash Course Lee ‘Covers Python 3 ond Python 2 nostarchpres.compythoncrashourse Boon ein eee ed aera me eae Pricer etait sr fe epseriete altel ed Cates Priming he numbers Ot 1000, {for rusher in ranee(1801): prin (nuaber) Printing he umber 1 ts 1000 for rurber in range» 1061): pelae(nanber) ‘Making let ot numbers for 1 10/2 milo ramoors = lsst(renge(2, 3000003) nec Frncing he minimum value in alist, ages = (83, 9 66, 12, 85) 4, 35, 82, 2, 27] Soumgest = adnlages) Fring the maximum value ages = (83, 28, 66, 12, ace Vesrtaees) Fring the sum ofall vale sues = (93, 98, 66, 17, 85, 4, 354 825 2, 77] titan pears = bungee} 438, m2, 2, 271 rns ae eter ered Bee preemie matt ead Poe ner torent ern reac eer aera omens ‘Gottng the fst tree tore Finishers = ("kat ‘obey fintlines + Findéneret:31 GGottng the mice threo tome ‘nisile_ehres = fsnssrers(3:4] ‘Goting tho tat tro toms last thvee = fintshere{ 3!) oda", "aus", "208"] oom rte ett ee ea Ten rete yee Pier erntinse ice aera eer Making a copy of st inishors = ['kat's ‘she's ‘ads’, ‘pis’, "200"] Copy of finishers = finisbers(-] Perens ener errr eto ee ae are eee Ere Sty oanea rey tet eee Pearce reese pr puree eet eee eter arene Using aloop to genera ais of square numbers sauares = 0 Using a comprohercion to gonerate ait ot equare rumbors fgaees = (1072 for x An eange(ly 1D) Using a69p to convert it ot names o upper ca res = [Nay "abe", "26a", ‘gus’, “z0e"] ae “pper_rones.sppend(cane.upper()) Using a comprehension to conver a listo names to upper case fimes = ("sai "950", "960", ‘gus', “z0e"] upper ranes = (nane.upper() for nane Sn nants) Eee coer + Use fur spaces per indentation level. + Keep your nes fo 79 characters o ower. 1 Use singe Bark ing te grous pate of your program vsuay ae ai ole teaitare intent Pecieer ree rk ney oes leg te Cee re Let ee Seared eet erate enn Een rea aneeea eer ieee re) Defining a tiple Ainerstons = (83e, 560) Looping through a tuple ‘int(sinensson) Overerting a tuple incrsions ~ (890, 680) print(sinencsone) imenstons = (1200, 908) Eta eretetenre forenr ereete tener rae ee Pelee ee ae a ae eee eee cee Bold it ad pr he ors in te ft “0 pent ths pent haste) Spent pce oe pe se) or ang 3m cogs: print( "Hello * + dog + *Y print("l lave these eoget") ) printc"\ntmese wera ny Fret two goge:”) Bid ioes = doest-2] ‘for oi dog in 014 do print (snag) ogst0) oes ranoret peso") printcaogs) Beginner's Python Cheat Sheet — Dictionaries Python's dctonaries alow you to connect pieces of ‘elated nformaton. Each piece of rformation na ‘otorary sited se & Key value pa When You provide key, Python reums the value associates With hat key: You can bop through all > key-value pais al te keys, oral the values, Defining a dictionary se uty bea er en rtd eee RA ie eet Een Making « deionary slien.e = {"eolor* “preen', “potnts' 5) eens et eee eet reer a eer eee eres ee ee a Aner Perera pga tour ac ead een ete ere ete Beemer errr ‘Gottng the vaus associated with a key siior.e » {"eolor": “graan', “points”: s) print(atien ¢ Stine {atterel soins?) Going the value wit get) steno = Ceol": "green atten cotor = alten 6 get( cater") ‘Lisrcpodnts = alien Grest( bosnte", ©) print(stien color) Print(aiden-petme) rome Soe rere ree eee pierre cae tren Chee ete eel Ear penreccenhae acca) eee Stent chlor’) = ‘green’ Stierce[ poate") = 5 Modifying values ee ere ane) re ee baie St pop ee inaesestae opin iaray Moattyna values ina devionary ier, 8 = ("colors “green: Drint(atien.2) “points: 5) the alton’ color and point vate sealer’) = "yellow Removing key-value pairs Persia cparieetiern (eine ey ey peers Deleting « key-value pak Slee = {calor prine(atien 2) een", “points: 5} ed aiten print(atien 2) inte" Erte Duets eer ery teen eee Pes ts nea ae Logping tough a key-value pie 4 Seg zeal s forte anne sow each person's fevorive language. ray language in fav languages, tens): Deine nane ¢ 8:9 5 Yangaage) {Looping trough al the koys brine(nae) Looping trough athe values 4 Show ald the Languages that hava boon chosen. for language In f0 prinet Langue) Looping through athe keys in order 4 Show each person's favorite langage, 7% onsen by the person's name {for rane in sorted (av Languages. Keys()): Drincinare'e "1 "5 Tonguage) ues): Dictionary length erro Finding « dcionarys length run.responses = Ten(fov_languages) ‘Stonng ictenatea inlet f Stare wasn an empty 14st tere =f | eke a-new user, and add then to the 1Ist or a eiese's "earsea"s seed. apenacnes_ user) take another now user, and séd thon 3¢ well. 2 ser$, apend (nen user) 1 Show all inforsation about each wer for ky vn user dict. ttens(): prine(i ess" sy) pine) ‘You can also doting a ist of destonaries cron, witnaut using append) 4 Define 2 List of users, were each user 4. _irevremed 97's aieceney. for user diet in . print(k + pint“) ry orl ‘Stoning lets ina cictonary {Stora multiple 2anguagoe for each person. far languages = ¢ 4 Siow all cespenses for each person. ‘on ane, Lange in #3 Languages. eens()¢ print nae 9 2 5) ‘for dang’ in Lange: prin? Stang) Nesting — A dictionary of dictionat 3 y for usorane, uter_alet tn kere. ttone(): print *\fUsernane: "+ username) ‘oliinave = user-euct[ first] + > * full-nave c= ener dict "Uest'D Aoeation = user-ciet| Location) prine( eral nan print(-\thocatlon 4 full nana.titte(9) wy igeation itLeG) ‘rosering he order of keys and valuce from collection: inert OrdoreéDiet Store each person's Languages, heasing 1 track of who Feapided first Say Tanguages = OrderedDict() ‘Fav anguages(‘@RiI") = python", "Raseell"] f Display the results, in the sane order they Fortin ens fy for Aoesnes ttn) ‘Arion lions sien = 0 4 Yoke @ mtI2ion green aliens, worth 5 points 4} "seen lave thes a1! stare ie'ere row. foc altenvim In range aeeasee) tewslien -'() femcelten{coloe") = “green eralten{‘solnts'T = 5 fet siten{'s"|"s 20 © aisen rom hewcaltent'y"] © @ ‘Tees sppen (nae atsen) Prove the List cantaine a million oliens tuncaliens = len(sttens) peint(Mumer of alsons eraated:”) Print(nun aliens) (More cheatsheets evalabe ot chmatthes github olpee! ea Beginner's Python Cheat Sheet — Tele) see t= a8 soueicsmme and While Loops 1 Testing equally and inqaaty re old enaigh to vote!) MW siatomenie alow you to exami the currant tte ‘of program ana recpond appropraily otha sto Youcan write 2 simple statement that checks one ‘conto, or you can create a complex series oli! ‘statements tat deny the exact conditions youre icosna for The i-ettelse chain ‘While bops nan along as cetain condtions remain ‘rue, You can use le loops fo let your programs. fun as ong a8 your usere want them fe Checking er eaaity Asie naasoy em aviuaoaveratm Acute sing orto checkin cortions Testing ita value'sina lst | Python Crash Course Covers Pt While oops (cont) een! Tectng ia valus ie notin et Lating outer choose wren oak Using canine wa kop teioecven eon play") ers — * a Checking ita st is erty ee eneecste lames Ceroseh Mintle trae rane) i . Hume = Soa oa SE eetiaat) ing a ag SR (his oe a nat See Af messaee ‘Accepting numerical input Se: ner = ireut(rew oid are yn? *) Using break io ext oop annie op Print("\nvou can't vate yet.") ‘Acooptng inguin Python 27 ar (tes rout tr Prtor 2 Their tems atime sea gat ‘Soro pate re csv Py 3 Removing all cas from a Ist of pots pets = ('doe", “eat, "dog's “fish, “eat cee faobie's “est printtoets) Counting 135 ote ronovel eat career printipetsy Print( current. numer) More cneat sheets evalabe ot chmatthesithublolpce/ rena pores Beginner's Python x " Cheat Sheet — : : oumng a erai va aU lara telah) . To fuil_rana(fiest, 1360) ‘one epacte ob, Furie alow yout wee code ss Bininsictn ‘ee that ean then be run whonevor you need fo Fetuiming a dctonary ‘Sccomplsh the same task Functone can ‘ake i0N® describe pee(mancter”, “harry Information fey noes, ad relurn the invomaton they eserite-net{vaoe's wit2ie"%" ‘ererate. Using liretions ellecively makes your wild person(firat, Last) Droaramo eas to we, toad, tot and 1 Using keymors erguments pet(aninal, nate rson = first, ast: ast) Pen sroraation sects bt: recur a vane musician = bulld_person('sinl", ‘hendedn') IMSS, Sate NaS”? atuiming a ovonary wih optional vakios et puis personctirst, 12st ‘Waking function print vetio1 erest_oser() oe, aninol-dor frit nusictan erik fe gant. Using Nono make an argunont optional de describe petCeninal, nant Greeting, oy Satara et ee Python Crash Course cece Print(cIte mane Le * + mane + °°) Covers Python 3 ond Python 2 a see orenton') describe. pet(‘naneter’, ‘naeny sorarchpressconvpythoncrath Sea Sarna esernamas = [onannan”, “ty, rect users(usernanes} ‘Allowing a function to medity a ist ‘seaman aie reso ea retro rong The gris ren anos its od. 0 print models(unprintse, prin Fossa print set of soe." senile tnpri sted: current model = unprinted. 090) fpeine Printing" currant mecel) Printed: appenet current-noas]) ‘margor'] f stone som unprinted dottane, fond print each of th Unprincec = ("prone case", printed = 1 Print.rodels(unprinted, printed) print(“\rtnrinted:", unprintsd) Print(-orintea" printed) Soe rrodieg alt ge Theor ape he ame Preis oe eet et print nocels(unprinted, printed): Eingepeins s tet of model vile tnprinted: Current model unprinted. p00) felnt (Printing “> current me) ‘printed. appar current mocel) “pondart’, “eine f Store sono unprintse dociane, original = [phone cose"y ‘pendant, ‘rin printed =) print_modeiscoraginat{:}, printea) Prine" roraes etna) rint(-orantee™, peantea) Thence Collecting an artivary numberof arguments et make pizza(size, *t00pings) opptngs: Sy Ropatne hake thee pizzas with oifferent toppines fia puzza['enall", "pepoeront Make-pizza(*Lerge", "bacon bits! have-pleza(nedlon:, "mashraons" > ntons', "extra cheese’) ‘Cotacting an arbivary nub of Keyword arguionts ef tutie_profite First, ast, userinfo Tredeat' Fest, Last ‘id ey other bays and values. for heyy value in ueee toto. stene(): profile(keyl = valve sora = Bulle profile manic", ‘pcations paris" prknt user. 2) Brint(user_2} seorte", ‘lelde'chenistry") icin core rine \mencing’2 "4 el3e 6 psa brit “Topaines" ‘matey nesor Ero lech nie ree sariede hope ie Amport zz piace. noe pis20( ‘nots lize. nae pizza's Importing a specif unction {Gah posed anon asin roa Se ‘fron piazza ingort wake pizza ake pizza ‘nediun’s, ‘pepperoni! (hce_plzsa(-onal)", “aacon’, “plnaapele") Giving a macule an alias soport piss a6 p rake pi280( naa.’ “pepeerons”) onke_pizeal' snail", pineapple") Ginga function an alias rom plaza inport mke_plzea as mp o¢‘nactun’,.‘pepperant”) mot'snall",“bocen", "pinescpie") Seen ae eee eee tron pista ingort © (More cheatsheets evaloble ot chmatthesithubsolpee! Beginner's Python Cheat Sheet - Classes proorammning Classes represent real-world things You want 1a medals your programs: for example ops, crs, and ebots. You use a cass o make ‘objects, which aro epece instances of doce, care ‘re robot, A class dofmoc th goreral behavior that 2 whol calogary of objecs ean have, and ihe Information fat Can be assocated wih hose objects (lesaee can invert rom each other - you can \wnie 2 eas that extends tne unionay of an ‘xising lass. This slows you to cove eficienty for a Wwe vtiely of sustions selfifuclievel = 0 Croatng an object trom a clase Aeseesng attribute values print(ny_ear.nske) Brimceng-car- adel) Caling methods Cita BS rl et te Betrek"s cart ayes taco" ait, f seerinuter spect to electric car ay gelf.battery siz0 = 70 ‘Adéing new methods othe chs class charge the vehicle Wing a metnod to update an atrbutes value ra taut eee Pring(cthe vehicle te fully changed.) capacity Using ene metnade and parent metnode Witing a metnod 1 Incromont an atirbuo's valve narge() Finding y Python Crash Course Python 2 Covers Python 3. ‘Overrigng parent mothoas ‘class Electrd Seifsbattery charge tevel = 108 Dbrint(“The vehicle Ts fuly charge Using the instance sy scar = ElectrSeCar("tesla", ‘medel »', 2035) sy scar.charge() Prine ms ecar-pattery.got_range()) Inycecarcdrive() ‘Storing classes ao “orRepresent gas and electric ears class cae) Etecersecar(car): A snple model of an electric car.” snips Importing ndvdual ass0s trom a module ‘fron car import Cary Eleetetecar sy beetle = car("volhsuagen', ‘beetle, 2626) pestle. 1211 fane() Syrbeetie drivac) fgg < Bectriccer teat, moder 9", syrtesia.cnaree() yikesie.drave() Inpporing an entre module a vaalawogen’, "beette’, 2036) beetle Fini tant) yibectie sesvat) Syxesielanive) Importing al slaseos tom a macile {Danton at ecomze We ou SF) ‘ron ear import * rey beetle = car(‘yolhsuagen', “beetLe', 2016) ‘Clecee choulé inher Hom objoct, lace Classnane(odsect): ‘Tho Car class in Pytnon 2.7 laos Car(abject): ‘Chis class._int_ method i dierent lass chilaciasstiane(ParentClass): aor ans (eeit)= Sioer(lasshene, se1f)._snit_O ‘The ElectieCar cass in Python 27 class Electra (Car): Got inst (eel, make, model, year): Fiver {Electrdecar, Sea). “H0a ‘noe, meee, year) ‘Afiet of rental cars rom car Laport Cat ‘ectricter 4 Poke ists to hold # Fleet of cars. fee fleet ™ 1) Slectriefeet + 1) 4 make 800 gas cars and 250 exectetc cars. for in range(s00 far o'Car( rors’, focus", 2836) as_fleet, aopendicar) ton Ne ago) Sear = Electetccor(‘nisa Slzetese_fiset.sppene(ecar) FALL the gas cars, or car in gas_feet: ear. tak sar-chorget) + "leat", 2015) nd charge electric cars. nt("Ges consi", Tenens fleet?) prant(veiectrte cars", den(eieetric.feet)) (More cneat sheets ovatable ot chmatthesithubsolpee/ Beginner's Python Cheat Sheet — Files and Exceptions "Yur programs can rea information n om files, and ‘hoy San wie data to lies. Readirg irom Hes lows you to work wih a wdo vaity of nirmaton: wring {oles alows users fo pek up where they ltt ot he ext ie ey fies, a you can Store Python structures such 26 Tein ata tls. Excoptions ate special objec that help your frogtams respond to eros in appropriate ways. For ‘Scamp if your program tris fe pena le that ‘dooen exe, you ar uso excoptions to deplay an Intoraive oor message instead of having mo ‘rogram crash Perrone easing no by ins ‘irene resotmanan area ottoman your program You ear wit tet ‘Stor the nee in lst ‘Opening athe using an abeolite path vdth open path) a8 Fob) 1Shon 2 Fon} reatnes() Oparing ate on Widows Toda erat ee omar ses corey deine (Linewrstrdo0) evant path) 25 £0 feb} reaslsnes() Wiig o an ery fle iting muti ies to an omy to Handing the ZeroD\iionEtrar exception eee eaere ee Yes Foeriee(*T love enesting now gates \n") Hanaing the FleNotFoundemor exception Appending oa fle fnaee = *ehlchartha. tet ireacopenct pemey estat Strita( 3156 Love working with data; nm") Lines seieetiey except Fewer taccase) opp readlines() rd File {0).". Format Knowing which exception to handle (Opening fle from a sbiowder ext files/alicectxt ner Python Crash Course ‘Covers Python 3 ond Python 2 ny reaalines( eer eee ene ete ner Ary cade at Seponds on te yok tang poe recente ord Using an else block print("enter two nuseers. 1°12 divide then, X= Anpt First munber: *) ¥ 7 Anpst(Second minbers resunt = 1ne(x) / antiy) except Zerabivl stenror Prine( "vou sans etvige by sorel) tse! ‘peine(recute) Preventing crashes rom usar input Celanese tor det) oe ren Nando te owarracsulyardkeee rng. "A slaple calculator for dlviston ony. rine( “arte two numbers. 1°11 sive thee.) Print("entes "q" to-aule.*) vite Tove Mn Anput(\irst sumbers °) ay! ‘break y= Input ("secons number: ye wy: result = Sne(x) 7 int(a) cexcopt Zerebivistoneeror: La Pmve an' ele by ser) Print(resute) Deciding which errors to report eee eters oer ese mr eee ieee Perey te frame es poveeaeenred ee eee eer eer eee cate aon enon a eon ter ern) Ree gina re Psalter aba ren T avril ra ‘Using mo pass statomont nan 00 Block E.nanes = ['alice.tet', “siashartha. bet’, “noty-dick. txt! “Lette women xt" foe fnane inf nanos Wheport the length of each File found. ww with open(F-nane) a5 £003: ines = fob} reselines() except Hicletfounderror: pass a Tn Lines = TencLines) mks Hf) hos (2) Lines." format ‘Same, am iteee) prictince) ed eel een ere ere Peieiereeta eer nner Peer ree pi aera for reer ein oe ener UE EEE SEED ee ee enreed peri eee eect ateatar oad pac Dont use bare except Books ss saneening except pase Use Exeaption insteas "a 20 sovetning except Decent ont Printing the exception yt 1 Do sonething ‘except: brception 36 €: printie, typete)> Erte a eer Pete oer Pe Ce etd Acard therein chs aes t e oienener) Concierto eased Pee ee pee ye ee bee ere reenter ete Using son.dump() to stove data estore sane nunbers,*=" mport json mens = [2,35 8, 7, 4, 18) ‘ilenane = ‘oumoers 3800" ‘itn apen(Fidenane, "Wy as £ obi "on-damp(nombore, #203) Using conosco road data “Lead sone previously stored numbers Amport Jon ‘Filename = tnanbers. json" eH open(Fttenone) 36 F003 Teabers = fson-Lsed(T-ob)) print (nnbers) Making sure the Stored data exis Inport Json f.pane = ‘numbers. json? ay ‘with ogen(F name) a8 Co Isomers = fson"1c20(4-003) ‘xcept Peto founderr Sav on) frm tram) Beginner's Python Cheat Sheet — Testing Your Code ‘When you wie a fneton or class. you can also You confidence thet your code wil work eorecty as moro peocle begin fo use your programe. You can ‘ico a8 ne faturoe to your programe ang Know That you Navent broken easing banana ‘Anis! verifes that ane specific aspect of your ‘code works a fs supposed to. A tock caso 2 ‘olecton o unit tet wr very your coao's ‘behavior na wide varety of stuakons fet fall pane Stele) {ing ho unetion| ran Full ames import get full nane Janis ~ get full name('Janis', "Jeplin’) print janis) 09 = get_Full_nane"BoD', aim’) print (bet) Testing a function (cont. ‘uaking atsteaco wth one unk tet Totes ata sera acne fa tet toe ‘tee ocate ant aaa heap west Sove the at ol nareeay opore vattcest from full. panes Sngort get full mane lass hasTestcase(unttiestTestase): eeSEtE for names se} .orserttquel(Full_aney Sands Deakin’) unsevest ming) Rgnromaten eee ee Ee mesmancacennem seems a=: Moding the function Don moa get rma) £0 ge ct mes. bt Wet dot Si ma ens eneng bonne et get_fulh_nona(f3rst, miele, last): turn» Full nase, fullinane = *(@) (3) (2)"-Fommat(rirst, indie, ast) sretumy Fuld nave t8t120) Using the function ‘from full_eanes import get full.nane John = get full nane("Joba’, “lee, ooker) rancezom). via = got_eut1_noma(‘éavte’, “iee", “rotn") printdeviey Ware) Running the test When sre race {0 gat run your xg [BUS ft fo was a cangoryce ae S08 Esa cost parce tant ‘ese names Like Jonis 3. eacebock (gost cecent call asi Fite "test full nanespj"» 1300 28, 1h cost flrst_last ‘oplin') sypetrroes” per fu12_pame() alssing 1 required posstionalorpunents ast FAGLED (eerocest) Fina the code [iter tf cde rd su te ses agar Gr mate ee sats rh ae [Jeornocom Howe car mane Pe maser opr! amo(flrst, last, midélee”"): "all panes Yall name = *(6) (2) (2)*-forvat( lest. ssosia, Jaet) case: Full pan = “(@) (2)°forest(taret, ast) retorn full none.tétle() an i tet in eens

You might also like