0% found this document useful (0 votes)
48 views

Complete Python Handwritten Notes 1695805594

Uploaded by

Syed Abdul Rasel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
48 views

Complete Python Handwritten Notes 1695805594

Uploaded by

Syed Abdul Rasel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 77
e PYTHON \ PROGRAMMING NOTES | Choe a 7 my Tee HON. PROGRAMMING =~ - Py FS Intuoductng Python - = x ds : . 5 3 = ee ras boo ae quale purpose _an vet. opulay Mogrammt angua __ cS = lt ts beth 4 wd fn d ot development, Machine Learn. ;> - ta appltdlin ete. oa <- ur Programs oye general J 5 ty smaller than the thes pxoqramming danquadds . JS Programmers Thave “ba Uiype sielatfuely les and the indentation requivement of the Jangua: ce, makes Men Headable at: the time. ! md p> Voi Simple Synkax. 8 Fasy to learn, g oT UT = ji pufat (“ wettc”) | rm = General pupose Janguage ( Simple yet very powerful language) i > console Applfcation & Scripts a ne > Desktop Applfealfon 2 B.. E> Web Applteation a a Game Development . L, Machine Learning sbeeptearnine, AL, 64 data eh Pr Mattinaradtgm Support = Puocedural Style Programming Ike Ce 5 = 00Ps [fhe Javan Functional Programming ke Uist. v == Portable or Platform Inde, endenh ; brsk - Pacsrams are interme date __the _Snterp neler. Peal Psa y code, compiled fnto an f then the Code fs yun by —> Dynamfeally Typed eS, ae qe” J nas This feature w 4 one statfeally YF ed. In python we don't have to specify name. But the disadvantage inthe yun Hime’ of the move chances of yun eels") “python” ~Py different prom oS. a in this the ty pe o puoqram , so to Hme error. Automate _Uarbage Callectfon the Ct 2 Taya. they vayfable 3 & asstqned Here are {t means when you dynamfealty allocate memory | So__you don't have worry to“ vealtsing thts uU o memory . \ s > Popular Applfeation Built ta Python \ Youtube) Netfife:,” Quora Inskag vam , : DoropBox ‘ _ 4 | => __butot Oy fn Python — $ A__funecton & a_sek_ of TnstracHons' thab fake “ Some _fnput from f ww, do Some work Seezat On those dow | "YT pouemetets and pucdure some j a Example = paint (“Hello”) ~~ jt (SN wWeleome”, “i > patat C) _ whet mr os, pafal (“ope you are enfoying fy thon") | 3 ae Ourpul - Hello > Weltome to GEG = Sy Hope you ave safeyting Python Le — > snd4H end _and sep parameters fa paint paint (i welcome”, end =") pafnt (* to GPG) Output = Welcome to GPG ro End parameter __teates Space _and. ih fetta a shoutd be purintin afte: tks prtating. And fn sep pavameten when we have multiple r—t input parameters we use sep ito Separate tiem. sl ds ll db & ul 1 By default Wey “ane sepanated Tey space. t J a fq- puint (“io", wut , “2023",) Sep ="-") = Output = 10-04-2043 J Sperat - BD “=> Nawfables Pn Python = — ———— — __Naxfable fa name that & Wied fo sefer to _memoy ___ dotatfon. Python vawfable also Known as an tdenlt -ffew__and> used to 1 “|w-python, we don't need i speeffy tne _type of 4 vasttable because Python & a_fnfer language ond } smant enough to get vaxfable type « i old value - 8 Example ~ pufee = loo * I tax = 18 bt | total - psitce 3 fositce + tax z puot (total putes) * a Output ro AS, 4G How vayiables wok 2 3 4 = 10 to]<— * y= “geeks” [gem] $ % z= “80 [go[<— = 4 : § if we say wez When soft % wx 4 but TP W= 30 Bole w 4 , patat_( *) Olpcke 16 a patok Cy) _geeks 4 patol 2) ay " —A paint (we) 20 4 q poe ieee Perea ~~» ee Pathan Dynamically Type eee 5 a Bo m% +10 $ J putat (>) . nk: “geeks” U ya paint (>) ~ 10 ~ qeeks ~y 7 ~ 3 Note - using a_vaniable without assfaning fk cause error. ~ &q- paint (x) » oP- Name Exror : name ‘x' fs not assigned ~— ut) tn Python - 4 3 This functfon ‘u__used to take fn put fiom the user } t Example - name = ‘input (“Enter the name >") 8 ” psiink |" Welcome''+ name) t ole - Enter the name = Himanf Welcome Himanf Example - # Python program tor _additoa ' t | +t = fnput (" Enter Fiect Number :") 4s input (" Enter Second Number : sy m= fat (x) We int (y) Hes ney F Spat print ("dm vee) vy lvl aoe lyl e blew lel Typed) In Python ~ Outpul = Enter Pirsh Number we rom string . Is d Type & a _bullh-in_function that Hells se h0 wherever we have to A you data lupe of a “vavfable or a value. i Eg a=10 : a (type (a)) = 10'S ‘ re Ciypecay) r C2 9437 puint (type Co) ; O)P = dais, tints § <= class, 'floatts <= class, ‘Complex'> T =n python we use "None" Io Whe value uel or we dfdn'h asstan any value fo thy voufable > g : é 4 indfeate that we don'h know § “ \n_ python there 9% h te no chav ype you w wank ft a. aga, reuld Eg - Sky_= “gtg" (Shing § fsa sequence of chav), F paint (type (atry) J [.10, 20, 30) (_@tray and dynamfe ally patol (type (19) add and vemove thee. st Irems are stored fa conte. ~nuous locaHon) Storae ~ re eae $= {10 30,30}, “difference fy modi Sek_& a _collecHon of _ Ss pint (type(s). where all thems are _ = t and set UW dike mathematical Set) y “ w Oyu », as J ~ dz fio: "gfg’s 20%" ide" J dicfonaries ore uscd to_do a paint (type (a)). ings. Jhe & a 7 3 J collecHton of key value pairs) > Eq- thems : porices rollnot Name. ai > p> Type conversion in Python - Type conversion > se 3 Implictt ExpltetF a fat !0 €g- 4 "135" os J= 1+ dnt (s) > ‘it (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” wT SJ » paint ( Jist (8) > patnt (tuple (4)) Py pafot (sek (43) : p= tigi. tet fet ht Mt] a 1's") sini (bin(a)) spat (hee (aes Ta “st [od (a) q 27 22 —, H bi _oP = __ Obl o100 ao oxty ate 4 0094 Comments tn Python ~ We may with to deseutbe the code we develop . We § 1 might whith” fe take notes of why a__sechion of cauiph fo, for fnstance. Formulae polocedures and sophistfcabed : business Jogfes are bupPeatly explained with comments, & uv vr J 4 Single - Jtne comment - # 4 Mult? - Jine _commenk - _# or ' # m7 < boc-string — The string ehictosed in _trfple quotes 4 that contes _ immedfatel after the dettned fn ante failed Python Doest¥ing. “ v u > SS SP_ib, else and eli? th p, thon - os 4 Shute come uation in dead Jife when we need lo @ do some Speciffe task and baced on some Specific & condftfons and, we decide what «chould we do next. : Sienilarly hee coma a sthuaton Pn Pxoqramméing whewe a Sepecite tak ‘ste be petform ed if wo spectre « Condiifon true. Seerat poli slaltments can be ui In gue cased in. duthe | tose oi slalements aves Ft il Wise cn Mousele : wdc > ~ Naked ff - ipeelif statements . » - al GW atatement - inthis ff the condifion & _frue thea iP the _elte powtt execukee any powt executes thse Syntax - if condition + # Statements to execute ff # condition &_biwe Flowchayt ~ 4 3S False ae Trane, ¥ Statement fust tli Hi Y TOPE IML OH YL @ @ IG Example ~ if 1075 + y pufnk “10 & greater than_S"') ih patat (* Puogram ended) OJP - 10 U_qreatey than §- Proqvamn ended Date .. ff: Statement the add?tonaf slatement which _perPowne/* iL-else statement ~ _n_ condftfonal block an code ry & hue ie ele: _ _s 4 # Erecubea_this_block if 5 } # condition & false j a 1 Flowchant = 4S fer oe 4 [nay of Body of-elce | = J ¥ 4 Example = HS a Rae=us i pafnd ("yea") = * else: 4 pufat ("No") 5 Example You can also chain {P.elge statement with more than’ one condition. 4 Jetten ‘= WAP 4 SP dette = = "g": ° paint ("Jetty & 9") a elses TE deter = ="¢": paint ("dette tc") Sy ™~ we elses Sp iettes = : Span Craton ba") fi dneiu Sue ‘ ele ; Jette unk: AS and ce” it es cao = 3 Fo? - deter UA Nuled_Y Statement - if statement _can_alte be checked inside FY othen_ if statement. Thu _tondiHonal statement G called a —~J_nested if statement. thuu_means that tnnen if condition will be checked only iP outer it condition %& true and by thu, we ean ste _mullple condone fo be sahisffed > gyntoe - if Ceonattion 1): ~~ i, # Executes when condiHonl W_fuue . ip (condttion 2): ~~ Executes when condition 2. true ~~ # Wf Block t end here ~3- # if Block &_end hee Example = num = 10 it num > § : J putnt ("Biagen than Ss") ae it num 2= 18 5 paint (* Between § and (5") — ole - Bigqet than § + oetween § and iS ite eltf 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- elf ctatement tb __frue. Y Spnat Date .... Syntax - tp (eonditfon) : Statement clit (condition) : = stalement elses pee statement a 8 Example - Jettey = "A = ip dete += "9": 5 paint (“Jeter G6") < elif detea == "cs . paint ("Jeter & 0”) . elit Jette == "A": wy paint Ct Jetten A") * elses paint (" Jeter feat A, 8 orc") ca O)P- etter ba * % = Asitthmetfe operators = They ane uted to peporm mathem—_.. [ =aHea) operatfons dike additonal, subtrackon, multip. -lication, divfefon. , & There ate 7 oiithmete operators fn. Python - i e o0 ° v ° = e—_)_ Addition @®_subtraction @_Muttiptteatfon B® + biviston © Modules @_Exponentfation _@_ Floor _divtston j ior ao S “wy “a ei Addition Operator -_In_pyth ° yO ee odd to = 8 values: Bo Example > volt = val2= 3 a acs es 2 vali t val 2 ST paint (xt) Se = Ss ptvalor - used fo subtract the atcond value from =° Subtraction 0 the _fint value. 3 Example = vabl=$ val > 2 ‘ a des = vob = val 2 ~~ _puiot { ses) ae Modulus Opuiator: — Pfo ik _the modulus, opuiator ured to find fhe _yemainder when first operand u__divided by the Ss second » 4 Example = val |= 3 val2 = 2 > dea = val l Yo vol 2 =o patat Le) > ale = 3@ +t Exponeatfation Operator - ** & used to raise the tirck _ operand, to power of second. “> Example - val t= — yal2= 8 -> ves = voll ** va 2 _ print (ves) < ge - 8 Date ... + ® Floor diyfifon - // Ss used fo find tne floor of _the ustinh when first optyand te divided by the second. Example - vall = 3 as dis Eps pe a b Nald = 2 ib Uh Mes = val t// val 2 ie bh patot (es) ge bs 7 pee ojp - Pa es __ # i=> Puth logit 0, ith Example ~ 3 ‘ython ogica) Opevators with ample - Operators aye used fo pot opeiaiions on values and vawiables. These ave the silat symbols that 0 and b>O: Date ... Sty aoe ond puto [Ye mumbo ane ne _qutalen than 0") elses ‘ palo" ANeast one _qumber t_not rebel uiianmOl ye axe qreaten than 0 = ofp - The _numbers Atleoat_one number Uno greaien than _o. a Example. le = a= 10, be lz y b _ Fc cz 0 ft o and b and c: paint ("All the numbers have boolean value os True”) else: paint (“Aikast one number has boolean value ou False DIP - Atleast one number has’ boolean value as False. = Logical OR - lk -steturns Tue tt efthen of the operands & True. False Output Tatue Output Example = az=lo + be -10 c=0 4 if a>o or boo: : f - - LHS paint ( Etiben of the _numbex_t& gusalat than _O _ — else: else: a pint ("No number ui « OP = Eihhen of the number ts qreatey than O No number greatey than O. J -__Example a= 10 bet? £20 _if aor bore: print (“Atleast one number has f Tue") boolean value at else: p» fnt (AN the numbers have: False") boolean value as OJP - Atleast one number has boolean value as True. = logfea) Not operator ~ woxks with a sfnale boolean value. re the __beslean value. & Tae th steturds Fale and vce ~ vote. soe Not % Tew. Faise Th False o|P True op Seeree ~ Date Dy i tat (" ae a a Te, gilf_ net (ated er 0 ones fete. ee wig nol dlvtitble by etthey Sor 5") ches a paint ("10 divible tithe dor $"). : ojp- 0 4s divuible iy tithor 3 or §*) Jie Oude of tyalualfon, of Jogtead operator ~ In He cate, “atta “lige optralors, Python always etaluates wh expression hom eft to nahh Dd ye Example = act ordut() : + paint (* Method called for values", x) within True tf X70 ele False ~ as order ¥ b= order cs ord a tfa(-t) or b(5).o¥ e(10): 3 pstok ("past one oh the number _fi_posttve") j + 5 OfP- method called for value =-I > Method called for value = § _ Alleast_one_of the number t_pouitve, 5 dor i =>_Python Membership and Identity. Operators - valtdate Python offers tuo membership the membership ofa value ina sequinte, tuth_at ctv sts or buplet . oputalons to_ check o4 It tests for membership. in opevaler > dhe in! Sptrdtor “4 used: Jo cheek Ifa thavacy —dsubstring | clement. exists Ina sequence or act. fvaluate fo “True jf th finds the specified element ina & ts E quince otherwise False. ror ey. j 'G! in_' Greekslorteeks! at Cheeking ‘4! fn_shing g Taue in_' Gtekstor Geeks! | i # Checking ‘9! fa strtng afnce pyth Mt case-sensitive | return false 7G st False Example disk! = [1,213,457 a sha > [6.4.8.4]. x item tn dts ip hem fn ster : : sink (" oon ‘ P in (Coventapping”) § else: w ow ' % print ( At. overlapping!) 4 OP - nok soo nok ; nok a nok a“ not - 4 ence and false otherwue. T “fst = [10 20,80,40, 50] Fs. 7 lx nol tm dist): é _palal (2. 8 Not pucseal_tn_gfven ssh”) ee else: J ink (x fs present in_given Jfst") 3 itty in Wsk): “4 int ("y fs prestat fn given Jit") A else: ~~ paint (“y ts NOT pyesent fn_qfven fst") t J t v g|P- x f& Not poitsent fn gin fet. 4 fs_pnesent fn afven list f J = \dentity operators - Thty ane used to compane the obfeck ff bol the obfects axe actually of the same data tupe and Shore the same __memor Jocatfon. SC There ote different dent ty operators such oa Ms! operator - Evaluate to True if the vaufables on efther side =) of the operator potat fo tie same obfeck and false | f otheiwise . Example - x= $5 ap yes paint (xf y) % id (x) fay) OP = WOTDYS 86677032 _ $o70us #667203 Hue, in the given example , bolt 5 assigned fo fh and both Us which why vidurn True. : : Ss nat! optuator 1 fe folie ifthe vailables on elthen side 3 1 of the opetator differnt objec ond true otherwise. 4 + Example = w= § , a ip (type (>) fs nol fat): ‘ + putat (C'bue") =~ 4 else: = 3 paint ("false") tr # Puinks Tue + Ke 6 5 if (type (x) tssnot fab): * q paint (“true”) = i else: & i : puink ("fale") = * H . 1" t ” OP - False : s * Taue f m =e => Puthon Bihwice Operators: — i & Operators are__used to perform opetahfons\ on values S. an wortiables . Shese_ aie the speci —tymbols -dhak cariy . ° ° . > out anithmebfe and logfead computations. dhe value und > Operator epetata on ‘is _known at Optrand . & * my, Date w2..0ce Ee fs gs 2 Bitwise operators — Return | ff both the bits one | SJ a)- _ Qthwise AND 1B ers _ & else _O- cite eratiele = aw le IOVS. ( ginary) SE be 4 = 0100 ( Binary) < asb=tolo ras 7 ee ~~ dloo 3 = 9000 3 =O (decimal) ¥ : “ 3 S)- Bikwise OR (|) - Returns | if vetther, of the bik & | else 0. > Example- _@= 10 = 1010 ( Ginary) +3 b= Y= 0100 [ginary) s alb = lato \ > o1oo * = Ilo 5 =14 (Decimal) 5 _)- Bitwise Not operator (+) - Returns one's complement of the no * Example ~_a=lo=10ro ( Binary) : 5 was clolo = -(lorott) 4s = = (1olt) +s- =-1_( decimal) > 4)- gitwi i {)- Bitwise (oR) (A= Relurn_| ip one of the bits fs land the Re other UO else return O- s Spat Date .... 4 Example - a= 10 = 1010 (Binary) : b= Ws 0100 ( Binary) orbs I Sepiin See — ig e “a O00 = Io a =14_( Decimal) Example - a= lo bey é # Puint bitwise AND operation s wint ("as be ot b) # Print brtwice oR operation 2 paint (“alb=", ays) te + Putnh bits No7 operation ey { palat (“was ~a) ss : # Pata bikwhse xor operation ' paint ("a*b =") a Ab) 2 | i F ofp - abba ajb=ty 4. hae-tt . a*b=14 as ! ao @ Shift Optrators = _ Mese Operators ane used fo shift the 46 bits of a number eft ov wight theneb multiply fn ox_dividing the no. by two ve. ghey of be used when @ we have Gig mulHply” or divide a Number by jwo. &. wo —2)-_Bihwite Right p Shiph (>5) — Shits the bth of the no. fe_the sight and fills 0 on vord eth (fils Vin the x fase_of a negative number)ia a Hesult, Similan of dividing the no. with some powey of two. Scrat ’ yy bam lea a=lo= 0000 1010 ( r iy — eS neat a>>} +0000 OWI = 5 —F ‘Examplt_— az-1o = Mitt ouo { Binary) o> he Vit lott e-$ Fy. pitwise Left shift number to the left and fills 0 ~S Shifts the bibs of _the on void right as 6 vesull. Similar effect at of multiplying a the_no- with some power of wo. v ¥ Examplt_ = a+ + 9000 o1ol (Binary) 3 ac<}] +0000 loto = 10 % a42 > O0O0t 0100 = 20 ~ Example = b=-lo-= NN ovo ( Binary) ~~ bee | = 110, WOO = -20 > bee 2 = Ot tooo =-4O Ta _Bitwise Operator Overloading - | Optrator Overloading means t si S giving’ evtinded meaning beyond their predefined opera = onal’) m¥aning. for example operator +f used to add two Tategers at Well as fota two. string. and merge two lists. Sy) o aahtevable because the +" Uperator is Y overloaded “5 _by int class and sty class. You might have notfeed that Qurloading. _* : — Example - class eek (): = def. fnft— (self, value): i: self. value = value s def. and (self, obj): ¥ patat (T_And_optrator overloaded") Sperat Date .............. ‘ i} isinstance (objs Geeky + selurn self. value be obf.value else: ; > ~ Mafse Valuetrror (" Mus) be @ Object of class ¢ def or- (self, obj): ae pxint ("Or Operator overloaded”) “Eg fstnstance (obj. Geek): yeturn self. Value \. obj. value a else: sate ValueErvor ("Must be o. Object of slass Geet def = ror (self, obf): 7 payin} (" XOR operator overloaded) ip tetnshance (obj. eek): Yeturn celP. value * abt. value else + ratse ValueEvror (Mast be a obfect of class Geek”) def. Ishifk. (self obi): 5 print [hips operator overloaded”) Ff fstnstance (obj, Geek): Helurn selP. value ze obf. value else: : yatse Value Error (“Must bea Obfeck of clase 4 i eek" def -tnverb. (self): : a patint Clnvert operator Overloaded") 4 Heburn ~selP. value 4 #_Duiven's code IP name ==" main"; i = Geek Uo) a be Meeks (12) 1 paint {a2 4) cs ink (a | ——— abe Crh aint (ab) si - puint (as>b) Me _ ro paint (xa) ” 3 _ Pe: And operator overloaded 8 r~ Or operator overloaded 7 ir > Xor optrator overloaded i & a Ishifl operator overloaded im 4060 na vishitk operator overloaded 8 re Inver} operator overloaded ll | Ue |e vt ae Ee Te _— while loop - It & used fo execuke a _bloek of stakemeuks Atpeotedly until _o given conditfon. datisfied And when the cond?Hor — becomes “false tne tne Inmedfaely often tre Loop inthe pangraut hexeuted » Syntax - __while cxpatcasions : Slatemeut { s) Flowehant TP Ener whITE Toop exit while loop While Joep ally undey “ tar wt dot ~ Indefinite “tedation means number of Himes the Jeop & i execuled _din't Specified ex} ta, in_advante. : L Statements Atpytsnks al) “the statements indented | same__numbey cf chaackey spaces often a H—tonshud axe considered — fet be Le code. futhon uses indentation inde tti flevahon. by the pogram mtn asi of a stale blovk of as_tk methods J of gtou fia slalemenls. When a while Joop ik exeaited”, exp 8 if +traluated tna Boolean context and if th ty bre, He loop « body U_ executed. dhen the expt be checked agatn ho Bask. S aMite baue then the body | executed ain and th continua unt the expuearion becomes Fatcoe 1 & Example -| count =O a while ( count <3): count = count +} paint ("Hello Geek"), OJP = Hello Grek Hello Geek Hello Geek sa 3 - _ ~~ ae Joop over a dist thak la this, we have wun while paesent fn the dist t J wit wun until there & an element = Fxample-5 Single statement while block xXample - ingle stateme oct > t J Just _Jike the Block, ff the while block _conststs of efrvals yi statment we can declaye the entire Joo ina single Jfae. | there He multiple ckatements fn the block Hrat mal up the loop body they can_be sepanated by semicolons 7 qe count = O while (counbé 5): count+=15 putnk( “Hello Geek") t o}P - Hello Geek Hello Geek. Hello eek Hello Geek Hello Geek 7 Sparat =_siange L) in Python = ; c ( % :. ence of numbou The thon ed) fr seb s seq see} A ina waa” anaes aid most ¢ommon use of ft & to fherate - ence of numbers usr Python Joop “ange (stew, stop, step) sequen tes T Payamelen ~ staat: Loptfonal] ~ shop + : Sheps devuwn 7 3 s Example - for itn range(5)i a : rat path end = +) i i paint) & f oP = Yona 4 “i what _& the use of the van e() in Python ? s E tn_simple terms, ange ()_ allows the use bo genevake op Svifes of no. within a‘ iven range. Depending Gn how. é \ many aiguments the usey passin kot the Op, the use © | can" dectYe where thal seutks of “numbers whl) begin 2 end, as well _q how big the diPPenence will be behween One ne. | andthe next. Pfhon range() fm" Jakes. ean be infttalteed © | aE: pans U : = sande (stop) takes one anquiuew, panes {stast, slop) takes + = uatae (Cs touh J arqurveudt slop, step) takes Wee augumed f 3g fg olsl & le 3 O)- Sat = al ae ote acs ~ + Fhe N_stange) with one _arguwuewt . the a ae will get a soutes of numbers tat _stavtts “al _O and ~y_ tnctudes coal whole number up fo, bur nol including, Woe ~ je__Tncludts__evel : I venben thol’ Ihe user has povided as_the slop. Example - ~ Python range (6) J Lo ‘yatslals| Te rip Sto Example ~ for i range (6) paat {1 end = \ pink) rO[PEE 0 LHe gus = sange ( stay}, stop) - TG * When the usey call angel) with — two antquments the use gets fo decide not only Guhore the foie of no. _ Stops but J also whore tt stants, so He users don't have to 3 shank ot-O oll the -Hme. Users can use nange() to gqenerak 3 a series of numbers prom X toy. 2 Y ; Python vange (0,6) se) ee Ts Tats Te] ay f tant t * Stop Fi Seerat Date ... ° Fark, sto le - Demonstration _ of Python range (ear =) # puinting a natura i ‘numb! trom 5 lo 20 cS ta fou ttn. ange ($140): it paint (i, end =" ") O\P- $6784 W913 Wis ke 18 1 tee wanas ( Staub. stop, step) a A When the uray called ange wsth three ayguments, the usey can choose not on whee He cafes of fumbuis will slaak and cto > but also how blo the | i diffurnce wilt be between Fhe one no. and th Nextg LI bre user doesn't provide the Step, then stange () jee sti automatically behave gs if the Sep 1. In this fxample, we ard puinting even no, between O and lo, & So use choose our stoViing point from O[ start*o) and 3 Stop he sewits al to { stop! to). for painting an even number’ the difference between one number and the © Rext number must be 2 {shep a) atten pacvising ae step = get The Jotlowin output (0,9,4,6,8), as d id ae Python stange (0, 10 ay > ‘ é ao a Stop fas PhEEEE OEE 7 or = = & & ys ° M3 Tage = a Example -__ Demonstrabto of futhon a po Jimeno e a on tin Nange (01042). “ 2 int (1, Send =") ws! aces pais a 5 ese GP 0,9,4,6,8 << J, fox Loop in Python - Fon _ecp ee 3: WW fs used for sequen tal biavessa fe, th fs used 3 t ei 3 ox iterating over _an__ ittdable Jike _ Stutng , Tuple, Jist, th oe J Seto DRHonary. = In_puthon , Whe fs no C style for Joop few, for (i:0; fens tet). There is a “for Joop which is similar fo cach loop in __ other lanai eb. : = _ NOTE - \n_ Python, fous Joops only stmplements the collection - based thevalton.. SS i 9 Suntax - yvox in iterable: _ J #_ statements ~3 Flowchart: of for | Joo) _4 for each tem in ; Sequin a A — Last tt Tnue > False 3 Spiral 1 Exit for Joop Date ...... SS age eS objects ike diths Irctton the Heable tsa a ue ; luples. the fndenled statements Inside ue Ox Oop e_ereuted —onee for each them. in’ an itenable. She woniable vay lakes the a: of the next item Of the = __# Python _pwoaram te {ilusbrate i Ls # “thrating “over_a Ish 7 ee lee Md ' : aint t 3 or ‘ PU Teg ey + p L : therating over dichonar: : wink (“dieKonay IHevalfon'" " 4 de da) . b d {abc} = sug ~~» pe Date PT taak_tn i - Ib ts used to bat bak Jn_pgon = tt _id_tn_bnlng_| a Hoe _Joop whtn some external cofrdtiion is ts eof atton Psp__butealt hy statement ix_put inside the Joop body te ene aftor_if tondition). Ik terminates the current iS the loop. fn which Th pears and resumes weihian an Fine _next_statemenk Trmecfalely afier_the end of that loop ~F_ lf We_breale shatement ts Vinstde a nected Joop , the treak will Hrminale the innermost Joop. t 2 33 a Toop test False =o Ss 3 % Exit loop a 3 Example - for f fo range (10): a; pint (tT) 5 it bas reak =3 ojP- 0 s 1 oe 7 2 Eyaraple-2 S= ‘qeeksforgeeks! . # ung or" Joop Seat = —— for_leter th s: prtak leHer) #4 break Hie gov 's' HE letter = = ‘ec? oF leney ="! = break 3) ~ — paint ("Out of for loop” : ae ae ass iro # Using ushile 7 while True: 1 pink (s[1]) 1 "# break the 1 # or 's! se, an loop { loop as soon ih sees 'e! t if SUTS =e" og SUJs='s's + pufok (tour of white loop") Out of for loop +} } e Oub of while oop * Continue Stakemen} nlasgla a Hilal e@ & Js! at i: 3 foi in_fython Ih fe Statement that forces” to a loop contro] I casate the nex) thera fot of the: loop while skipping the vesk of the fode inside the loop for the currenk Skeratfon only y he, d See n> |! \y oq My on tne _cfnn We Is Me Joo pot Mesh Yhe continue statem statement ollo \ “for the ination and. She continue print (x) 1 Howdhart of tontlnue Statement = | Ss ~ - vy 32 aS = ~_ fondi ow, True * a = » 3 oat a > i fe conlinue . mes [continue | iterahes False Totxecute the remainin part of Joop for van_in_“ Gieeksforgeeks”s if von = = "es “1 tontinue paint (var) caceae Spinal £ k Date ... en_you need fo wrtke a # patale fhe number fvom 1 fo 10, but not 6. } A ' +a slualion = = 3 akipping. the psitnt of charach ore _ skipping paint of x _Joop from | to lo for i th range (1,11) # ip tts “equal to 6) # continue to_next Steratfon 2 without _pyintin tp tee: d “tontfoue else: i # otherwise paint the: value # of 7 ; » pata (7, end =" *) n checking and _contPnue__ states, of- 12 3 4 578 4 10 J+ Nett Loop - With - for and while NOTE- THE CONTINUE STATEMENT CAN BE USED WIT ANY OTHER LOOP ALSO LIKE WHILE LOOP” simiLaRLy AS IT 1g UsEb WITH ‘FoR LOOP” ABOVE. loops we. can { ‘ a create nested Joop. Nested loop means Joops inside a Joop. For example, while loop "tnifde the ® for _eop, for loop fnside the fox loop eke. é ie Searat fa LJ, = Syntax = Quley -loop Expression : a ' ye Nyy Inner- loop. Expression + “= Statement Inside ‘nner. loop ne t : Statemenl Inside _ Owter-loop Example - m= £12] y= (4,5) for fin x for | fay: + patak (tf) i $ Sige 1 \s 24 25 Example -2 # Mullpltcation Table # Running ouler loop from 2 to 3 fort tw range (2.4): # Puinting! inside the outer Joop f # Running jnner loop prom | te 10 ° 6 U0 " * for {_in_vange (1,1): # Painiing! fnstde the inner loop paint (2, Wanye te bey) bea Se ta] 4 Ha] 4 fol Hal G LG ae # | Pataling aside the. outer loop oe paint OW f 1% oP - Des geek WS a 10 + 0. 2 Se eS oe ee CR WE Sie Oe 8 a; = i Speorat outer for Joo Uy or _ilem fa bl: levabe ois # Puinting outside toner Joop es stat (% stort outer for loop") # Soital’ne cout } with O tO # Running fnney while loop fo # theralt through a sha while (Pe Jisk a* size): # faiating inside inner loop patind (tem JJisb 2051) ; # incrementing the value oft feaeal ' + patting oubstde _fnner loop + paink (end for 2p") _O}P- _shovh ouler for loop 1am _ health | am fine 1am aeck end for Joop Stayt oulty Poy loop You are health You ove fine Sorat You one geek ———t = end fox Joop niftalizing two Iists with some a In_Ints example we aye z ching: Store the size _o} Jeska in ‘Wish 2- size’ using Vent) “Syondlion and using tt in fhe while loop _as a counten, J Afier_thar_vun Son outer for loop _to__ iterate over WstI_ ond inside that loop un _an inner» Joop _to__iterate over rid using _list_indexing inside that oe avers puinbta Teach val sof st 2 fSy every value of tisht. d “a _Fanctions_ in Python - SF Python funcHons ts. a block of statements that veturn the _sperifie task. ; : The ‘idea 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 “SF inputs? we can do the _funclfon calls” to weuse code t * wontotned in tk over and oven again. = say = = ~ Syntax - Python functions ; J a Keqword Function name Parameters, « t > + ——. + e det functfon- name Cparameteus): . iy ‘ T a # statement | ————> 8edy of j Statement ——) = jucturn_expresston 7 f = f x fuaclion xetorn + Spaat Date .... Example = def fun: wink ("welcome fo GF Gr” 3 ve Dsitver code to calt_a function fun | off - Welcome fo GFA. Defining and calling a funetfon with parameters: < aa Defining: ‘ 1 Syntax - def Punctfon- name ( paraniele : data. bypr).33 Aehurn fy et 5 "DS vtng i # body of the funchon * q a aidturn expression > { = si Example -_ # some more functfons f a def fs- pate Cn): = Spo in [a37: 5 Mehutn Tae a if (né=1) or (nm Jo a=-0); nial Achurn False %y 3123 > Auquments are the values. passed aici Mis of the functfon . A function kanikebe fe pouanth i Mave ony number af arguments sepauated by e PT commas q ~ Example -_ #A simple Python Function to check # whether % is even ov odd » “det evenddd (x): SS i paint ("even") J else? patnk (“‘odd") ~ # Datver code to call the funcHon ~~ even Odd (2) evenddd (3) : oP - even = odd ~S = Types of Anquments. = ~ 3p “FH Default argument - I} fs a paramelew that assume + ary ° pal a_default value if o value. isnot povided ea | age the funcHon call for that argument. tr JU \ 5 fxample - de’ ony fun (73 y= $0): L = pariah ("2 Mey patak (* 4s “4) # baiver code Vive call muy fun) with. # only agum ent) my Fun iaa\ J fe {wt 4 satya o}P- x=10 4= 50 4 4 ee ese: A ee ee —— @_keyword angumente = the idea is to allow the the _ayqument name wilh values dors mt need to nemember _In¢ order PRT ti ts ' Example - __ dep tnt (frsiname, lastname (firstname , Jastname) al Reuuaerd arquments i. Studen( HrstnaMe = Greeks", lastname = Student (lastname =" for! , firstname = geeks) BH a —— OjP - Geeks for & Geeks for _ = @__Nawiable- length arquments - é J J ; S we can pass~a vautable number of argum- sents fo a Punctfon using specfal sumbol. Were ave two __epecfal symbols - ¥ S . "* args Non-kKeyword Arguments 5 a C = cate) = Kwargs ( keytbord Arguments) J g 7g Ge Example: - def my Fun (*arqv)'s = p Fy $ = for arq in argv a ; point Caray’ i Bay Fun (* Hetlo! Welcome! ‘tot, Geeks tor Geeks fee. O}P. = 3b. Hello Welcome ¥ fo = Geeks for Geeks = Date ... To Baaieing. =. The_first_strtng—oftes fos ated the Document _st¥fng or Dockrin ark. this is. used te described the funckilonaltty = uncon. dhe use of docstring fo f9 g of he ~» Dea bul {fk ts considered o gee prac: t ‘ fon mame. doc-) Syntax = _paint( function name 3 J Example - def evenodd + - “TEunchon fo check whether % is even or > odd f° a St (wsJo a == 0): =] paint Ceven) 3 elses print (“odd”) — wz Dulven code fo call the functfon SS patnt ( evenddd,—~doe—) F e a dlp - Functton to checkuif Khe number fs even or ~ odd. Return skatement fn Python function - the fundion sNturn “statement fs used fo _exth pom a funciton and go. back fo Ihe _functfon calle wy and sekurn the Specipted value. or data fkem to at _ax__the caller = Suntox - Heburn [expression tist] uw Se: She seturn statement can consfst of a variable, an Date .. ‘ the end — expression, or a consiant which 1s sicturned Te : nd irabove is of’ the function executfon. If none of te rate puesent with the _veluyn statement a __None "obj Heturned . Example - def squane-value (num) + ~, i “This funclon steturas the square Value 4 “of the entered numbut 4 wiekurn num ¥ #2 3 pufnt ( squave- value (&)) _ pital (squawe. value (4)) § : $ ojp- 4 ¢ 16 7 . Pass by Reference or pass ba Value = Sj One important | thin fo_nott is, in Python . every vautable name is a vieFurtace. When we pass O_variible to ao ftunctoni, a: new eauefbrened fo the é objech is oveated. : 6 Example - def my Fun (x): i Pe = 20 & # bdyivey Code( Note the Ist fs modified after # funcHon call a Ist = (lov it, 12513, 04,189 =? ry Fun ( Jet) & wink (Ist) ky . OJP = [8o, tor ni2, 13,14, 1S] er it Suatags fn Python - oe c ee Se aa Strings” aye adviay of byte v t atpterenting Unicode chasachou . e J yo Seerat > Date wv Geeksforgeeta’ chavacker data type, a sta PY hen dees nok have chavaclor_ fs cogly 8 sh ‘with a _Jength of 1. | to © . braces cans be use acess elements in ching Pe Trample - a A Computer Sctence_portal portal for — t uv a A_fompultn Serene Garating 0 Shing in Python - SS ‘Gring ind python can be created using sin le, double ro ov_ever bright quakes. wy Esample Ghatng 1 = *weltome fo the Geeks world’ hw puall [2 sang with the use of single duota :"} poe “pail String 1) ie: # taeating @ String ~~ # oy atl Ghote — Stang | =“lLma Geek” te patnt Cn Siving with the use of Double duole + mint { Sting I) = H# Greating 4 “ining with riple quotes Sing): U" I'm a Toeek patat | “\n Stving with Hoe use of Triple U Quotes : i) pint (Stving 1) s H beating Steing with Irfple # Quoles allows mutifple _tfner String | =" Geeks ' v tor Life paint (“|n taeatig a multiline Shing’) Date .... ‘ puiot {Shei ') i OJP = Shvfn with the use of Sin vi Quotes : = . Weldime fo the Geeks wor i SS Slatng - with! Mens ase of double duoter 7 Vanda geek , ~~ Sting with the use of Triple Quoke + 4 Um a “Geer” —$ Creating a multiline Shufng 7 i Y 2 Gees ” For —__% Ape S = Aeessing chawachus in Python Statng = 5 7 dg 5 ‘n__puthon, individual chanactes of a String can be accessed by using the method of Indexing: Inde¥ing allows ™ Negative address Heboiences fo | access chasacterc! from + He back of the Shuing , eqoni Hefory to the dask thar, s ~2_atfers to the seed Mt char and Soon, ‘hile accessing an index out of the Mange wilt 6 coust_an_IndextyrorV only Inkeqeus are allowed Vis be S passed os an index, tod? or “other _Fypes that will cause t vt #y Oo TypeError. of % Example = Stufng | = “ Geeks For Geeks" & thE Intfat String :") 2 paint (Sting 1) U ary # Painting Fd tharacley % paint (Ga Biysk charackey of String fs") 5; paint ( String | Cor) d Sterat ; J = ~y = Painting last Character aa _paint Last character ies paint (sixfng 1611) ~ jp -___Inittal_ Strin ~~ GeeksForg eek i First character of String fst G Last characky of Statng s+ gd S$ _— Reversing a Python String - ¥ uv > # Pao gram to everse ashing SE a = — geeks forges at tl a (gtg 1) SF O[P = _Skeeqrofskeeg J d _* ~ = Sbiing Slicing _- 3 To aNess a range of - chayacteus in the String oe le F oo ° ° of 3 Phe method of altcin is used. Siteing tn a String ¢ ac_done by using a VSiicing operator oO colon). 2 Uo qt a > - Example -_ Stung |= “Geeks ‘or Geeks” a putt (" intHal_Shving 2") ae iat (String 1) g = paint ("\o Sifetng characters’ for 3-19:") oN paint ( String | 3: tJ) R paint("(o Siting chavachers between” + 5 8rd Vand dnd last charactey 3“) paint (Sixing 133-21) Se T Ojp- Intel Stutng: 23 ae Geeks for ede 3 ates Rott Slicing __chavacktys from 3-19) 0 3 ¢ — ksFovqeek a : : Sifeing characters between 3rd and dnd’ lask char, werd Gee ce ‘ = che) function - —— It _velurns a shying from a _Unfeode code Inkeger. puint (char (a7) 4 1 OjP- a j * Escape Sequencing in Python - i + While painting — Stutng with single and double quoter in tt couse | Sunthhervor U because sting already tontafns {_Sfngle_and Double Quotes and hence cathot be Sositnted - lth_the ust of eliher of Hest, Menee, fo pain’ cuch a String either Tif le Quotes are used = to Escape + t Squentts yt: used" bo’ pytnk such Shings. t = String Concattnation _ustna + Operator ~ : U7 an operator ay be used fo add multiple Shin, fogethey . However ,* the: SAgumenks mush be a chingh We. the + - operator t sting : combines the string thar > S_“shored ia the: vow and van 2 and shores aut a f rs another vayfable vay 3, : . NOTE ~ STRINGS ARE IMMUTABLE , THEREFORE WHEN. EVER IT Is (Seat : H Pom Co cATENATED » IT 1S ASSIUNE So ye_index O method - It allows a user to find the Index jah tne first occurence of on cxlssing eubibrig, — - tnside_o_qiven stating. . aa ao ae Syntax = string — obj: index (subsbrings begp endp) = Parameluys = + Substring - the string to be Searched = ~ + beqp - Vf default 20): UT ynis fo speci fes the —S position from where search has to be — : started . 4 +_tndp default: length of string); dhis f" we ene, oe , specifies the osttfon from where —w search has fo tnd. ~3s Return - Returns the 4st positfon of substring found Excephon - Raise valueEyror iP argument shiny fs no! E found ov index ts Suto rangeJ = : vu qir_windex() method - It Heturns the _hifghest index of He substring inside the string _if the substring i's ~ found . OHArwisey- Tho tatses TJ vatuebrror. Ri —* > Case Changing of Strings - J 7g « Jower() - Convert all uppencase characteus in & string toto lowerease » + upper - Convert all Jowercase characters tna “string into uppercase. Hele case. 3 Hite ©) ah Convert String nlax > _sluobf.find( sub, start, end) sy ajefind ( Gabshing that need to Wy Stovehed _\isk_Inhoduelfon - Puthon lists aye fust Jtke dynamically steed quays,” declared fi ont onquage Vee, U Fava). In a stmple wet th’ tee collectfon of t things enclosed “with OY Separated by comma. V The lish ts 0 sequente date type which is used sat f fo_Stove_the collection of data. Ty Its and Strings ore other tupes of sequence data typu. Tt Now =f" Geeks" for" , “qeeks"] Mi aiint ( Vass) 2 JP-_[' Geeks! s'For', “Geeks '] : ae Lal EEL bh db! Date encous 1 tool_in Hen Data Types he tot Woays wnt =a a Sas wet _as¥ objects 1 and hence ey can be altered theiy_cxeatfon . Lytnen = r —>- S Tih ean be ueated by just lacing the _ 3 Sequence inside _ he tquarey) traces td. UUll?Pke Sete pee fish docin'} need a bullk-in functfon for the. wieation of a Iist. —~ Example ish = ta & —> paint LiuStank tist =") ‘purnk (7 Utst™) Ss, List’ = L10,20,30) ; Ss paint C™\n ifer of num bers paint (List) = o[p = Blank Uist : a Ea S Lis} of numbers: = Tio 20,307 ay Aucssing clement from the itera Uist e [geeks SFor, Seeker paint (" Accessing a elements’ wd oe (bist eats : = > paint (iter C21)

You might also like