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

Complete Python Notes by Kaushal.p

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

Complete Python Notes by Kaushal.p

python
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 77
COMPLETE PYTHON NOTES KAUSHAL PATIL Revision Wise Notes for Python Programming = Date ... jo ~~ EyrHoN._PROGRAMIMING c- Into ducing Python - be: i — ea &_a_high- level genus = purpose and ves. it opular progr tng. tanga : 2 a! uate veh usd tn Gwe development, Machine learn. - -tag applied ete. eae ee Pytflon fuegrame ae Cd Smaller than the othes jin Hogrammin dong uages . — Puogrammers VU have to type Helatively less and the tadentation requirement of the Jonquage makes tens a eadable at ihe time. + i> Veg Simple Syntax. 2 fasy fo learn, t v oT Uv ~ oa 9. “ w paint (“ Helto”) > = = General pusipose Janguage ( Simple yeh very powerful, 3 language) s Console Applfcatfon & Scripts iw C= f> Desktop Application : = [> Web Applicatfon ‘ ; * E> Game Development FE f Ly.\Machine: learning iden: learning. AL, Bf dala ek- = “4 P “t ot Z — Muttinaradigen Support = \ [= Pavcedural Style Programming _I?ke C - = sl “s L>. oofs ike Java, © g Functional Programming (tke Usk. f => Portable or Platform Independent = Puoqrams are typreally first compiled nto an Utatermedfate cod¥, then the code Pe yun Me interpseten . —>_ Dynamically Typed. nyna 4y---NP ~= 10 4 ys “qeeks™ 4 uv . ace “python J 7 This featuve %&_dffferent from Ctr b Tava. they ‘ ae stateally Typed i In python we don't have to specify the vantable PY i name. But _the disadvantage & fm this the type & asstaned | ° i v in the vun time" of the pnogram , so there avd f preg move chances of yun bme exror. — Automate Garbage Collectfon ‘ \t medns when you 4 dynamically allocate memory So you don't have fo worry: to yealfstng — th?s memory . g u \ § => Popular Apolfeatfon Butlt tn Python FF ~— + Youtube y Nettlix',) Quora 2 Instagram , DoopBox x 4 =r__batat O tn thon — % A__funclon & a sek of fnstructfons' that take x some fnput Prom | diing..dose somehiwork on those - Date .... io ~~ a quametes and 2 Example ~ point (“Mette”) ~~ pofot Welcome", “to, ee = aint ©) ee F pofot (“Hope qou—are enfe zy ae Output - Hello = ~ Weltome fo aE a = as ‘ foyfng Pyth 8 s Mops you axe enfoyiing Python s Vas endgA end ond sep parameters fn putatO : 2 z = siint [“ wWeleome, end =" "')_ paint (* fo GPa) Outpuk- Welcome to GEG = votre End parameter creates _ space and ft tells » should be printing after tks patating. - And tn sep pavantetet. when we haveY multiple = P—f input parameters we use sep to separate” them. — # f By defoult they ame separated by space. a o f CAMS REL Ah Per i eae putnt (“10", “out , "2023", Sep == "y EE Output -. 10-04-20a3 a => Nanfables fn Python = Nawable & a name that oO used fo. suefer to memory Jocaton. Python vayfable also known a+ -fiex_and® used to_hold value. ’ : Jn thon, we don't need bo specify the hype of Notable because Python t& a in flew language and i —__# {__smant enough to _qet vanfable type. ie | get_vontable typ +s E z fee» 5 xample patce = loo ” tax = (8 = ! °, s = t total - pailce + ostee + tax paint (total- putce) * & Output =o alts, aq How vantables wok 9 a = 4 “= 10 Uo]<~ * yee “geeks qeeks |e~ f ‘ Zaid (go|—z € it we say wez a § When adolf 4 Nwx 4 bat TP w=: 30 Bol<— w : 4 aa OPocs 165 3 410) f. : y) geeks 4 putat 2) 36 / print (w) : 4 oO q a4 | ee _Dynanl cally Typed _ m% +10 pata (2) nk: “geeks” ro) puint( 9%) 10 qeeks 9 Note - Using a variable without assigning fk cause evror. uv Gg J yy Eq- paint (x) » Oe- Name Exror : name ‘x' fs not assigned a ° °. => input) fn Python - > ue 2 This functfon ‘used fo take fnput from the user } f ie 4 Example - name = input (“Enter the name =") 5 paint [\ welcome’! + name) 2» jp - Enter the _name = Himant, + Welcome Himant > example - # Python program for addivoa i‘ ' t toad +t —% = input (“Enter First Number :") yz input (" Enter Second Number : ") 3: ND eae o> _fat () >» We int (y) Hes ney F Spat print ("fam te", Ye) _ Fah Number: Ente Output = TypeQ fn Python ~ we yom shir ee Ie d Type & a _bullh-in_function that Hells £9 wherever we have to ‘ you data lupe of a “vavfable or a value. i Eg a=10 : a ( tupe Cay) = 10'S ‘ re Ciypecay) r C2 9437 putat (type (a) OP ~ = dais, aS & = class, '! float > <= 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 § “ in python there 2 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, 307 (_@tray and dynamfealt paint (type ( 4)) add and remove thee B 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 disk = t o and set U_dtke mathemated Set) y “ w Oyu », as J ~ dz fio: "gfg’s 20%" ide" _( sisfonartes, ore uscd to_do a paint (type (a)). ings. Jhe & a 7 3 J collecHon of key value pairs) > Eq- thems: prices rollnot Name. ai > p> Type conversion in Python - Type conversion > se 3 Implictt ExplteF a fat !0 €q- 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") Date ..... 9-3 a= 20 patint ( bin (a) te = palnt (hex (ay) aaa + b (oct (a)) a | ¥ OP = Obio100_ | URIVE H 0094 => Comments fn Python ~ ate 1 We may with to deseuvbe the code we develop. We 5 might with~ to take nokes of why a J seckfon of seu pk pr, for _fnstance. Formulas , pocedures, and sophistealed business Jogtes ave v lypfeatly explained with comments, # TH 4 Single -Jine comment - # a Mult? -Jine comment - we cor "4 ie # te a Doc-shing - — The string enclosed fn trfpte quol-es 4 that contes _ immedfatel after the dettned fm ane caiied Python DoestYing, @ ¢ v E =P ib else and eli? in Python - ig a pans %e Shee come _sthuabous in sea) Jife when we need to do some Specific fask and bated on some Speci pte, é onditfons and, we declde whak should we do next. 7 Similarly, — there Come a. sthuatfon Ph potoqvammeng = whee a ‘pectpfe tak & te be performed if O spectPhe ie conditon _& true. & Seat Lh Me & ~~ Date . in quth_ care, cond?Honal . slatements can be us condivvonal statements ave 2 So ~ ig. elie = Nested if s SF. tp nig. statements. cee s ement ~ tn Ist ¥ R= stat t th ip the condition & true thea pout executes else the elie pout executes . 3 " Syntax - if conditfon + % H Statements to execute ff # condition &_tHue + Flowchaxt — > aS Fi Test False ¥ awe % v Body FT| s — Ss y Statement fust below ) Ce ey + Example - if lo 75+ y puink ("10 & greater than 8") F i paint (“ puogram ended) O[P - 10 U__greatty tan S- v Program ended ia J bt Date on. oe k if-else statement ~ block of code te when if, tond if: Statement Me additional slatement which tb poral recutes this “block if condiNon & true ele: 7 # Executes thts block if # conditon & false Flowchant ~ 3S <> False t Lire |: Sody of Tf] [Body of dae] : zy q Example = a= 3 4 if w==4: ee pafok (yest) ‘s ; else: J paint (“No") 4 Example~ You can also _chatn ifelse statement with more than” one _conditfon. : ¢ Jettey = "A" 2 {P dettey == "BQ": e pint (" JeHor & 9" a else 3 © wan TE deter = ="c"; paint (deter & a) Seeat Sy ™~ we else pion Span Craton ba") Mites ‘ ele E Jette anh, Ay®and co") cao mE Z 2 Fo? - deter UA Nuted if ghatement_- tf statement can alto be checked insrde —————— mi.” ° 0 SF othey_if_statement. Shu tondiHonal ttatement u called a ° ° °° —~J_nested if statement. dhiu_means that tnnen if condiHon will ye checked only $P outer tf condition fs brut _and by thes, oT we can. ste mulHple condttfons tobe satisfied . ~~ gyntoe - if Ceonattion 1): yp i, # Executes when condition w_fuue TR (condttfon 2): ~ ; Executes when condition 2. true ~~ # SP Block tend here 5. # if Block &_end hee Example - _num = 10 = Baas! it num > § : >: pufnt (Biggew_ than $") = it num 2= 18 paint (* Between § and (5") > ojP - Bigger than § + oetween § and iS 7" tfeatt Statement = shorteut of if-else chain, while using ip -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 - i? (conditfon) t = Statement elif (condtHfon) : stalement 4 4 ; = L . = Bs) elses « a statement a Et Example - —Jettey = "A" 3 ip dettem ss em: _paint (“Jeter & 9") elif JeHea == “ct: putok (“JeHer uc”) elif Jette == SA": paint (" Jetten AM) elses pint (" Jetter isn't A, 8 orc) OP - Jeter GA > Aulthmetfe opetators - They gHe | uted to peiform mathem-_. =aHea) operations Jtke. additonal, subtrackon, muthip. -Itation, division. ; _& That axe 1 onithmetfe operators tn_. Python - = O Addition _® subtraction “_@ Muiiipixation @_divteton @_Modutes © _Exponentiatton @_Floor _diviston i “ay Date I Onevator -_In__python, + 4 the addilfon operator. It TW y 5 0 tet odd 2 values: si 2 ~~ Example > voll = 2 val2 = 3 SS ess vol dt val 2 SF _puint (tt) —j_ fh + £ Sos SubtracHon Opevalor_- used fo subtract the second value from he fick value. 5 on -_ vod 3 val a2 2 Ss des = vobl- vad ~~ paiat ( He) So as Modulus Operator - slo au_the mod ulus. opuigtor used to find the vemainder_when {fest operand t_divided by the ~~) second 4. Example — vol 1= 3 vol? = 2 J dea = val l Yo val 2 ~S_ __ paint 9) > 0) Pace h +O Exponeatfatfon Operator — _** used to raise the finch _y operand to power of steond. x Example = voll +2 > vab2= 3 > ves = voll ** v2 a. prtat (ts) = oe - 8 Spnrat Date ... + ® Floor diyfifon - // Ss used fo find tne floor of _the ustinh wher fret oprrand fe 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 __ # => Pulhon Logfead Operators with sep o i Operators aye used fo pot opeidions on values and # vawiables. Shese ave the spectal symbols _Hhak cawiy out artthmebic, +—and__Jogteal_compulatfone. he value tht _epeslor opera _on_& y known as Operand . ~ logical And = logfeal ov ~logteal not v vo U = toghal_and- True ff both the operands ate hue. peat f and oe X and y False \_Taue A | ZN + False_Output Example - a=lo A b= 10 4 c= -lo 4 th a >0 and b>O: SS , ne ees piel. (ome oe WE es fparons and b> d 6 70% es ie : SF pata [2 oe mabe ou ane aye _guieator than") elves. ~ tol Tepmeast one number & 4 riot greatut thanso°} are greater than 0 FP = The numbers Aileost_one_ number U_nok geal than o. ~- ~¥ Example > a=to Se eR i cz 0 ff a and band c: i paint (* All the numbers have boolean value as True”) Sy 3 — >> else: Ss ~~ puta ("Atkast one number has boolean value _as False O]P - Atleast one number has boolean value _as False. =e ~~ Falte Output Tue Output ~ > Example - azto : pS be -10 es eae c20 ™ if a>o or boo z . then of the _numbew i agrestet than 0"). na ben ts ps s th b>o or emo: me: : z _puind ("ef Mhey of the numben gusset than 0") else —-paint_{"No_number lu greaten than 0) DIP = Eifhey of the number _U Greater_than 0 : No_umber i _greaten than 0 — Example - a=to +. brie 4 =o } iP aorb ore: putot (“Atleast one number has # Tue") _ boolean value at else: paint (“AN the numbers have boolean . False") Value at S/P- Alleast one number has boolean value as True. | = Logieal Not operator — wouks with a _ Python Membership and Adentthy Operators - validate the _memberthiy ina sequence such at Shing Afsts or tuples . im_opevatoy = Jhe Mn! Python offers wo membership operators fo_check es of a_value, It tests for membersh, operator ‘u_used to check it « thera / substring | element Evaluate fo “true jf th finds. the apuitfied clement fra existe tna sequence or not, Sequence otherwise False. For eq - U | “Gy in_* Geksforqeeks! tt Checking. 'G! fa. shen | “Laue g d LL 4! Greksfor Geeks! %# Checking 'q' fn strtng sfnee pythe tk case- senutiive, veturn fal g ig False " Example diskt = J1,2,3,4 23] 4 isha = [6,7,8,9] them tn dtc: bs if fem tn Stet: i — paint (" oveilapping”) ; v elses paint (" not overlapping’) i * 4 nok 100 i nok Te a not a nok 4 oh t int opevalor = no! J Vasfable inthe does not fie J false other Example >. R224 ts a id _— ys 20 wt a ie “Yet = [10,20, 30,40, 50) _ = E(x nol fn dist): a ft NOT nt tn ven disk _pulat (. ats passe gf sk”) elses ace i 4 fs + in ven Jfst" int ( xis paesen i gis fs ‘) ety tn Wt): aint (*y fs puesent fn given fr") -s else: ~~ patnt ( iy is Not puesent fn given Ate") = °, * 2 2, OP - _% fs_NOT paesink TIn_given_ list. ~ y te present fn given _Itet SS wt v - Identity operators - Thty ae used fo compane the object woh’ the obfeds ave actually of the same data type and shove the same memory Jocatfon. a There ote dif wank identity operators such ad Nis operator - Evaluate to True ff the vanfables on efther side of the operator joint to fhe same object and false a} f othutuice. Example - me S 43.5: portnt (oc & 4 fd) fa Sport } OJP = 1407045 86672032 —— isin SENS Ie, both the vay Hore, tn_the S asttgned to th fi “and which? why eure Ty Ss rot’ opwator - Evaluates fo folie ff the vaxfables on _effhen | stde : of the opwiator _pofnh te a ditfount objeck_and te othuwise, 4 Example. ~ KES S2a0p 4 iE (type (oc) fe nob int): | a putnk ("true") . a elses = paint ("false") = b # Putts Taue = & Ke Sb iy 3 It (tupe (x) tsinot int): i f “ " = paint (“true ) i elses & t punt ("false") a . '. : > 1 ¢ 7 i ofP- False a Taye) 2 => Python Bihwise Operators: — & Operators are used to perform opeialt e4__ gS ie ea an perfo peatons. on vafu axiables . ese ane the Spectal tymbols that cawiy out _anfthnee and loatea) computaifens. he value ahd operator opevales on is_known as Optrand . i : i wy ~S Date ween oo Siu operators ~ “ SJ = Slhtce AND () ~ Return | tf both the bits ae I else_O. " Example = £102 1010 (Binary) | =I he ee be Y= 0100 (Binary) ~~ ~3- ¥ a a&Sb=lolo b ol00 = 9000 = 0 (decimal) STG Bitter OR (]) — Returns Lip veither of the bik & | else 0. ~ Example -_@=10= 1010 [ Binary) =3 e b= Y= O100 (Binary) 4 a|s = (ole ~ { > o100 = Ilo 7 = (4 (Decimal) ¥ 3 _)- Bikwise NOT operator (~) - Returns one's complement of the no > Example - = 10 = 10lo ( Binary) waz sl0lo 3 = -(lolott) 4S > (1011) “5 = -11 (Decimal) > d)- Bitwise (XR) (A) = Rebun | ip one of the bis fs tand the 5 other & 0 else return O- W” Senal Date wee. =lu (Decimal) + ‘ Example - a= io — = bey _* i ++ Puint bitwise AND operatfon EO wink (“ab b! arb) # Paint bttwhee OR operation = pink (“alb=" a}b) 2 + Puink bitwise Not operation Ke paint (“wa =", ~a) # Patot bituite YOR operation e paink ("ab =", a Ab) é o}p - at b=o 2 afb=1y 2 Mas- * atb=ty G & @__Shitt Optrators — These Operators ate used fo SWrPE the ¢ bits of a number Jef or sight thereby multiply én “ ox dividing the no Sy—two resp. they oth be used Yoheg WG we_have Vig multiply” or divide a Wimber by two, & 9)- Bitwise Right &p Shith (>>) — Shifks the bik of ime no, fe the _sifght and fille 6 on _votd. det p (fs tn the 6 case of a _ntoative Humbe) iat a sesult, Similan effeck as & of dividing i no. with some power of two. ae : Senae J : a sy Date Example = alo = 0000 1010 (Binary) a>>| = 0000 Ohl = S_ Wo ; wample eo ecto 's NI OO ( Binary) —— o> ee UY Vols 28 , “Ty. _gitwise rept shift - (<<) art shifts the bits of the number to the left and fills 0 on void vight as vesull, Similar efPeck a of multiplying a the _no- at some _power of two. SS Examplt - az§ + 0000 O10! (sinary) 3 acs] 20000 lolo = 10 6 azeg = O00t 0100 = 20 ~e Example - b=-10 = UNE oto ( Binary) ~» bec f= 110) 100 =-20 =a bee 2 = Ol tooo =-4O 28 Bitwise Operator Overloading - . Optrator Overloading means nt extended meaning beyond their. predefined operat -ona anin For example operator tote used fo add two integers it © ochtevable because the ‘+! “S_by int clase and sty dats. 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. = 3 Example - class Yeek(): def- init — (self, value): i self. value > value A def and. (self, obj): paint (And operator overloaded") Sperat Date ween. 4 if isinshance (objs Geeky ES ditturn self.value be obf.value operator overloaded”) ity fsfnstance (bjs Geek): seturn_self. Value | obf. value : a) else: Mase Value€rror def - xox - (sttP obj): paint (“XOR operator overloaded”) (Must be o Objeck of class Geek’) ip isinstance (obj Geek): 4 rehurn selP. value 4 obj. value i elses ratse ValueEvror ("Must bea object of dass Geek”) def. Ishit. (sel, obi): y paint (" Ishiph operator overloaded") iP fsinstance (obty Geek): eburn SelP. value ce obf. value t else: Yatse Value Error ("Must be a obfect of class § Geek")” ; def - tnverb. (selP): paint ("Invert Operator overloaded") 4 Heburn ~selP. value 7 # Duiver's code iP— name ==" main": 4 = Geek (10) 4 be Geek (12) sit {asb) ‘ ‘i 4 paint Cal b) eS s te ppt Cat) r~ paint (aces) ae ees wad 3s paint (a>>b) is us te pata (x9) een [= - p- And operator overloaded = OQ Pa 8 Or operator overloaded Ww Xor optrator averloaded eat \shift operator overloaded p> ~~ j= 40960 > is wishith opera for __ overloaded 8 Invert _operalor overloaded =H —~* loops in _Pythou_- U — while Loop - It & used to execulke a block of stakements sepeotedly until o given conditions tb Latislied . And whee the oldie beioma false , tin Hue frimedialely olen He loop im_the pucgrave uassexeated “43 Gre Syntax __while_expstessiow : statement (8) Flowehant “exis while loop i indeffntte thetahon. ~__While Joep falls unde the cig mn ih eee ladefintte “eration means that Cnumber of Himes the oop & executed sin't specified ex; Weil fn_advante. : Statements epsesents ol) “te statements fndeated by the Same_oumbey of chayackey space, oa Pegrenaaatg —tonstrud oe considered tot be pat of a sine blo of Li tode. Python uses indentalfon oh methods Vof souping 1 _shatemess. When awhile Joop hk execuked exph & (for 4 fvaluated {na Boolean context and if TEER bette He loop ‘ body U executed. Then the expat checked again, ff fp St at taue then the body | executed — agai and the continua until the expsieaston becomes false J 7 lr Example - | fount 20 while (count < 3): count = count +} pink ("Hello Geek"), OJP - Hello Geek Hello Geek Hello Geek | nd ol bly. while @ paint (a popu) ss — [20 fos Le | | ~ Sn Wnts, we have wun a while Joop over a __tist tha SGN wun _unbil there _& an element poiesent inthe Js = Example-3 _Stngle statement while block vy v Just stke the if block, if the while declase the entire Joop fa_a_single Jinv. | fn the block that moke up the block conststs of single py statement we can there ame mulHple statements l body, th tan be separated 6 Peol P % loop _bedus ey pana xy semPeolons (3). _s_ count = 0 5 while (counk' <5): counl+=13 patnk( “Hello Geek") —¥ t J: olf - Hello Geek 5: Hello Geek Hello Geek i Hello Geek aw Hello Geek > a > * Sparat Date ... eC) in Python - s e__puthon nm swehwan ence numbeu sa sequence of umbeu thon _stange () £7 webu 7 fe & to Pherate - it i range. Ihe most common use of tk J a ina _gwen nge.. Ihe most ¢c 4 Python scquiotss onal! scquinee of numbers _using fy Syntax - range (stot, slop, step) U e Paxamelen - stax}: LopHonal] ‘ Stop + . - % Sheps } cs Rekurn : “s Example - for _f fn _range(5): . t ° Os wu " pain (SR end =" ") ot puink() & OP 4 f O34 : ~~ what the use ofthe wange ©) in Python ? ‘ Oo % : = } n_simple berms Hange() allows the usey to genwtake a v ° 8 i Seifes of no. within a given range. Depending ‘on how é |_mani aagumenl the usd _ti patting to the Vpn, the useu © t | can arte where thay seniks | of “numbers wits begin 2 en (Bas well a how a the dif Peuence will be behween one no. and the next. Pf range() $M takes: can. be infltalfeed | fn 3 ways — g = wane {stop)_ fakes one anaqumuenk. 5; = Tor Toh: [sTsfst Te =—+t pas - > Stat ced + ¥, Speral Date .... 2 tok, sto} Exomple- Drmonsinatfon of fyihon stage (shat, step) # patoting a natural 9 at cianbi from 5 to 20 fou i fn sange Sy 20): ~ fa ea 7 part (ty ene" f 0) P $6724.10 Woes ty te ett 1819 poe sang | Stat. stop step) { ie) When the us called ange () with tree angumenty the usey tan choose nok onky whee the cenfey of “___numburs will staat and ston! Qhdt tio haw ba the a ; ; f diffuence will be behween the one no. and th¥ Oexbeg Wf te usey doesn't puovide Hhe step, Hhen stange () will automatically behave ay if the sep & 1. InJ ney i txample we ar patahinn even no, between Q and lo e i 2 So_we choose our stoVitng point from 0 ( start=0) and x : He —$ stop the sewits al to ( stopVito) > for pyinting an even f = number the . difference between one. number and the © fext number must be 2 (skp) afte. providing. a Step: $e °° F F F t oth Ut we a e fo owing output (0 2,4,6, 8), “6 Stout Python ange (0, 10,2) oS 4 gd yer s fol Ts Ts Wes Ter ela po] ~ ; or Ser , = See ofale 8 2 eee EE ee Sperat — = i

You might also like