0% found this document useful (1 vote)
309 views

Programming With Python PWP Tech Publication Textbook

techpublication book of python

Uploaded by

comedy lover
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (1 vote)
309 views

Programming With Python PWP Tech Publication Textbook

techpublication book of python

Uploaded by

comedy lover
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 40
oe MSBTE Solution @ SyLiasus @ Booxs/NoTes = @ Las MANUAL @ Las MaANuALANSWers © & @ MCQs with ANSWERS @ Micro Projects @ Latest News @ Tips & CHEATING TRICKS @ & More www.msbtesolution.xyz Introduction and § yntax of Python Program eset Pon lneractive, Ob}et rented, Interpreted, plafrmindepende pda buldng Socks identifiers, Keywords, Indention, Variables, Comments en envvonrent setup Installation and working of OE surig Sle Pthon script to deploy ‘weleome’ message. sydon sta Types: Numbers, Sting, Tupes, ists, Dictionary. Declaration and ue of datatypes BEtEe Introduction to Python nareterputar programing Ings, is verre of mg yet power programing guage tht Grorpeeweh thon. Curently 1 the mas used, upgraded and heard pga language among a fom eid} esd general-purpose, hig evel prograning langage and wos mil dewoped for rehass on rahi, Al fs stares are fuly Ue rcbword Engish commuricatio serteces and nce alow porsscent apes ay concept in fewer ines fend “= ese bejoing every single discussion about Python, first let's have some Interesting facts about Python which ‘scored among ober languages. 6: enor en diterent platforms (Windows, Mac, nox Raseber (© When has a simple syntax similar to the English language. ‘© ttn has syntax that allows developers to waite programs with fewer fn pce, © htennanon an interpreter syste, teasing that coe ‘Siping canbe very lee ; © aovctetatdinaprocaderatway anciecreatewoy runes ‘ite caneaty mast famous programming lane specicaly preferred for auemasetit for developing (xara wenn eats ie AROUND sapere te ren reed appleations) Adsiionaly, thon ean 3 cin ing Urs twee evelopment, mathematics ste SAne THE ears an aan oe SSeesysu aig orstco mech nae score red rasbe ax for an eoncen nue my seed for readabity and fas sore sininris (2 the English lbneuage wth ey nosed to other = le comand 5 090 =e ie (o enter Key) competessbvanely any x= aclinguages which aften use semicolons or parentheses. mn oT tetas such as the scope {pet on eden, ung whitespace ta define scape such "*2¢ramming inguages often use curly brackets (()) fr this Pu"Ps 1s than some other protamine be excouted es s00n asi iswrten. Tis meen 2 from rods, feeions and sie Incadtanand tert {ty ta lea: Pen tan epesive and ND Wvepraganeir ngage ard tw dered x oe {ey sot satenet ors hese nua betas kageeeaae None, ich messiiseantotndesand the langage and ee. ay Interpreted: Patented nguege Ie potinaoene cron seer let complers. the eer ngugG Cv, va, therein te conpe Prone hm toéebugourezde 2 atorm Independant: Fon Por odependes ag ante runthi eae enter ation such as nex, Un Tee cancun tical on my tor, | Gloss ator and Prale :hon cable ard can nonin reing seme sch i Ym ‘us Unie ses ea Ges ltr and portatie rag 5. Objet rented: One of he ky featses of python, Obes feted peyanig Pre nis ce criented language ennese csies an objec, nears polmorpion, erent Large standare rr :Pthon hs large sanded Ree which poses ch set meant toot hve to wit Your own cae forever sl rg Tre we man as rest requir expressonseaasing web browse e& 1. Free and openseren Python is tra t downlad and we. his meats ou onde i ie re Xin {our appleaton yn an example ofa FLOS (Fret Open Seu Sofware whch irs er ely Fed ts source code mdi Rand rey dstribtedense or peonne Fenn, 4. Atodestrcve (tomatic memo management]: Prion spots arate menor mages eens the memory earl ond feed wot asthe spect m ey eis Yu cone ote te Zig themenor/tatweddinGreby tring ducer. 4. Supports exepion handing a xcesion i an even tata oan ding program een arden? ‘arma ow af proyam Phen pers exceton hadi shh ean wen wt seer ore ‘Gots rods sears tate use a exeplon ere 4124. Python's “Everything is Object" Concept OR Python is Dynamic Typed Langeege “We now that, Pyton tan object ented propramaig ngere. in Ptton ve se whe it cee For example: tf we decease are, nun = 5 nena = tnotherpogranming rguges, nu” behaves as aisle teretn Python, value "5 behves aan cet ad “rum” are vet ee hare yun ede fr wees ctanwe det cesiadasey Se tte cc and "5 a asiped cone oe But rth ta Wee Ea] Les] aa te poe se nnn Prooramming with Phen US - ~ Now eter fotowing other statement: runes eet neeeter ee me ee cercierene ae kc hr ene tame er rewton and Syriac Pen rer towns e ise Ee Ba ee eter poyenmina ase yee = fF beth above cies Stipe ma Beas Now ela ig sath alam ume 17.25 Other procramming fangusges wa cantnue the deste of “um a teger 5 “nt and wat perform maton \ypeanverion. Or progameicganguages wil ate rege verson 1725 fa mn where i Pylon valve “17.25" mabe: a tetaby new bj ad erence “nu ow ita new jen “17.25 an wil args Gasayoe of “run trom “eteger test ser = tas a \ ; a area oer 7 emeans, Python wil change date o any vale lerence cad aired obfec/ave, Now se wl tagpen when we son any Sra value Bove value to some eee "aan 122 Python's Smart Memory Management = With respect to above dacimion Secon 121, le ws contove xt decson about Python's smart emery management To begin with tte flowing sates, mes mes In ether prosrming languages above sateen are about to erate td erent memory Bods 0 and #2 and thd ot here vee #0ot neve el Phen (nd alone) eventing cen concet wit make S252n ie ‘and bth nd and od wit behave as reece to me obec. = Tow ss we change de valve Cfr2 win ether languages valve or wit re-wite by new value 10; wheres: In ryan x new objec 1 wl be eet nd m2 wi change/nore Rs lenin ower ee 1. (Retee Section 123) eS a sen Pym OMSBTE) 14 4.3 Python Bullding Blocks . ne ofthe most Imgortan inst Inow abut any PTENTIeG Lene te cts heya vbr, data nes and commenting sections. The baecrterseergs wrogran inthis secon we wilsecand deasthee Pion bg as es 434. Python Identifiors pny ame aed 3 HenierThes ames dae ats rane, tots ae, te modules name, et ie ober programs my fons name and module's ame, eee poy ng =ge beaten ei to2ry entity sch 3 | Theysart wih eter (A~Zora~t)orundencre ()-benyteyan han eercee, “hei length sot Knit Bat prefered tobe meine ‘ ‘They should net contin whitespace. hey ate case-sensitive. (ies and unt and NUM ae ert) They shod nt be keyorts ( stow of "Smal ey = Raowrgare ine empl fata latd ees wate, ats 2 ate td “ fl, but meals noetiumbers ald Pees ‘rial, bec of speci symbol eccount number Fina beara space 25 ‘va because starts wth igh emono. ‘inva because ofp smb ont inva, pecae ae key = Aadone more important thing, wie ing ondercre (_) a ene fr es eb cunt and appearance of undericoce la Mente far dass menbers make tbe eso name means, ot lowed ting (ie fede mere cmame smecns semaine ame ‘meons, peiternenber 132 Python Keywords ~ teed ae the weds whose megs ake non oe coo Python has tol 35 keywords. Tr COssSSsC2azsSs y 2) q me noe | a 5 Ter oe 4 and_| cota ore or SEER Sosy 4.2 Pytenlndentation waste pron erasing aes sr of cut braces (16 en lo ut Pon ws Aegan eee ch 25 ody offre, o0p, ass, ete) tcedeceibe The rot ofindetaton upto You, butt must be corustooreeion nee ee tbe cain weugou th oc for ese at (Fopeseng mest ofthe programmer pees ie space a xb (Pym ese sete acre ste Tb by fe) Soe Ee hdeig sf smore rte ad vee We found may i 6 ares Ce ced cs aie bgonng a my mater. But you ese Fen wll ow et car 134 Pon Variables ‘tithe reserved memory lations to store 2 rtime value that has an stir rare), HEN ‘weeecevanitie, reserves a merry ato. previous programing angst, we a9 4 Seioctneey crit aton carer ae E ree aston daa ype ofa vara, he bterpeter allocates memory 2nd es ‘Sony Tete, by azining erent data ype 0 varables, we an se Ieee, ‘atk’ reer. ————E um=45,— fullme weee” stent onan? Th atonal eae amen tome no nd even yl ean ee tle on ve ah een ea rune ston stent Pon il otomaty rate ni tpn desnpenor ee ‘bona alow tle sel ve freamiet eehnesis ers he ioe he he ad reas ae eed ne location. One mare incecstng valid assignment statement i: ied snieteinan 3 it eo be niger ee ole ng 101, 30d 29 1 es possible while asipring values of diferent data pe oa! con 6555, “a rat = Andmainparant hg stow the ener nde cited seen 34. 4.35 Comments in Python = Comments vr mparan while wens gam exrs the pros nd plan mien cde So that amen ws uptig or undeanng te wren ce, der ot have fr ef ve Pponve ivetwotperatcommen = We tao tt cman te stn I an de at winter be caged nor nee. Ledranng dn pps. Pe pres peste oo 4 ‘Sigene comment te conment tz coments ge i of ede nd eters path elite Saree \Wehwe bah) bas agit connent Ref lewng emp. frame: sssiete comment pita] baled: ‘ras be conment ‘rosy cgay at stl) xan: iH) athe pa Ho exami Wrasse 3 Pepe wn 2 ute comments athe cones Ut ened tut are comers me 0 mee. Obi wean ep ae oreo e ramplet: ‘oie ae be done Moma smuline ent a) ‘wren cc pos vmuln comment fay bruni pita eer sneha (°“ "For erampe abv mtn comment eon canbe ween teampiez: “iis ean ato te done tomiesmitiae pire ar) Ceampie3 biscin ao be dove pitta) ‘One move important the abut lng double guctes("**) acannon, wecan to ie Cog. Deng Ina thot documenting. Wecan ries CocSng athe fin statement of any fnaloner das ar mote. Far earl ef squaretnun: += wh method etumssqareot parameter pase *** sarnun om ‘Avove pepired DoSthg cn be reviewed anytime by wing te nem suite __ de orev youtan can above Destiny ty wing foto Senet. prtsquare_toc_) 4.4 _ Python Environment Setup -Installation and Working of IDE = Assassin orelace etre bok we have wed and flowed PyBan 3.7. Youcan se am yon 38 “reson 3 pe Your convenes or nected by our hb ruc. ov ean downoad any Pton wes fom cit Pinon web te Sey oto bps pyhoncr/lowod te dawned any yen eon afer your Operating Siem. = Aesone moc important suction, evn alton wiréol han dag check AA! on Pot". [il autor set enaramenvarbl far Phono emma prone. Now you cn a ey ale shore Frianconmnands on youreommand prompt (A Seen ao seed “tbe pth hot pend ‘Aerintaling eho, deepen command prompt an i “BH iw open Pino PR, at te Kecton 27) ————et—e_ SSnrPnicrosott Corporation. AIL rights reserved. 41) (WSC v-ASUA 32 Bi Cae, _Abers sition ee aa aun Sf bceS%3, An 27 2038, ye ns", scopyricht”, “eredits® or “License” for rore inforsaticn "Wash pret nase hon prompt dey same bc Pylon eminem \sers\Aafithlagython 3.7.8 (9.7.0:3bF9¢c5093, Jun .27 2048, 04: vin? ee "help", "copyright", "credits" on “License” for nore inforestica. > a0 a7) (Hse v.asa4 32 bit (Inte >> print value of w is :%50) Hue of a is = 10 bees ROSS a = a rte ol agar ri ee Fo re Seem nent tne mn PEW orintcary ere De Lape pe rtp cre how rt Fnaae Dee Team, poe pee Smee toon = cet remtecs Fre ce ear Go es, Se rae ae Cee OF Pe ee ea em ee bon ere Be OE ser ncn epics yee Oe ee ae raom owes por Foes ft ‘oe tee | 1 np ye my ac Pn Na Sc ye ob wt a nk y= Son lroad net wad bre pees Shep hs Ckhen "masher trina 18" al HN Tey nk a 8 7 —— a toda and Sear ore we ae sPowng shea cing feneo sear Sere I eer na enim ‘e022 Tk wil actos dnnled sng podoge nu vl owe dowrievdng and ain posit YOU in se Us tay narod Expr em. 4.5 _ Running Simple Python Scripts to Display Welcome’ Message ‘Aer ncentandng about station ot Pon vesen nd ys, ow i'r some bask apa Program 15.1: A Python program to display “weleane” message. ~ Unite eer srogramning teages, Ptbon da eu ay by code that defines orm, ethidto te vena single sate. Fy eat have ma) cbade ay manaatary css Seflns We on Gry an tng Python pope, Foreame, tate} eye saan ee ater ese eras le oe aeerecon pana pata gn eee er ere ena terre praetor Toconcatenate any varisle vale mth Suing ypemessages use comma. fFerexampl, a= 10 lve 31.73) on = _sroterenmplecanbe, stvaiveot #7 = Ate tying stove prosams ln Orn 10, sry fun the program rom “Bu” men or pret SHDNTs Getshiner oer ASAT. Program 15.2: Python program e ake Input = Grey nputeutpa operation we ptm a ython Python perfams kb frm of Sing Le. every mes ig, wi be dpaped a Sse an erry let you tak, wl be read Sg ony, Here we have bitin functlon pa 0 ea pu al. Th untonrene any apt vale Inform of ears Forename ‘read and return npr ame to ale. The dea tp fee wl le Sting and expected data kW fame Sing Here, nedel pei flr allowing sot emp, ow) z g inst pt) 8 de Hare tpeeating ea eieret Wig Te ball futon rut} weed we etm ang 06 put wood ‘hei mata wil envet he poster gre asta anger ae eure tbe ope SRG ve bitin conversion ncn lo ) boo) aa a}. eee at Python don have data ype oe Here, we ae fee to use dole qn ("") and sgl guste or SU ves. Meer felons means eanyle | | | | son yon BOT 13 tosicton nd Sete st Pon Mls wing éatype. aera 2 ses ne Pearonetee ponents: Afro gt tes ome! apt) tn so lon owe 8 promt Th prompt mesae wit oe nat MEME Wl be pled fr gan vest pcie) pote remot “Eater pat SPE as mesoge Reb sera of wring te deen & a yn (STE) 4 nse sina) oe 448 _Pythan Data Types, jo poets Seen ee Ra ia ast eeey SST eae ts eo en Ee bg leer lin toma tyne bul pray dpe bes 2 song un Je te Scat = _Trtecarstout tise cate pele lee ater UNIT we ith dead daemon ato thee, 184 Pyion Numbers ‘Detar datatypes ato Fore americas. Uke eter programing npwpes, Fehon hav four dere ishonten. 1 kebinedineges) 2 etn tgrthey anda terrsendinel ad hen 2 feng pleat 4 seston rns ett nox peed an conma ue pee dp tales wos toma at Tossa sipe lng ene ey et a ees Gaara ws Pon len Yatcas base hig tar tonne a uve np 0 oan 8 ric desing een eon apne Bakar ashen on he Fon apelin gan ed, td oe cope bee an ree at a bers dented by x where x andy are the ltrs ads te imaginary ut Rl Hedgenss op where 204 y Seep atieesnditeeese tt teepasddtemeeete a =o be enn deste sous ee fsa goat = tS tps an nsec ber Aldi? Hrepreet en Ocal mater so sesestesast * Teena me -6susr8 nesast0ases wate) ~ he apne satenenty = GPs Oe x pres hoadecinl mnber apd I= Co © eersens an Octal number. Sim. we Gn we b fo rerset ay numb. Ty exe tc ‘= Sudnuersmast tart with er oom by ideing character xeraar®. 162 Python Sting = mryton sg set of contiguous sto racers presente in Sle dale ues. ban won Hine ‘petra wk or Sing. The gape ( [Jor] at eves stig bston ree abe Dat ‘at fom @ Python ai allows boar stn nec wher st caret of Sig Pos Ines es horace 2 ond 1 on Th sng eoetentn operat] t concen tings Ard Ue ween pertr at epeat the ef operand Sing acardkgtoni epetand mesa, re a Livan ad Spaeth Po S ingen Pn us ett a ae f stort hat wed rg above aa eee operators tt . on Jaa ee oe enon tes, TA SARA oR (CaieeshsiiaychaabrjectaBISUTE BEAM Pegs py A “=e more ting yihon als igs afe arabe Le ie Giher vais ant eee ( ced SSien2in stings wit ot change iad bts ae wil sla praesent whereas ga ing renuinsncngs. 163 Pont eet reed eae reece meen a monte aang Senirar een ecranoe eat manomcore soeranena (15.25.326) foxessat 4.6.4. Python Tuple =A Tpit ananer eae which stores sequence of al parted comma, enclosed parents) Forenmele, upl = (8520316, “av ASe3, 02658) : “The man diferece between Tule ad tae Us sensed in squab ats De) tt it oe eps at cers Spdaton nsteor ements. = A Tupletrndoy anti. A Tepe ow ace prt tat we eat ins eos jefobets sind Us ATgadan 165 Python Dietonany “week wit st an Toe and Aras we have to remember the nde rte: of ees The Phony ‘Tacit Ut a gon ure oer ou on tide mann or ur ene NN A (RH CIP SII NY ANG AD arryon Desai Bs that has pao aninextey| and lees stax fsb) ‘pedis ype ond and ebmentalue can be any Yaké Python data te, omy repented ine ean bess (ree t= Prove "27/898 anda:727/0/3985" "ie saunono, ‘toe cesar sow the pena mame shaving 2 Lynde) and pasa de of ithe Beoig BES le ota ndex Siler oU, Dicdonary sao angst At lowing cde. Python Operators and Control Flow Statements ‘pera hon Poe 23 Cena sateen —daesel i) 24 Lanpng hotonline) 25 wip mailing pm bk ie ‘ete’ codon nd rgmig bs, wel Saas ont peter et lind cant fou nee og ena ap treedi Pten Bring Wek isis a ODE ppecesn rye aaron a semanas mar oneles Pe. Basle Operators asp sl os scl ya at roms predeto’peesoncoar PYBenht a sep eh ede alongs I 1 Aainteopenon Conese ale fale © Mempertipcpentes 5. Sis epeates 2 ee cutis Trraraw des out en oprmare eles earela ona BAA. beet Operators etna oprtrs eto pec wtb pero: nt peas Rae wet ‘ Sa Nan | a ON ST O41 Litthe teases of Python sind explain any two, (Ans. Refer section 1-4) (ae Oper es iS a Gees 2 Wed dy nan by eva Gaydon ert ecto fates ey et > Toaion rr en - Gas. Rear secon 1.34) oe = [aeration Performs sabsraction of two operands “ | mulieation | Pevforas mination of two operands (2.3 Watecomect ont apy ments in Pin. ns. lr section 1351 ui) nance jm as Retr Sen fins | 4 _eeremcenpannasmeinin at vere SES ‘00 a ee 3 fais [rer on Teco raga deans abo 9D OTS S1_nogarmay wn yng gat) 22____tynan dyer an ong 243. Assignment Oporator siement opertee 12 1 6 WAL ECCL OGLCPERLT IE eae operstor ingests ea Pate Tate 23 a Tale 243 3 assignment ZAZ_ ComparisonRelational Operators . “allgnme operators isa Repl eating shart hard exerts pater ra fettisnal operators are to test the conddns The relatos operators resus as Boolesn Tut or Foe feteabieA2. sudhesnm time efor Table 2.24. won Sr SRS eo commie) | (Foperate)| > CFasterthan ) Ras Tre vale of lek operand greats than value of gt | 2>y = sie operand cocand sd en] 2 coe ee ena fbt Sanco < eta Rn ae ie ol a TN wd xy > Tabtaek AND | Subtract eaht operand trom lek perad inf > torte Tt | ssigntlet operand = SF Taw [Fess Trae leopard rater an eau thevae | > : Eat Step peo; tere ee Pe, iu : tir AND YG eed ih coed te Ys than or ep | Ret Tie, ale of et eprnd estan or eual tothe vue of [ny 7 siento operand " ® ‘bt opnrn odenisereks Fae a “ition AND [Peto fost cision of 1k eomnd wh = 7. =e ano cperand and then sign ole creed Ta nan eguatts | Rats Te, ves of bthopwands re equal other res xr | ae ; " 35 [mode AND [ates mad wang end vie poms dar taoving progr bat enonteer abe ni ea Oa rena tole operand z 5 ‘parent AND | caeute expoentaee power) valve we and asian atta eh oper _ 7 - 4 ae eT ae aN NA SEE AE AOR SS A Les | Pel ges see eosin exqeniocnrae nan Par an eeass , Se en i epatgenrs a otek mse cnt la ope aes eon To fot et Bia i ate = aetna Lam er eeee na nia i ue pore 3 oron | reuse, TT a 5 [aware feet = cy er ier oe C ra oe | yea amram a Reet cas t a egstneT reese oon et i Right shit The lft operand’s value s mened towards right by the muriber af bs | a> t =e = fale : =a as aaa 24.7 Wdentity Operators: yin operator asa ni ea se ay opener yen herbed Tablets Stree henwie efae Shenae res fae. Ress Taz, peed ek opunna Sane fo rae pid VB peng eg, 248 Membership Operators - a Ea ee Scie aco eee etl emcee ees vw fg Romane er etm on ec all ne i as ee Tenet, | Results True, f bath operand rleencaratin & peo ES Se woewaes ree ‘isco Secione 12. and 122 and then avg Sarge Python Operator Precedence ‘MeTéble 219 shows the operate precadencelhom bghetobM= Ef... we 2.41.9 range( ) Function = lng wt enon sore) aa eee (aaa Inte very necertary to dieuts on range fancton before dition en Cat! ow sstemonts an aoe Ey ‘eral on forloop that we see maty one ura, ae using ronge J uncon. emake an pc a tht range) funilon ls mandatory prof ep, But not ke tat TR angel) func, bce ren 3 ‘aed on provided parameters Th uneven hs folowing sgntue. ange star_salue,end_yal, step] eeauie of assigned delautargument to each thes parameters, we en wie tls urtin wih ee difernce posses en used wlth one parameter, i wl consider this parameter ab exdvalve and returns 2 ronge fem 9&9 | end velvet." For example the statement worse nerantiniie sn Wit est os: Rie aa ioinaaTD Vibe eed with wo parameters, wi consider these parameter rl an end yu ers 2 tantaning value tom stor lnder end der mpl, the statement 23 SEES OTT [RANT OR ES {Gpenenion abe ete pore evemerm pectin a= ompement ny ie i EW MIR ee ode sd foo on a ‘Nidionsed ion ae hs ane ae Eeama = EASSAATEN ROT z ee tiD arerear : = ten sowe cai, or fat wareet Dll ea wlth Yon ge nr ae "1 nie eave Oa aRUATOR ee ae Ss | When sed with three parameter tl ocr Oe pts send wl nd eg. reas sami geen rm lester ath ates cenanoene) atone, - omg ewe ots, the ep Sey aa ey wore) alee AsSeanent opt on hot ted wprsion poner Fercunglehesttenent ietinoe deity pete Tanti Nenbersipepenioe andor aga operat 2 Control Flow Statements Te te ones enced eet fo bea Be aa eed hese non no cays ohh cen i eprom co arse bead er Sitpermtenensobe epee ° eat flow statements that alow for mor der peeing bres Pon a pes a Sn oe ln: Neto saen ec + rnin ate ag te) 2 eer! saenents fetes teameg cepa eet oR RPO fet examen 3 fan redia ecesten eck ot sno ape cod SE _ Programming wih Pynan MUSBTE) 210, yon Operates and Conte Flow Siatonents 23 Conditional Statements OR Decision Making Statements, The conor stetement executes he Bock serens based on eos of enon Le. Dec Making sttenents are uses when we wart a se farce shouldbe executed a one sation and ferent Instructions sould be executed in anette seton Oscson mang ca be Inplemented hPyhon sgflowig statement 1. statement 2 Melee statement 2. Hettelesatemen, 234 The if Statement ‘Theif statement old standard syle where eck ef statement gets excited provided condition is Tut The nent MOR peta ng: ors ny anon tern ots ean nd en ndertain opal ere, the spcted condivon 1s Tue then oly Bock of satement exeares ethetwise gets skipped. Retr ‘Aire ram cots one prompt msg n pl) ater cs Pg 4 whag ioe coer tg coed me condor ret araher oang cl muioel satresseesorses 2.3.2 ‘Thelf-else statoment The fstatement only evaluates to True cesut, bt we cn ao evaluate alert in teneralsyntaxof tee statementie: ceca cx ae tnd ett spatter Tae wien sunavinate ee ‘ec eereaeeror t ec Te eoaenent ip tering ober oni any re dt Yes Te SES eka ents tl floing em wre we ec whe tte ara Sa teen en ae ne jon Tesene gmc bey ing yng aye Ar we TO 1233 Thelf-elf-else Statement OR The else atm a statements ar epee cocoa wi waste sean tine easiest ‘Teton to hs stn ei F_Progranring wt Python S2TE) 2M » ‘ere the exciton of aterents depends em creas of cons. The sans wil eee 3 sn Operator Cvs Fw Seren Programe win Pon SEED en wi esiqned To conn fet Te tee‘ wb ioe aaa ae a tones ate flowy roger On pet ol et aes by gente etementanlagalepent, oe 25 208 Cod, a onion are Ta Relig program hat ts geste thre rumbersby wig nese sere Tate ee z pein "Erier 3 alae) en) Pececdif Hove ale, at re outer iFcndions ar dependent a ee ets tested even F presen ve, The onion tne igs teste if str conon rts ue, 22.5 The Shorthanditlse Statement “The shorthand ele statements mot Ie ens operator hat ows to wee ee sate sgt egerenl amare statement Hendon ebe statement? Hore, tenes exces specie condone Trsotense executes statement. Ree fofowlgeamle resung eve. ‘The mses: pref i event) ces excel Hmm % 2 == 0. Tru; otherwise rium, edt) ezectes fle oli anche rogram ofidlarestet aoe. Pacem CTT Beton ee pt’ fat Regine arar wl make Rei toundntand abve nese tue inPython ras arto neue block of ates eer fr eval tint oro sing Tue Byam ies no yes of loing seers. ey 1. wile loop 2 oto Tires dcr tbo trae wo oop stiterant wth ames 24 _Loopin he lope 244 The while Loop tons weep ely ame 2 that we uel ad CCH ad De The OWEN en rae: Tatton "ate cobain Ssaenesl stoned [oS acerneuidecreeat ere pier niastng, th wie lop wl rspest hs rao pected codon reas Tate Th wil perform soeced neremen/deeement (Nake: Pyon does not support ine tet = decrement operat) Rlerfloning single ease ta prt “Helb oF mesg 1tnee owt worry abate nes The pint value of loop counter" wth Hella” message g + 246 a ——————— OE ae Ee. (5 = és ean za ern ree tet ab eg cn an ee Her Pa tate etanng nt oun see pin act owcorteceniee Prater) Pinca) 242 The forLoop = Tefen nt tale weeding Ch ano. ee the generat ree ‘eel =(2.5652070) ano: Sock ne: e fom ahve al anaes, we GR Bal Pes froon exits» rt We, ator) Seah Cia tC ie Sen mare Iraumer/devenen ene, 25 _Loop Manipulation ‘ie ser peyrmning ania tan pode: pwr 0 pet el atin Bean Siang wean beat pote bit Rb oH ee topless the umber For 12030. Tron Be etputwe en ae th on ey eration of fordeoP the 6 ern” ets fhe Sara a als mee: fe Cfoung ano Popa wae we ao eee, snd exon sy. en eis ect er a sree, i 7 kepeod"orte™ 2 hey a ayer ‘25:1 “Loop Meripultion using Keyword continue” eyo “emo tts thes ak els ann ant prea no ttn br Pg ten eter he ure dfcrtee. Rel lowing snp coe rove") ove Sat ater Se we 1” becomes fesomig coe enti ae I sts tection and exeeitscvtive sateen. Refer 252 Loop Manipulation uslog Keyword “broak™ eyword “tet meaty tee the eeton of ry bop ab the ea {olouing Single example xt, Oa, In above prosam, brent statement ewcies when De orden ass; a Reni ea enc, re out wi be Tao eenstey Programming ih Python (MSBTE) 220 2.6.3 Loop Manipulation using Keyword “pass” eyword “pases sed when 9 statement execute forts In Cand Cs and Java it ike ep Pytion Ones we Contra Few Seems tatty ogy requ at we dort do ot wats xd to PY Pair ol curly braces (()) fer an empty body. For example, Loe Fata wea) 7 ‘Gerlaterin "Pyon’; fete =" yee k Be » te: pri"Careat Lett ‘péz-rain ates") a ent GES) Nea ibis cere tooth ier ony acer Dein esc ery : Output = Curent Lever :P CarentLetery Cura Leter:1 _OmrentLater:0 CuneatLever sa” ain aenende 2 We can also wte the statement “pass” to keep enpty definitions of funcions and esses and pices Focexample, z eft 5 2 penuh from method) 2.54 Loop Manipulation using Keyword lee" aven becuse. Ricseoe wes the arate tnmesor ertinatte tough exhaustion tements may In enon loop statements may orc Dove ogra nesta otows 25 _ Nested Loops = Pree aioe 1 use the cones ef nested lacs, where we 436 en ap ie athe oop. The very tout pace paamsand many other sustors foes to ue nested opt Flag prams help you to er he 7c ot ces oop, Wet leew ketene pet" whereas exter loop wk mate te ener loop to ete. es by extn gel | ncn wi pes massages In Cawkre. Trelore we have used paramecee ne Beertroean i 83} 20 ‘i + det ee mare tire Ba rongel ancien nr be wise om sor ead idex—1 The sms regan be coe by eg ive at LI45] ete (12.345) fer eset fade. But ner feedoop rezares feet Nea o wiedoct. = tertk acer exampie cf paeeng iene Fi eget vig tee cpm Scene ro dene leven fi wr Fa nt ote vat un tye ec og in eo retro by wing ested whats 8 FH a mene aE tes: (0) oer zsie desi dling asin i ies (6) Bieetopensene ()Sok-louetntin a2 Tals: (a) eee ust ep aetna Tepes and ans \ [FRviow cussions 101 tessn atte cen Pien ih earl rh) rersaet = 2 Colon iver pena fPyoruan an ere (te ebro 2 1 on | Sete } i (0.3 cipkan mendes operand erty operator tn Pytion wih eames | SEE peer : | i ga fears cet eben ate sc en (Pee lest ling wus et andupntnses ' 2S Show he use efte;word efi Pyien wit example. (Ans Aaa chon 22.9 ‘plaas} (oy Redeset operons \ QE Howto use sheethand oe clement in Pyson Exlanwh exam. Ans fer secton22.5) (Mas) [ebrciesmiemital \ j 2.7 Biplan frlonpin Pyen wi ele (Ans. Refer secton 242) (eats) | th Cems } ae ‘Cane use Leywend ete wth any loop? Justly your answei. (Ans. Refersocion 25.4) Glad) | (a) Accessing values bo Dictonary, deleting valves In Dictionacy an updating Dictionary. 4 | 2.9 State tw use of keyword pass. (Ans, Refer section 2.5.3) aman) | () Basi Otay cperatons, | eon ements ecninots Pen i Reco: 2 t0ni28a) (ate \ (a_i toe i 21 Epi er ee = we have akeady coed abet Pyne Bask ata types In Seton 16. Tes deans in uous Pn } sa mr Sat ts een ue reas eevee | Se atc nyrennebawtoae Lust Cyrene way dave terbgnge eed nb ones er ASS | nn cranes gen Song etm CSS a | ce peed en ae ON ! A aascpptnneeee ansh a eede cou Tecan wb we ead SS 09S cr eg inant eine bees tS Leto coh cen ore em att Fond LS ee peetioes ands pptaatons In Pytson, J 4.4 Decarng List OR Creating ist OR Defining List \ 4 : 2 E 4 : ne decay in steno eres gore (ama) ustonne cece pn sense se 5 eT coe eed ee : oa care WEEE wm Pron 22 Ea=[0,20 30) =. = = istesta age sss (tnar. an. tsetg See iets [152,200, 24.055, “aie 5, 98405), (100.200 30.Tit 34.2. Accessing List Elements using Indox Numbers = We can indo pest osc elements, which fom. Therelre a Ueto Slew have Inderramber am Gree Freanpe, “wet ta aceio elemert othr an evalé adc autres hwo an eestor aoe rae ater arene be i wi he i pes) = peove cade nsw oboe eer Indetior te ndexoutt ge ‘are more ting, th nde tbe an neger. We eat web rth res hs wl eso pea ferenanpe veo clog stent ators code; print.) Tes wit how wing ears Tipetrerlstincces muse reese sees not Most seer proermnng lingages we can aa erate rough bdo nents by ung whiedop. ele tw len, .(funson etre gt amber of laments) inna Us eon (Rte Secon 3163) Lin z sn Pen a3 ‘axa Negative List indexing ton sows necsne ext eens oder numb let dea ere not be ses stent shod be tings 2, and neler ogee Pale (easererT ~ rate ve eve HAO) | olay wctase:"ul ‘Rat ace wl oa flown Hib seb 1 ; ‘Mies-ty eaves Fant 2444 eratieg trough Uist sng frtoop wich set eel apa a bre pen oef MADER Bn, eae ei eye ie stp, Dees an Seg ite eee Sots cence . = Aspe edema ea e aa = ease ste am Ga erey een fray, wi eer each element oft. An ere wee iret eae, ateszubies square ond abe of Ust elements 4 * ww 10) 100 5 1000) 3.4.8 Sllelg Lists (Using Sticing Operator(:) on List} : In above etios, we discussed lise wast digas elements, bt tops eae of leas of Un, we ue Siceepeition. The Sx operation performed on Ustwth he ue of en Whine owing varieties ‘toparfor Sire ceraton. = Topintelements rom beioing tos rarge use stain Topi elmens from end, use synta==Inen Topsites rom pec laden the en as sta inde} Topi elementswibia serge, use syntax [Stands nds} = Toptet whole Us withthe veo ng operton we stax] = Topi who stn reverse order, sesyntae t=] Telertallovng code that demonstrate a zbore sng peaHens, See etc el orm ton ao slice! ts =a) pring al elements “) nga eres: TPT 8,0. PLO, RAL ST ry ews. Woy gi elms nee : TSUN AR: 10°C, RN, OB TYP AS Bsele Ust Operations sr dsasion eo gps a ent of st em am as ns cn aU eens te ang ont pntg teats ean 3 pony tena fadrgerghol we 3:84 Adding eloment: append , inset) and extend) Functions \Wetoow tats mules pact. Aer eatga Ut wt nee Ket asend ran oben aniston new eee tanned) tannagpens nd odds sete ere ll. eth wecefeleant eat ton of eet: Fa.nene spender) na soc tytn, ogre z San ring Sait Bae aT z ee ‘Above ode lala he wo eS Cement ant cepsin awh ae appended al. Hee, oot tate erce lb: The fa tte of gu al eS Theor ery ener ole Slag We Gn 8m MPC kena wep ee along cre Ra i aS ckements fur List) Te pt vals ges peated ree an ere Lt wl oy eg we. Now te lepu mus Be negra ves oy 22 taser Tis tcon ses an lene pected pst, To we thi coe tas: tix nae Isertpoivayindey est ele flowing code. trent gels ivened Et esto, Rete ele ct ncesnsect res rectal) Valine sinter) - Fema serine Sanshe atid ics 1 ee eee) ete h571800°) eet ering iso aindes 1, cons") ai é ony teil Abc bet Ski ote 2, Ut coats [haters Ces Soniye, gy, Te] ‘Ate ezhng“Acconts tind 1, steonn Toft, Coens, Sant, Phy, ion ate seg ain ainda: in Manat, Cherny oss Te ino 3 eater): Ths uncon ads lames fanart withing oe eee) tend lens of 2 wi Bi. ere an sn, PS | = ace eee nae erties emer ee SS vues sa oa ae aa wee SS nated ee, ae Bens Be | Ramiremntcimetaaeatetiess Sa aa | A oe eri out tran ne ive FIRICEED Zi He f13 35.45.55) laiecane) RICARS ein, bt consi : il) int Afr asin is contains :* 2) ae ote a cms otbwahing a es rnd wh lene parameter And elemers of vane ‘alot et chanestaeates 3.4.62 Finding Length of st:using__len__() Function ‘pioneer ee cts ion Tein = Thi et lng rb ent, song ecco tbr sce 322th icon orb ae tees eee ‘oo eno wiieait os: [fsitiristeonaies 1 3.5.5 Lies ‘Abo cade wie as: eve is nates program te pt acer of it laments Tea np aed, itase20 Eaeteieesas eros SRE PE Soe 3A462Updaling Element: Using Assignment Operator (=) o over-wite Value We know that ft scale eet Le we en update and cre elament by sing asgament oper ‘Smoly sescsnment oper t upete value 2 required Index Hee han xa, where we ove wit It Sents 344 Dolete or Remove Elemant rom Uist Wecan dete oe of more denen fom Ut by eg yer Aung enon fuon 9 oth Aen or vig cert Horcion. |L de skeyword sto remove ee ert nat from it anderen x omens eer st re #5 Heeisan example of removing yee eanert ar Ut ina en nde I [Sige Gmina 9X Let “2 _remove(}:Thsfanon renowesseofeem fom 9 st Sta ee — Trae rerewielenet| ant) Tis non remover ener am genes etn "iam popader ner en} :Tas ncton remove eles aati Wnt Fox rame. cea) ler titowng code het demons remo Fp ction ore) 300 34.65 Testing Membership Operators on List Wena deny damsel Menbentip pent Secion 2.6 Fina’ nbenp pert check the presence of ah elenetenev spe iuence U5 Tile 6 Sel Pon pes wo Memes (oncon REE est Tu, # specie opeand laren is pesent i speed ght operand sequcr, Aes oe Feced pc ane ftps piel RANT RT _Propenniog win non twats era 347 Bull secon hive ulin Ut ations eer AL edn cadet est tem ont eS a Ce a" EA? f wi 30 ‘rece |-sperelemed) as anclementtote endo est ‘end eneraoqera) elfcllelemers cfs ttotbemncer st Tsar lsentindegeonee nero tem at te del ee ‘emo remem) Reovessn Rem mth # pore 7 fae )-deort) 2 Removes a tens tontha st ie ide) -ideelonet tse) a etrasthelndexthe ata deen cunt |- coun song }-sert) Sart teneia ain sendog ter 7 revel) resend) eve the ede ofan inthe ‘orl -

You might also like