Download as pdf
Download as pdf
You are on page 1of 77
‘ PYTHON PROGRAMMING mEIeS oP Date ... Bs Py THON PROGRAMMING a SCODING BUGS ENOTES GALLERY c- Introducing Python - Me i — fytten &_a_high- level genus = purpose and ves. it opular progr tng. tanga : = os uate vehe usd tn Gwe development, Machine learn. - -tag applied ete. eae ye Pytflon fuograms aye Cd Smallet than the othes ir ogrammin dong uages . —_ Puogrammers J have te type Helatively less and the indentation requirement of the Janquage , makes Mens 3 gj ——adable\_ab Me time. Min’ > Veg Simple Syntax. 2 fasy to learn, v oT Cv ~ a rary ay | paint (“ Hetto”) > = = General pusipose Janguage ( Simple yk very powerful, 4 language) s Console Applfcatfon & Scripts iY C= f> Desktop Application : 2 [> Web Applfcatfon i ; * E> Game Development F % LL. Machine Learning Deep! learning , AL, Of dala ek cs Z > Muttinaradigen Support = \ [= Paocedural Style Programming _l?ke C . = y “s L>- oofs ike Java, © g Functional Programming (tke Usk. f => Portable or Platform _\ndependent - Puoqrams are typreally first compiled Yate an Utatermedfate cod¥, then the code Pe yun Me interpseten. —>_ Dynamically Typed nyna 4y---NP m~= 10 4 ys “qeeks™ 4 uv . ace “python J 7 This featuve %&_dfpferent from Ctr b Tava. they ‘ aye stateally Typed . i In_pythom we don't have to specify the! vatable PY i name. But _the disadvantage & fm this the type & asstaned | ° st Vv in the vun time" of the paogram , so there avd f paeg move chances of yun t’me evror. Automate Garbage Collectfon ‘ \t medns when you 4 dynamically allocate memory So you don't have fo worry: to realfstng —th?s memory . g u ‘ § => Popular Apolfeatfon Buflt tn Python FF ~— + Youtube) Neteiix',”) Quora » Instag ram , DoopBox y 4 =r__butat O tn thon — % A__funclon & a sek of instructfons' that take x some input Prom | diing..dose someniwork on those “ wameteds and paoduce some output - + 4 os al a S Hope you ave enfoying Python % Tos endZA end and sep parameters fn paint . P—f f > = = int [“ welcome”, end =" ") = paint (“to GPG") Oulput- Weleome to GPG votre End parameter creates _ space and ft tells » shoutd be painting after tks patating. - And tn sep pavantetet: when we have? multiple = P—f input parameters we use sep to separate them. — # f defoult they axe _Sepaxated by pace . o f CASE) Ab rey ik patnt (“1o", “out , “2023",) Sep =" "y = Output -. 10-04-20a3 a EICODING BUGS CINOTES GALLERY “=> Nautables fn Python = a _Nawable & a name that Outed fo siefen to memory ° ° Jocatfon. Python veurfable also known at an identi -fiew and” used to hold value» ee In_python, we don't need to specffy the type of ® vorfable because Python & a fnfew language and og smant hte qet fab enoug get __vosiia le bype 4 i i aH I E iS cre % | xample patce = loo ” tax = (8 = | ° a = L total - psilce = _fostce + tax i t ° 7 % pant ( total pufce) On : utpub- 1g tp 4 How vaufablec wouk ie EICODING BUGS EINOTES GALLERY © 3 4 “= 10 Uo]<~ * Yes “geeks! qeeks |e~ f % z= “20 [aol z q it we say we=z Fi ‘ ‘ Winen soft 4 : Nwx 4 but PP We 30 Bole— w : “4 ® ies O}P- ios a nm & ° $) geeks 4 putnt (2) 20 f °. f pat! (e) Qo 4 4 Lace od ~~» —— Pathan Dynamically Type eee 5 a ho m% 10 $ J paint (>) . nk: “geeks” U ya paint (>) ~ 10 ~ geeks ~y z ~ 3 Note - using a_vaniable without assfaning fh cause evror. ~ &q- paint (x) » oP- Name Evror : name ‘x' fs not assigned ~= ut) tn Python - L 3 This functfon ‘Uu__used to take fn put pxom the user } i Example - name = input (“Enter the name >") ° ” psiink |" Welcome''+ name) t ole - Enter the name = Himanf Welcome Himanf Example - # Python program tor _additon ' t | + = fnput (" Enter Firct Number :") 4s input (" Enktr Second Number : ny m= fat (x) ys int (y) Hes ney ¥ Spat print ("alm ve) vy lvl aol eo blew lel SCODING BUGS ENOTES GALLERY Typed) In Python ~ Outpul = Enter Fish Number we rom stying Is 7d Type & a _bullh-in_function that Hells se h0 wherever we have to ‘ you data lupe of a “vayfable or a value. i Eg a=10 : a (type (a)) = 10'S ie Ciypecay) 4 C= 9437 puint (type Co) ; O)P = das, Mints § <= class, ‘float! <= class, ‘Complex'> T =n python we use "None" Ip Whe value uel or we dfdn'h asstan any value fo thy voufable > g y é 4 indfeate that we don'h know § “ In python there 9% h te no chav ype you w wank ft a. aga reuld Eg - Sky_= “gtg" (Shing £ fsa: sequence 3 chav) FF paint (type (atry) J [.10; 20, 30) (_@tray and dynamfe ally patol (type (19) add and remove thee. st Iwems are stored fa conte. ~nuous locaHont) Seoae ~ re eae $= {10 30,30}, “difference fy modi Sek_& a _collecHon of _ Ss punt (type(s)). where all thems are _ = t x and set UW dike mathematical Set) y “ w Oye S, a J ~ dz fio: "gfg”, 20%" def dicfonaries ore uscd to_do SF paint (type (a)). ings. Jhe & a 7 3 ‘ collecHton of key value pairs) > Eq- thems: prices rollnot Name. F > p> Type conversion in Python - Type conversion > ae 3 Implictt ExpltetF a at '0 €g- 4 "135" a Ts J= 1+ dnt (s) > ‘i (0) f= float (4) 3 d= true patat (3) es atd paint CL) 3 patat (e) : $ X opp = us ojp - 14s » u 135-0 fg- d= " geeks” fp wT SJ » paint ( Jist (8) > patnt (tuple (4)) Py pafot (sek (43) a p= cigs tet fet ht Mt] c 1's") Date ..... 9-3 a= 20 patint ( bin (a) ante 7 palnt (hex (ay) ne T b (oct (a)) = | ¥ OP = Ob10100_ | URIVE H 0094 => Comments fn Python ~ ate 1 We may with to deseuvbe the code we develop. We might with~ to take nokes of why a J sechfon of sept p>, ng for _fnstance. Formulas , pocedures , and sophistcabed business Jogtes ave v lypfeatly explained with comments, # oH 4 Single -Jine comment - # a Mult? -Jine comment - Hs. oe ie # ite a Doc-shing - the string enclosed. fn trfpte quol-es 4 that contes _ immedfatel after the dettned fm ane catied Python DoestYing, @ ¢ v E =P _ib, else and eli? in Python - fe ae pari %e Shere come _sihualous in sea) Jife when we need to do some Specific fask and bated on some Speci pte és gyntoe - if Ceonattion 1): ~~ ne, # Executes when condition W_fuue . ip (condttion 2): ~~ Executes when condition 2. true ~~ # if Block tend here ~3- # if Block &_end hee Example = num = 10 it num >§ : J paint ("Biagen Han Ss") ae it num 2= 18 5 paint (* Between § and (5") —7 ole - Bigqet than § + Noetween § and iS _~ ite elif Statement - shortcut of theelse chatn, while using if -elff > statement at the end else block & added which “& _ S_peitormed ip none of the above iL-_elff ctatement 4 true. F Spnat Date .... . Syntax - i? (conditfon) t = Statement elif (condtHfon) : stalement 6 4 ; a L .: = Bs) elses « a statement a Et Example - —Jethey = "A" 3 if detiem ss em: _paint (“Jeter & 9") elif Jette == “ct: putok ("“JeHer uc”) elif Jette == SA"; paint (" Jeter & AM) elses pint (“ Jeter isn't A,B orc) OP - Jeter GA > _Autthmetfe opetators - They gue uted to peiform mathem-_. zalea) operations Jike. additonal, subtrackfon , muthip. -Ikation, division. ; _* That axe 7 onithmetfe operators tn_. Python - = O Addition _® subtraction ~_@ Muiiipixation @_divtston @_ Modules © _Exponentiatton @_Floor diviston ‘i “ay Date I Onevator -_In__python, + 4 the addilfon operator. It TW y 5 0 het odd 2 values: a 2 ~~ Example > vol = 2 val2 = 3 SI yess val dt val 2 SF _paint (tt) ~j_ fh + £ Sos SubtracHon Opevator_- used fo subtract the second value from he first value. 5 on -_ Node 3 valg 2 2 Ss dese vobl- vad ~~ patat ( He) peorens Modulus Operator: - so -u_the mod ulus. opuigtor used to find ~yhe Yemainder when {fest operand t_divided by the Ss seconds 4. Example — vol 1= 3 vol? = 2 s dea = val l Yo val 2 ~S_ __ paint 9) >} Of Pazzah 3@ Exponeatfation Operator — _** used to raise the firsk _y operand to power of steond. x Example = __vall+2 > vab2= 3 > ves = voll ** vd2 a. prtat (ts) = oe -~ 8 Spnat Date ... — a © Floor division - // %s used fo ffnd the floor of Phe quolien) when first operand s divided by the second. Example - vall = 3 a oe es ee b val? + 2 % is, Me Sie ub Mes = val t// vat . -F patot (es) _ sees. - oo ojp - Pa Ba __# => Python Logfead Operators with Exampleli = : Opryators aye used to _patform _opetalfons on values and vawiables. Jhese ave the spectol symbols that caory_ouk arithmetic. 4 and _Joaical computavions. Ihe value tht operator ~ opexata_on_& 4 Known as. Operand . : SICODING BUGS E)NOTES GALLERY, ~ logical _and = logfead ov = legfeal not 4 A 24 = Logfeal and~ True tf both the operands ae fue. >and y. X and y False Tove 4 oe True 1 False_Oulpub nas Pe che cow Taye 4 + v ~ fatse—Outpat FPorre—Oertpet Example - a=lo A b= 10 4 c= -lo 4 th a >0 and b>O: SS sl NS ns patel. [ome oe WE +. Spayos and b> d 6 70% ae he : SF pata [2 oe mobs ou ane aye _guieator than") elses. ~ tol T[epnest one number & 4 riot -greatut than o°} are greater than 0 FP = The numbers Auleost_one number Yok geal than o. ~- ~¥ Example > a=to ~S =e i cz 0 if a ond b and c: i paint (“ALL the numbers have boolean value as True”) Ss 3 — > else: Ss ~~» puta (“Atkast one number has boolean value _as False O]P - Atleast one number has”::boolean value _as False. — we ~~ Falte Output Tue Output ~ > Example - azlo : ps he -10 PS or c20 >), Mf a>o or boo z 7 thes of the _numbew i agrestet than 0"). na mbes ps s ff b>o or emo: “i & : z _puind (“Efe of the numben grsstut than 0”) else —paint_["No_number lu greaten than 0) SIP = Eithey of the number Greater_than 0 : No_umber i _greaten than 0 — Example - a=to +. brie 4 eo } iP aorb ore: pufot (“Atleast one number has # Taue")_ boolean value at else: pink (“AN the numbers have boolean . False") Value at S/P- Alleast one number has boolean value ag True. | = Logteal Not operator — wosuks with a _cfagle boolean value. If | ine beclean value. & -Tstue te seturde Falee and vires Nvisa, £ False olf Date » a —— 7 0210 { Evamplt = je Bearcat ca ity eo Sy poco [Boolean value of a t Taue") oe i nol (.afJode* © orzateSt2O)t os paint (tio nt divtlble by etter Sor ) Se hie oul ("1a 4 dtble by, hen dor 6") f pF 1 P= tots divisible by cithet dor 8") Vv | »~ a 3 ys he dade ef tvaluatton of Jogtead_operalor ~ Hae cate _of swulliple operators Python always evaluates the expres from eft _lo_right. 4 Vv J Spang) = ef odatfa ¥ patat (* Method _talled for value", 2) vithuyn True tf X20 else False 3 avons 1 a b= order cz order 3 Hate) oF b(5) or e(\0): 3 paint (" Alltosk one ot the number fi positive") < j wy of _muthod_talled for value=-1 Method called for value = $ Alleast_one of tre number positive. f te | Ly dor a pe |e i Date ..... => Python Membership and Adentthy Operators - validate the memberthiy ina sequence, such at Shing Atsts or tuples . im_opevatoy = Jhe Mn! Python offers two membership operators fe_check es of a_value, It fests for membersh, operator ‘u_used: to check it « thera / substring | element Evaluate to “tur if th finds. the aptetfied element fra _ existe ina sequence or not, Sequence otherwise False. For eq - U | “Gy in_* Geksforqeeks! tt Checking. 'G! fn shen | “Laue g d LL 4! ‘ Greksfor Geeks! %# Checking ‘9! fn string sfnee pythe tk case~ senutiive, veturn fale g ig False " Example diskt = J1,2,3,4 23] 4 dfsha = [ 6,7,8,9] them tn Jct: bs if fem tn Stet: i — paint (" oveilapping”) § v elses pain} (" not. overlapping’) i * 4 nok100 i nok net a not a not 4 oh t int optvalor = no! J Vasfable inthe does not fie J false other Example >. R224 i a id _— ys 20 wt a iB “Yist = [10,20, 30,40, 50) _ Es E(x nol fn dist): a ft NOT nt tn ven disk _pulat (. ots passe gf sk”) elses aoe i 4 fs bin ven Jfst' int ( 1s paesen i gis fs ‘ pty tn Wt): aint (“y fs pesent fa given Afr") 3 else: ~ pata ( iy is Not puiesent fn given Ate") = ¢, °. ° o, OP - % fs_NOT paresenk in_given_ list. ~ y te present fn _aiven Met SS wt v - Identity operators - Thy ae used fo compane the object woh’ the obfeds axe actually of the same data type and shore the same _ memory Joeatfon. wy There ote dif went identity operators such ad Nis operator - Evaluate to True if the vanfables on efther side of the operator joint to the same object and false a} f othutustce. Example. = me S 425: portnt (oc &% 4) fd) fa Sport 2 OJP = 1407045 86672032 a gist SENS Ie, both the vay Hore, fa_the 8 asttgned to th Fi “and whicho why xeon Tv Ss not’ opwator - Evaluates fo folie ff the vaxfables on _effhen | stde : o| the opwtator _pofnh te a ditfount object and te othurwise, 4 Example. MES S2a0p 4 iE (type (oc) fe nob int): aa} gq putnt ("true") . a elses = paint ("false") = b # Putnts Taue 8 & mK Sb i 4 if (type (x) fsinot int): i , “ " = paint (“ true") i else: & t puint ("false") a * '. : > 1 : ai i ofP- False a Taye) 2 => Python’ Bihwise Operators: — o Operators are used to perform _opeualt e4__ gS Bee an perfo peatons. on vafu axiables . ese one the Spectal tymbols that cuwiy out _anfthnec and loatea) computaifens. ghe value ahd operator opevales on is_known as Optrand . i ! i wy ~S Date were oro Siu operators ~ “ SJ = Slttse AND (3) ~ Return |_tf both the biks ane I else_O. Example =. 102 1010 (Binary) | —— he ee be Y= 0100 (Binary) ~~ ~3- ¥ — aSb=lolo b ol00 = 0000 = 0 (decimal) STG Bitter OR ([) — Returns Lip velther of the bik & | else 0. ~ Example -_@=10= 1010 | 8fnary) = ee b= 4 = O00 (Binary) alb = lolo ~ eer ~ o100 = Ilo 7 = ty (Decimal) ¥ 5) Bitwhe Not operator (~) - Returns one's complement of the no Es Example = Q=1o= tolo ( Binary) waz sl0lo 3 = -(lolott) 4S > (1011) 5 =-11 ( decimal) 3 d)- Bitwise (XOR) (A) ~ Return I ip one of the sbils fs tand the 5 other & 0 else return O- W Seal Date weve. =1u (Decimal) + ‘ Example - a= lo a = bey Ss yi ++ Puiot bitwise AND operatfon Eo wink (“ab be! arb) # Paint bttwhee OR operation : print (“alb="y ale) 2 # Putnk bitwise Not operation Ke paint (“wa =", ~a) # Paint bitule YOR operation - paink ("a Ab =", a Ab) e op - at b=o 2 afb iy 2 Mast = atb=ty G & @__Shitt Optrators — These Operators ate used fo SWPP the ¢ bits of a number Jef or siight thereby multiply ?n “ ox diiding the no. Sy—two esp. they oth be used Yoheg WO we have Vig multiply” or divide a imber by two, & 9)- Bitwise Right &p Shith (>>) — Shiffs the bik of ihe no, fe the_sifght and fille 6 on_ vod. det p (fs tn the 6 case of a _ntoative Humber) iat a sesult, Similan effeck as & of dividing i no. with some power of two. of : Senae J : a y Date Example. = a=lo = 0000 1010 ( Ginar WF a>>| = 0000 Ohl = S_ ~ az-10 = Mtl oo ( Binary) ~ o>> he Vit toms -$ ro “Ty. _gitwise veph_shift - (<<) art shifts the bits of the number to the left and fills 0 on void vight as yesull, Similar _efPeck a of multiplying a the _no- at some _power of two. <3 Fxamplt - az§ + 0000 lol (sinary) 3 acs] 20000 lolo = 10 ¥ a4e2 > 0004 0100 = 20 ~e Example - b=-10 = WN oto (Binary) ~» bec f= 110) 100 =-20 =a bee 2 = WO tooo =-40 28 Bitwise Operator Overloading - . Optrator Ovetloading means ft extended meaning _ beyond their | predefined operat -ona anin For example operator tote used fo add two integers it ochtevable because the ‘+! “S_by ink class and str dass. You might have noticed that ~ the” same builk-in_ operator or funclton shows different _beha- 7 vise for objects of dfpferent classes, this ic called Operator as thet as join two sting and merge two _Ifsts. perator is v overloaded ~ > pverloading. a 3 Example - class Yeek(): def init — (self, value): i self. value > value A def and. ( celf, obj): paint (And operator overloaded") Sperat Date wee. 4 if isinshance (objs Geeky Es sitturn self. value be obf.value operator overloaded") tty fsfnstance (obj. Geek): seturn_self. Value | obf. value : a) else: Mase Value€rror def - xor - (sttP obj): paint (“XOR operator overloaded”) (Must be o objeck of class Geek’) LI ip istnstance (obj Geek): 4 velurn selP. value 4 obj. value i else ratse ValueEvror ("Must be a object of cass Geek”) def. Ishitt. (selP, obf): iy paint (" Ishiph operator overloaded") ip fsfnstance (obt, Geek) eburn SelP. value ce obj. value else: Yatse Value Error ("Must be a obfect of class § Geek)” ; dep - tnverb. ( Sele): paint ("Invert Operator overloaded") 4 Heburn ~selP. value 7 # Duiver's code iP— name ==" main": 4 = Geek (10) 4 be Geek (12) sia {asb) ‘ ‘i 4 a 4 Date .. paint Cal ble ee print (@*b) paint (a4eb)_ as paint (a>>b) a paint (x9) iy p- And operator overloaded OQ Poa 8 ~ Or operator overloaded r Ww Xor optralor averloaded E> ra TICODING BUGS CINOTES GALLERY rs \shift operator overloaded [= 40460 na vishifk operator overloaded 8g Invert operator overloaded =i |G Sa * loops in Pythou_- Uv kel = — condttfor become Viale , the dine tmmedfately often — im_the pangrous Gu exeauted «| nek — While Loop - It & used fo exeeule a block of stakements 2 °, ° eye p sitpeotedly until a _qfvn condition. w —_datisffed. And when Me Suntax = __ while _expsitasiowe : = statement (.) Flowehant exits while loop ‘I indeffntte thetahion. While Joep falls unde the cliguy tn ladefinile etalon means that _ ih numben of Himes the executed sin't specified ex; Weft fn _advante. : Statements _uepsesents ‘all Ying atahemenk indented by the Same _oumbey of chayackey space, oa Pegrenanatg —tonstrucdk one considered to! be pant of a sine blo of Li tode. Python uses indentalfon loop & f as th methods of souping L,_shatemess. When awhile oop hk execubed expy & (for 4 fvaluated {na Boolean tonkext and if TRB bete Me loop ‘ body U executed. Then the expat b checked again, ff fp oS at taue then the body | executed — agath and the continua until the expsieasfon becomes false J jr Example | tount 20 while (count < ae count = count +} pink ("Hello Geek"), OJP - Hello Geek Hello Geek Hello Geek | nd ol bits. — [20 fos Le | | =) — SF yin wun until there & _an__element Joop over _a_Jisk thak this, we have Hun ao while potesent nthe Ist t \n — : ; Example -3 gfngle statement while block yr U YFust_Jike the yp statement we can thert_ ane multiple TE block, ip the while. block consists of single declare the entfre Joop fn_a single Sink. f ctatemenks fn the block that make up the l body, th can_be sepanaled 6 Peol sh ¥ loop _bedu ey p xy semPeolons (4) _s_ count = 0 5 while (counk' <5): count += 3 pafnk( “Hello Geek") —¥ t J: olf - Hello Geek _ 5: Hello Geek Hello Geek =) Hello» Geek aw Hello Geek > si - > * Sparat Date ... eC) in Python - s e__puthon nn webwan. ence numbeu sa sequence of umbeu thon _stange () £7 webu 7 fe & to fherabe - ‘i i range. Ihe most common use of tk J a ina gwen nge.. Ihe most ¢c 4 Python scquiotss sna scquinte of numbers _using fy Syntax - range (stort, slop, step) o ; Paamelen ~ shart: L opHonal] ‘ Stop + . t 3 Sheps f cs Return : os Example - for ft fn range (5): . T ° Os paint (“tend = puink() f O]Pa 4 f One 3y4 : ~~ what the use_ of the Sange() tn Puthon ? é Oo % : = t in__simple berms Hange() allows Hhe usey to qenewake a t F . i Seis of no. within a given range. Depending Sn how é |_mani sugumenl the usd i patting fo the “Pr, the wey & f | can deetde where thay _seniks | of “numbers wits begin 2 en [Sas well a how a the dif Peuence will be between one no. and the next. Pf range() $M takes: can. be infltalreed | fn 3 ways — g = sane {stop)_ fakeb one anaqumuent. =_wange (stant stop) fakes Arqurveuk. zi sage (stout, shop, step) taker Wee angumear” g Date when al Fae will _qet_a__sentes of Sadudts every whole number up toy bul nol including Wee T number thal the user nas patovided as_the shop ‘ wa Example - Python range (6) Teh bsteleT 1 for i tn_ range (6)% pink (1 Gnd ="") paint) p= o1a 34'S Stop {lo siange (stant, Stop) - Tv ohen the user call ange) with — two anquncents , decide not only Oyhore the sente of no. he _usey gets bo lope but Valse whore it stasis, so He users don't have to Yi © shank at O oll the tes Users can use mange () to qenerak 3a susies of numbers fiom _X toy. S ¥ i v Python vtange (0,6) ce J > 5; = Tor Tol Tz [sTsfst Te =—+t apa - > Stat cea + ¥, Speral Date .... 2 Fok, sto} Exomple- Drmonsinatfon of fyihon stage (shat, step) # patating a natural > # cen rom 5 to 20 o fou iin mange (8:20): sos a . . Ly purnt (ty env: " f 0) P - $6724.10 Woes ty te re tt 1819 Tig wangs ( stant. stop, step) ; aL When the use called ange () with three angumenty the usey tan choose nok onky whee the cenPey of “___numburs will stank and slo bubsaltio’ ‘haw ba the 7 7 f diffuience will be between the one. no. and th¥ Oexbeg Wf tre user doesn't puovide Hhe step, Hhen stange () will _qutomatically behave ay i} the sep & 1. InJ ney i txample we antl -pitnitas even no, between Q and lo e i 2 So_we chosse our stoVitng paint Prom O[ start-o) and a : He —$ stop the sewfes at to ( stopYto) > for puinting an even f = number the . difference between one. number and the © fext number must be 2 (skp) afte. providing. a Step: $e ° i r z both U1 we a e fo owing output (0 2,4,6, 8), “6 Stant Python ange (0, 10,2) > 4 gd yer S oh EW sTebfelapol ~ ; or Ser 3 = Se ofal4 8 > eee EE ee Sperat = = i Date . brant - Demonstration of _fython afige (stant, step , Jon ‘in songe (8.10.8) paint (1, Send = © "y v ° paint () et Oe 0,3,4,6,8 Ty fon Loop in Python - fee ae 3 Fi ts used for sequential braves tee, th fs used Ee Gterating over_an orable |. dike Staing Tuple , dist, ~ Sek ox _D¥eHonary. => In python , Were is no _¢ style for Joop ‘ bes —for iO; te ny ttt). There is_ a “for" Joop which ts similar fo cach oop. in other Janquages. SJ UU * NOTE - In Pathan fous Joops vonly_itmplements the collection based. theWatfon. = i 5 Suntax - for_vow in__iterable:: aL oe #_ statements ~3 L Flowchart of. for Joop For each ikem in _ 4 z 4 equeace =e - True > ; > ¥ t Ext for Joop Date . once for each ikem: in’ an Tae fe woiable Vor takes the value the next ikem o| the Heable ty tach_Hme throw hi eat a Hag eg eae thon puogram fo. fllustrake { Le # “iterating “over a dist r rh Ve ("qedls, "Por", "“queke” [“qedks", "for", geeks ] : i lov Fin Ls a uF or a sp ees | le - | r Loop fa Sonne é @ Fi a c © 4 ‘heating over diehionar: oo one, . i int (“dfeHonay revelon" ; NS py PPT cacak_ ta pyttion = Vt fs used to baing FT ofthe loop _whtn some external _cofdition is _ tyfgqer SJ bueak statement is pul inside the Joop body en Waty _oftes if tondition). Ik terminates _ the tureint Jeep , ted a the loop _in__whrch_ Tk appears and resumes _txecutfon ‘aa \ statement Hnmeatfately afer the end of that loo inside ao nected Joop , the ft f = _tontrol_ouk | i ST the_nex I We break _shakement fs Ireak will Hyminate the innermost Joop . | {oop lesb expression be j ot | Lal False } 4 % Exit loop Lalo Hel a [a al oe 4 b owe |e Example - 2 S= ‘qeeksforgeeks! # using for Joop T ——— for_leter th s: prtat leHer) #: break Hie gov 's' HE letter = = ‘ec? oF leney = 'a! = break 3 ~ — paint ("Out of for loop” : ae ot iro # Using ushile 7 while True: 1 pyink (s[1]) 1 "# break the 1 # or 's! se, an loop { loop as soon ik sees ‘el t if SUTS =e" og SUJs='s's + pufok (tour of white loop") Out of Por loop +} | e Oub of while oop * Continue Stakemen} pnlasgla Bl Hilal @ & Js! at i: 3 foi in Python Ih fe Stalement tha} forces” to a loop contro} I cagdte the nex thera fo of the: toon while skipping the resk of the fode inside the loop for the currenk Skeratfon only y ey d See n> |! » ¥ Date 2 The _ceniinue executed in the Joop , he tode_ inside __tonifnue slater oh a 8 ict wil ‘evalton and the y "tonttnue paint (x) tT Howrhart of Continue _Stakement = fonditfor. True fo continue I: ‘ < Rene Continue | Teal False Erecuke the remaining aie part of Joo for vai in" Greeksforgecks": if van == "e": 4 . continue pint (var) iS IS + 4 bla el FLY 4 4 E14 ' whale ' ; i 4 J+ Nett Loop - With - for and while Date ... ave _akippin the point of _chavach ion checking and _contPnue states, ya situation when you need fo write a patate fhe number fvom 1 to 10, but not 6. } n Y x Joop from 1 to lo for i fh range (1,11) opt ts equal bo 6» + continue to_next Steraltfon without patloting tf Te=6: ; conHnue CODING BUGS C)NOTES GALLERY , else: a : # otherwise paint the- value # of 7 ; » pata (7, end =" *) ojf- 129 34 £789 to NOTE - THE CONTINUE STATEMENT CAN BE Used WITH ANY OTHER LOOP ALSO! LIKE WHILE LOOP” simiLaRLy AS IT 1g UsEb WITH ‘FoR LOOP” ABOVE. loops wer: Can 2a a create nested Joop. Nested loop means Joops inside a Joop. For example, while loop" inifde the ® for_leop, fot loop fnside the for loop , eke, ‘ at Searat sa Led, = Syntax = Ouley -loop Expression : a ' ya i) Inner- loop. Expression + “= Statement inside ‘nner. loop SE t : Statement Inside _ Ouwter-loop Example - m= £12] y= (4,5) for fin x for | tay: + potak (tf) } $ Sige 1h \s 24 25 Example -2 # Multiplication Table # Running ouler loop from 2 to 3 fort tw range (2.4): # Puinting! inside the outer Joop f # Running jnner loop from | te 10 ° 6 U ¥ * for {in _vange (1,1): # Painting! fnstde the inner loop paint (1, Wanye te bey) bea Se tal Ha) 4 Fo 4 Hal G LG ae # | Pataling taside the. outer loop oe paint OW f 1% oP - Dele gee WS ae 10 + RO. 2 Se Lede CR We Sie Oa 8 ie = i Speorat culty for Joop to "through _o_lish tem fa Ih # Painking outside toner Joo puinl (“stort outer for loop") # fniblaltze couler | with 0 0 # Running fnney while loop fo # MNerole through a Isha while (fz Jus 2S dee): # talating Inside Tnner loop pint (them © disk 2017) : 2 Inerementing the Nala of i je t+] Ht painting aie inner. loop paint ind for loop") O)P- short outer fox loop !_am_healthy oN | om fine | am geek end for: Joop slort_outy for Joop You are healing You ave Hine Sterat You one geek ae = end fox Joop fniMalizing two Iists with some a In_ nts example we aye z ching: Store the size _o} Jeska in ‘tisk 2- size’ using Vent) “Syoadlion and using tt in the while loop as a counten, J Afier_thar_vun Son outer for loop _to_ iterate over VstI_ ond inside that loop un _an inner» Joop _to__ikerate over rid using _lish_indexing inside that oe laters ipitabea Teach val sof Wst2 fy every value of lish. d a Functions in Python - SS Python funcHons ts. a block of statements that veturn the _sperifie task. ; : The tidea is fo pul some commonly or repeatedly done Tasks fogether and make a puncton Go thal | tnttead of wailing Vthe some code again and again for different “S inputs? we can do the funclfon calls” to weuse code t * wontotned in tk over and- oven again. = sa = = ~ Syntax - Python functions ; J a Keqword Function name Pavamerers, * t > + ——. + a det functfon- name Cparameteus): . iy « T a # statement | ————> 8edy of j Statement —=F = sucturn_expresston 7 f = f x funclion xetorn + Spaat Date .... Example = def fun): wink ("welcome fo GF Gr” 3 ve Dever code to calt_a function fun i off - welcome to GF. Defining and calling a funetfon with parameters: < Ae Defining’ ‘ 1 Syntax - de? Punctfon- name ( paraniele : data. bypr).33 Aehurn hy et 5 DSvtng i # body of the funchon * q a aiturn expression > { = si Example -_ # some more functfons f a def fs- pute Cn): = Spo in (837: a Mehutn Tue a if (né=1) or (nm Jo a=-0); aia Aehurn False ey 3123 # Pao gram to everse ashing eS a = — geeks forges nt tc se (gtg 1) SF O/P = Skeeqrofskeeg J d _* = Sbiing Slicing _- 3 To aNess a range of - chanacteus in the String oe fe 7 oo ° ° of _¥i Phe method of altcin is used. Siteing tn a String ¢ ac_done by using a VSiicing operator o colon). 2 U qt a > - Example -_ Suing |= “Geeks ‘or Geeks” a path (" intHal_Shving 2") ae iat (String 1) g = paint ("\q Sifetng characters’ for 3-19:") oN paint ( Sting | 3: ta]) x palnt( "(no Sita chavachers between” + gt 3rd Vand dnd fast charactey 3“) pink ( Stuing | [ 32-21) one ae v u Ojp- —— IniHal Stuing — Z Greeks For Gecies Te _ a rene i __charackers fyom_ Sly a geek a Stieing characters between 3rd and dnd) last char; ksFh Gee = chal) function - lt yeturns a string from a Unicode code Inheger, Eq - paint ( char (.q7)) Orie o/P- a + Escape Sequencing in fython — : J 7 | While painting Sting with single sand double quale | in it couse | SuntSkervor Ubecause sting already contafas Single and Double Quotes and hence cathot be Spain ted J with the use of either of these. a String either Triple sequends 1 Heiney fo pwiny) euch Quotes are used: to Qyt used fo” paint such shings. t Escape t = Shing Concatenatfon using + 0 This Operator canbe Used fo add multiple string _toqethey . Howeved the Qigumenks must be a ia shinf, ues the 4 Operator combines the shing thar > is Vetored ta the. vaw! ai trator ~ Vax} and vay 2 and ao ref rs Another vowfable vay 3, : 7 NOTE ~ STRINGS ARE IMMUTABLE THEREFORE Ww * : sies 1 WHENEVER IT IS ™~ Date ... yf a re CONCATENATED, IT 18 ASSIGN ANEW VARIA index () method - Ih ollows a _user to find the Index ot the first occurence of an eefsting substrin iven stating. ¢ instde 0 SF Suntay.- string S obj. index (substring. begp , endp) Parameluis - + Substring = Ihe string to be Searched for. a : crap U{arfoutt :0) 7 Inks to speciftes the — TST position from where search has to be _ ! sharked . : endp(_dttault : length _of shing): his f” aes Teagpechies The ~ posttion [yom vohere ~~ rT grarch has fo tnd. Se Return - Returns the 4st position of substring found Exceplion - Raise valueEvror ip _arqument Strimg ts_not ~~] ct found or index ts Sut of ranged SS : u qee_uindex() method - Ih Mehurns the highest index of the oy substring _instde the string if We substria its Natuetrror. found. oWNrwise , fh natses } Cose__ Chan ing of Strings - + Jowert) - Convert all uppercase _ charachens tna Pt string into lowercase» * upper) - Convert all Jowercase “string into uppercase. ‘ «Hee = Conver™ Sting fo Hele case. $ characters '7 | a Slowly wtth OQ. &_endswilh () [3 bullh tn methods = in fat 0 Femetnddl - ith te returns the he _lowyt 3 ee of the substyin _ it this of ong, OA then ih & a avin nang. pits Th ts not penne then a ee Pt diner Be le intax - sla-obf. find( sub, start, tnd) Gubshihe that need to WE starched x isk Introduction Python lists owe just Jfke dynamnfcally steed aways,” declaed fn otht Jonguage © (crt, Tava). Ino simple lonquagt Sie tee collection of tings enclosed ‘with EW ahd separated by comma, T The list to sequente data type which ts used ot 3 fo store the collection of data. Tuples and Strings are other ly ts_of Sequine data type. Ut Vou >" Geeks" "for" “qeeks"] patot ( Vax) 2 Pe [Geeks for’, “Gecks'] STEEL » © — Date ... ae Lists need mot to be homo neous always witch meee Tithe. most powexPiil tool in “Python. 7 ss stngle ist may.contain Data Types RARE =x ew welt _asJ objects - = mye ave mutable » and hence, they tan be ~~ cuen apes they xeatfon . —~ =, ©, = _— = __Girating a Uist in Python = = Til ean be created by _just pladngq the ay sequence _inside__tne square™ Graces ti. UdIke Sete ab atst doesn't need a butlt-fn funcfon for the > 5 7 cxeation of a ist. So Example = Uist = C2 —>. : point (* Glank tisk =") ‘part (7 Ufst™) Lis¥l= L 10, 20,30). C2 \n ist of numbers 2"): ish of numbers? Lie ,20, 307 = S paint 5 pain (utsty - > ole. Blank list : > ti > a= Acessin clement from the fst - o Lisk = ("Geeks “For, “qeeks"'] pautal(" Accessing a clement paint (ifs Lot), paint (ifst C23)

You might also like