You are on page 1of 31
PYTHON BASICS ® General {nfermation :- “punitetpace matters | Indent where needed. Import modules " import modulename” 4h This is @ comment: print ("Hello world|") 4. Prints to screen. * Conditional Statements :- tf fsSunny: Print (‘It's Sunny | yy) ent go<= temp < 100 and bath > Oe print (‘Bath js hot and Full!’ ) elie not Cc fee == ox (usr == 4am’): print (‘Match if not ya or adm 2) else: pyine (‘alo match. job is + jor) ATUL KUMPR (LINKEDIN). s Sri oe AOTES GALLERY (TELEGRAM). “Fitle = Us and them’ 4 most list operations works on strings title [oJ] #f output: ‘Vv’ len ( title) Mt title. Sput(‘ ") at [us' ‘and’, them’) ‘2? foin (CA; ‘c'I) HAG Bae Cy nine = ftv (9) tf Convert int into string title. yeplace(‘them’, us’) 4% us and us. x Dicrionaytes + votes = { ‘ved’: 3 votes. Keys ( ) votes f ‘Jo1a"] = 4 de! votes [ ‘go1a’] voter L ‘blue J=6 ten (votes) votes. values ( ) ‘gyeen' jn yotes votes. nas_key(‘rea’) w Numbers :- total = 2 *3 fotet= 572 *3 Cost = 1:50 tr 9.95 toral = Int("g")+1 “biue' 5} # Output :[ blue! , ‘red ’J # add @ Key [val t deletet ey + Change value et 2 # (6,25 # False # True + Output: 9 # output ctl a output: 5.25 4t Output : /0 ATUt jumar (LynKeDin). NOTES GALLERY (TELEGRAM), Like lists, Except they cannot be changed EUple ds seal ool ae tupte1l3 J a tists i Scores =L'a’, 0) 9° scores [OJ seores [1:3] geoves.count (‘c’) scores. append ( 100) seores PoP ( ) e Kummer (LINKEDIN )- 2") 4 creates tuple # fa? toon # Output: ‘A’ #'C', Go + 2 # Adds 100 (0 +E yemoves third jyem. Hist a Pee renner eeerece ython OOPS Concepts Objet Oviented Programming | Fymon is a mutiparadigm programming language. It Sepports cutferent’ Programming appyoches One of pre mocr popelay approchet fo solve programming Problem by Creating objects. Tris is known as objew Orlenjed Programm)ng + (00r). “OOP hoe f90 characteristics 1): Attributes 2). Behavior Eyampie f parrot ts an objed:, as it has following Properties. * name, age, Color as attyfbures. + Singing , dancing o£ behavior. The conupts of 006s In Fymon focuses on Creating reusable Code. This Concept js also Known Qs Dry CDon't Repet Yourselt). [Giars] TELE RAN NOTES GALLERY. A Closs is a blueprint for the object. ple can think of class as a sketch of parrot Lith labels. [F contains Qil duals Ohout tne name, colors, cize ete. ox Class farrot: Pass. Hose class weyusord define on empry cl9ss parrot from Class We construc fnstances (-)n jnsrane Js a spedite Objet created From a ParHcujar class ful wom ae (cincediel) TELEY RIN NOTES GALLERY Cinspanee) }s an instantiation of a class. When Class js defined only phe dicealption Fos phe Class objet he defined. Therelore , nO memory os ttorege is allocated. ex f= Obj = Farrot ¢ ) Here Objer fe On Objet of class parrot- Suppose te nave details of parrots. plow 19¢ are geing 40 shod howd 40 bulld the class and ebjer of parrots. we can access the Class ettribure using — Class_ species Goneritane }s q ay of creating new class for using idoratls of an exlsting class without modifying th. The newly formed closs fs derived class, Simillarty , rrr existing class Is @ base class. €x> Use of Jnhevifanu In pytnon- Class Bird: def_Init_ (sue); print ("Bird is ready") dof culm (ree): Print (" susim Fasper") class Penguin ( Bird)? def —Init (see): SUPCY( D, Inthe (7 de yun (see)! ne ( 7 Pz Penguin () pce ACU DEE) pg. svime) Stsim Faster yun Face lale can use ¢he fuper () function Inside pne—Init_ ) Method+ This allows us fo yun — init_() method. using OOP fn python , 0 can yesfrick access 40 methods and Variables. This prevents detg From dived modification Which Ms called encapsulation. Tn python We donate privete attribute using — as tnt prefix Fe Jingle —. ov touble —- Glass Computer def__fnit__ Cselé): Seh-. Maxprite = 900 Sf setmoarpriee ( sell , Price): elk, 2 MOxPrice = pri. C= compurer( 7 C.-- MaXprile - 000 C. Let maxPrie (00) ble used_init.-( ) method fo ¢tOxe the maximum Seung Pria of Computer. Cc. Max price S1000 Method Class Member |Acess from own | ftccesstbte Accessible access speutbley Chace om serlved |from Objet. Pavate | ayer DiS Nie aay colnet | Seng au es es Poste TUL KUMAR (INKED inl). ddd ddeWveeoroeeer ekers NOU LLLLeL ee edddddedveee Polymorphism Polymorphism fe an abttity fo ue 4 Common InterFace for multiple forms Cdata types) Polymorphism in python Sefines methods in phe child class thet have the same name as the method jn phe parent Class. fp fs possible 40 modify @ method in a child class thet It has inhert ted From child class ,.. Parent class Class paxrot + def Fly (see): Print (" paryot confiy") Jef swim ( ser) Print (“parrot can't stsim") Clase penguin: def #uy (sere): Print (“Penguin can't fuy") del sim ser): Print ("Penguin can stsim") Dee Ewing test (bird): bird. Fly( ) biue = Parrott ) peg = penguin () Flying — test ( blu). Flying - test (Peg) Outpur Poyron Can Fly. Penguin Can't Puy. ATI Lumar CLINKEDIN)- lbher are Functions ? A Funelon jc q bleu of lode Only yuns bhen ty called: Dr Python a Faunetlon ts defined using phe der keyrsora . de my — Function (): print ("eno") Arguments fn a Function Arguments are spedfled after the function name, inside the Parentheses. Yeu can add 96 many argumentr as you Want Leparate ¢hem ith q Comma. def my — Function CF name) Print (fname + “ Refsnes") my_ Function Cem") my - Ranetton ("Topigs") my Fanerion Citnus") TEELCAN ALTE GACe ERY. Axbitary Arguments SE you do not know pow mang arguments that Lill be passed into your Funition, Add Q bebove the Parameter Name In the function efinition. OF my Fanetton (*kids) : print ("The youngest aiid ie" + kid sto) my Ainitlon(" sour” "70d", “txpark") MAK (LANIKEDIN) NON UUUL LLL ed dddddevenenee NCCU dcecdddeeeeweoes ie Keyword Arguments ( Kwargs) You can alsd sond argument? with phe Key > yatue Synrax - def my- Rineeton (osias, CMid2 , Childs): Pint ("the Youngest crtia it"+ Child 3) my ~ Puntion Ccbdidy © "mtb", childa *"bea", ehiiay ="bte") ~ Aree Korn ph CiiniKeoiny) Arbitaay Keyword Arguments ** Kioargs SF you doe not Know ho many keyword arguments that wil) be pasted Inte your function, add 7130 asterisk: * * before the parameter name }n the Function definition . dee my Funttion (** Kid ): Print (“Hic last name ve"t Kid Et name 9) my — Funution (Frame = “Tobias”, iname = “keFcnes"”) Atul Koma CLINKED AL). iON Operator CHEATSHEET Komaat incepta). rithmetic operators: HOTEL GaLLeRy (TELEGRAM) An arithmetic operator performs mathematical Operations like addition , Subtvaction , division and multiplication. Meaning Example te Ardd tO opexands S>> 5 EY 4 Subtract two operands P>>b-& 2 Multiply +490 operands >>> 2¥10 20 divide the left oferend by Boo oh yight operand as whith will give Integer ia Part raised to the power Prr>E* KZ 125 arutwornpe (unikenr)- ulhich will glve us reminder aoe 573 part Comparisions oPerator | operator] Detevintion____—‘examele IF two operands values ave equal | 777 aa then the condition becomes true. False Values of two operands are not >>> S1=3 equal, then condition become True tyue- IF the value of eft operand is >>> 4>3 gvearey than the value of right True operand, then conditon bewmes true. TF the value of 12ft operand is S>>b<4 less tnan the value of vignt Forse operand, then condition becomes true. Syeater than equal: LF tne vatue ef D>> FT >=6 left operand is greater tnan or False equal to the value of vignt operand, then condition becomes true. less than e Dor ae me True ATUL KUMAR LINKEDIN). loves CLALLERY (TELEGRAM) Logical oPerators © Logical operators js Boolean expressions Suth as and, or, not. © It is just @ conditiona) tesr thar a resuit js either true or false. Continue — > put Kemer Cu nmerin) Description Example it two operands are true >>> True and Tue it become tyue. True >>> False ANd True False It two operands arenon-2ero} y>>Tyue OY False tnen conalHon becomes true. True >>> False or False False Tt ts used to reverse the >>> not True logical stare of Its eferand + False >>> not not not True Falce ATUL KomARLLUNKEDIA). "Notes GALLERY (TELEGRAM). [___benrtlen SCT mamre | Assigns values From vignt side operands >>> x=20 to Left side operand. It adds vight operand td the tet operand >>> Kt=20 And ASs19n tne yesuit to Left operand. Tk gubtvacts vignt operand From the left operand and assign the yesult fo 12FE operand. Ir multiplies vignt operand wlth the left Epevand and Assign the result to left operand. Tr divides left ©perand With the yight operand and assign the vesult to lerr bpevand. >>X/- B50 Tt takes modulus using two operands eae and assign tne result to leFt OFevand. Peshorms exponential ( Power) calculation >>>x **=50 on Operators And Qtsign value to the let operand St performs Floey division on operators And | >>>x/}/= 50 assign vatue to the 1eFt Bpevand. ATUL womek (LUMKED IAN): Evaluates to true IF It finds @ vartasle [922 X= Python” In the speafled sequence and False 2>2'P'In x omerwice. ee Evaiuates to true TF IF does not Finds | >>>x= "Python" Q varioble in the spedFied sequence >2>'2' inx and False otherusl.te- ores GALLERY (TELEGRAM), [orem | _Bewwinion orem Operator copies a bit to the vesult [Fit exists | >7>10 &20 In both operands ° Tt copies a bir lett exists tn efther operand. ee to] 2° 0 It coptes the bit Fit 15 set in one >>? 10%20 erevand bub NOt born. Bo Tris unavy and nas tne effect of tipping’ bits. The left operands value is moved 1eFt by >>> 1o<<2 tne number of bits SpedfFied by the vight 4o operand. The teft operands vatue is moved yignt by D>>rlop> 2 yne number OF bity Specifled by the vignt 2 operand: Example. Evaluates te true TF the variables on >>> xe “netio” eltner side oF the operator Point fo the >2>y = “hello dame objet and false orherWire. utaae Gvoluares jo False If the variables on >> x= "hello ” elther side pf the Operator peint to the | >>>¥= “hello” same objet and True ornerwl se. D>>xis not ¥ False. pul _KurnAR (LINKED/al). PyrHoW [Moles Wrupiks 2 paabre Python Variables —— e = Variable 1s a name that is used tO vefer to memory tocation . Python is alse Knoton as an jdentifier and Used to hold yalue. th python , We don't need to Ydentfley name must not contain any white space ov 5 result 1S true. andX >Id ) Python ide Operator Tdentity Operator ave used fo compaye the objet, not if they are equals bur tf they ave actually same objet with the came memory locarion. Copmarer | Dasesinton | ecampie s Return True tf both variables are Kissy me Lame objec. ney Reruyns true Tf both are not Kisnoty. same Ovjet. thon membership Operator | Membership operator ave used to rest IF a Sequence is pretended is an objeu’. Sexton aaa in Rerum True if a Sequence wirh rhe Spedfied value Is present. notin Rerum fyue TF a sequance With me specified value is Nor present. A TAREDIAD MOTELS GALLERY (TELEGRAM), Bindlse Operator perform bit by bit operation on the values OF tWo Operand. Consider the Following 1able- Continue —> Aruc_ xumer (UNKEDIAL)» Deseripton Se each bit tf both Jide aret Set each pit to | IF one of rwo pitts | Set each bit fo 1 pF only one OF tWO pits is 1. : Zero FN ShiPt left by pushing zeros ln fom tert Snir +e yigntand let tne leftmost bits fall OFF. Sete ont Gnift wignt by pushing copies oF RSE the lefrmost bit In £som the (ere and rer the slgntmost pits Fall off. MOTEL GALLERY TELEGRA™), Python python tnput 0) Funceion Fymon inpur funatton Is used to get Inpur From uses. th prompts for the user Inpur and vead a line. Arex reading dora. if Converts if inte a styling and yeturns char ir mnrows an ervvoy E of exvor js EOF }¢ yead. (Parameter) Prompt * ipisa string message with prompt for usew Inpul. CReturn) ir yerums usey inpul’ aFrev conveyting Into dhying - ler Jee an example oF Input ©) function ¢o understand irs Funerionality - Continue —> Cunnedial) jngut 4& Python Input () Function . val =Inpur ("enter a value : print (“you enrered: ", vat) eevrn erg (LINKEDIN) ne NOTES GALLERY (TELEGRAM ) enreyQ value 7 20 you entered ; 2° 1+ Does Python have OOP's Concept 7 > Fython it an Object Oxiented Frogvamming tanguage - This means that any Problem can be elved In python by Creating 4 model. rowever , python can be treated 9S procedural as well 95 Structural language - 2 flow fo add yalues do Python array ? > Evements can be added 40 an array using dre append oO; extend) and insert Ci,x) function. a). append () 4) extend L) c). insert () Arut weomak (1imKedin). 3. How Jo you to data abstraction in python ? > Pata abstraction it proviciing only phe reguived details and hiding the implementation From the w2ord. ft can be achieved In python by using interface and abstract clax. 4. How wlll you capltatize the Firse letter of cttring ? > fh python , the caplralize () method capifalizes tne Arsh letter of String fF phe string alyeady conshtty of a Capital letter of ne beginning » then it returns the oviginal tring - §- that are generators In Python? > Fonctions thar yeturn an Hevable ser of HME are called generators . ATUL LUMAR (LINKEDIN): & kthat-are doc Strings In _Rython 2 Y Pocspings are not actually comments, but they are clocumentation Strings. These cdocstrings are within triple 9 4 quotes - They ave not assigned ¢o any varlable and therefore , at pimes Serve phe purpose of Comments AF bell. Example t- Using docttying at a comment x=e vas Z=x/y Prine( 2) 7 that axe _puilts in ¢ype of Python ? “2 + Drtegers * Floating - Point + Complex numbers + String + Boolean * Bult in function. AIOTES = Gatteny (TELEGRAM 2. 3. Detine encapfulation In on 7 > Encapsuiation means binding phe code and clara tojetner+ & Python class i$ an example of eNCapsular{on » q. bdhat toes an object() cdo? St yeturn a featureless object that has a base class for al) classes ASO if does not fake any parargeter. ATUL KUMAR _CLINKEDIN) - fo. How 40 ¢ {0 Creare emmy > The empty clats isa cher that does not have any code defined within ity block» It can be created using phe pasts KeyWord - Howewey , you can Create object of das class outside the clars rtelt» In python phe Past Command joer nothing when tte executed itt @ null saternent- Semele i- “Glass a: fast ob at) onjname = "xyz" Pring (Ham é ="object. name ) prue comar (LINKEDIN) - NOTES GALLeRy (TELEGRAM). Us Does £y¢hon Lyppost mujtiple Inheritance 7 2 ruitipte inherttance means phat a Cclgst) can be cevived fr0M morse phan one parent CIOSLOS + fytnon ces not Support multiple inheritance unlike java. 12. phat IS. Polymorenism In Python ? > Forgrqoxpniom meant the abliity go gaxe multiple forms ..S0 far injtance- SF the parent class har a method named ABC +hen the child class also can have rethed with Same name ABC having its 08M parameter and variable python allows pelymerphism « (3. phat js lit used for? > The splitl) methed is used 72 Separate a given string jn Python « ample? a= “edustka python” Paint (a. split) ) ArUt lume CLIAISEDIN). lg, How to Import Modules In Python v > Afodules can be imported Using the import Keyetord: You can import modules in three Ways Hamele '- 2% import avyay Rx* import array A ary 3% From array import #- KEDIN). 15> hat is Fieing and Unpickling 2 7 Pickle module accepts any python object and convert it into String yepresentation @nd dump it using dump Function , this process is called piekling- iihile the process of yetriving ériginal Python objects From tne stored string representation is cated Onpickling. NOTES Gactery (TELEGRATA). 1): [kaha bs Plelding and Onplading 9) > Prewre moduse accepts any python object and convert it into Pe?) v utring yepresentation and dump it using sump Finution, pls process 3s called pickling + mile the process of vetriving python objects From pre spored String represenfetion is celled Unpitkding « 2). | ether ave geneyators in python ? > Functions pret rerun an jfevable set of items are Called generators. “TELEGRAM OTC! GALLERY: 3)-[How you will capitalize the first settey of string? > fn python, rhe capitalize € ) method capitalizes pre frst letter of string. IF the string already consists of a Copitel Jorter of phe seginning _ then, (f geturns the Orlgine string. 4). [dhe ave dbcseving In python ? | > Docstring are nor actually comments , but they axe documentation strings. These docitrings are within friple quotes. They ave not asslgned 40 any variable and thevefove, at dimes, serve phe purpose pf Comments 45 Wel]. example cs wun using doestving as q comment nun x8 Y*g 3 =xX/y Print 63 ) ATUL Jeumar (LINKEDIN). Tn types oF Python. 5: [eahat are bulits. > * Integers + Floating - Point + Complex number + String * Boolean * Built In funcelon « 6] > Encepsulation means winding phe Lode and data fogethey- A- Python class is an example oF encapsusetion : ATUL Ione (LINKEDIN). “TECEG RAY NOTES PALL ERY: 7]. Lhe oet an Objectl ) do? > Et verwns a featureless Objet phat sa base close For all classes. Also it dees not qake any Parameter - 3) [How fo create empty class in py¢nen? | > The empty class is a class phat oes not have any lode cleFined within its block it Can be Created using the pass Keyword: However, yeu can Create objet of fis Closs Outside gre class IFSEIL- Jin python fhe pIss command does nothing when irs executed - its a null steternent : orame)le :- obytacy objname = "x3" Print ( “rlame 2" Obj.name) 9) | Does Pynon Support musiele inhevitane ? 7 pyputiple Inhevitane means thet a class can be derived From more dan one parent classess - Python beer support miuhiple Inhevitanw . until. gava. LINKEDIN). 10): [phat Ts Polymorpricm in Pyphon ? > Poymorprism means phe abitity fo ¢ake multple forms so bar Ingronu FF phe parent class hs 9 method named ABC then the child closs also can have method with same name PBC having Itt own paramerer and Variable Python ows polymorphism + uy. awd do you clo lata abstraitlon_in Pyphon 2 > Dero abstyartion js providing only phe vegulred aereils and Afding g¢he implementation from from the World- It can be ackived In python by using tnperfacr and absbrest class 12)-[How #2 import moduler In Python ? Y Meceles can be Imported using phe Import keyword - You can impoxt mecafes in phree ways « eremele?- @- import avroy ®> import avroy as arr © From arvtey Import #, 15h 7 The sputl) method Is usted fo seperated @ given string in python - ovample:- a= “édureka Python" print (4. spute) ). 14J- [Does Pysnon have OOPs Conupe ? ] > Fanon is an object Oriented Prgramm|ng Janguage . Phir means ghar any Pregram Can be fclved }n python by Creating @ model. ¢Jowever, Python can be heated as procedural qs Well os styuctural Jang ” Ns UL Ken At : TELEGRAM” Noles GALLERY 15) To ae aaa Welue de Benavree To} 7 Elements can be gaded 40 an qrvay using phe append() , KXtend () and Insert (i ,x) function . © appendc) © exvtendc) ® insert cy, INKEDIN)- PYTHON INTERVIEW) Choesty ONS Part -1 1). [eahar type oF Tanguage jy Pyghon? Programming ov Scyletiag! > Fython WN capasie of scripting , but In general purpose Programming Janguage 2) [Yow 1s Pychon an Interpreted 1anguage : > fin interpreted Janguage 3s any programming language vnich is not in machine level code before yuntime. Thereteve, python is an interpreted Janguage. Page CuNneon TEC RG RAM NOTES YILLERY. 3). [whet i's Per 8 7 # name PEP stands for python Chhanument proposal: It is 4 ste of yujes thar spedhy how t0 format python code for maximum yeadabtlity - wl you is memory manages In Pypron 9 Pe Memesy management In python js managed by python private heop Spar. Ay) python Objects and dard Struttures Are located sn privete heap. The Programmer ches not have access 70 PAIS pyivate heep Tht python Interpreter fakes care of instead. * fru allocation of hep spau for python objects js clone sy pythons memory manager. Prt cove API glues Qecess 40 tome drole for re Programmer 70 Code, ATUL KUMAR CLINKEDIA ). © Fyrhon also has an inballt garbage collection uohich recycles all the unused memory and $0 for that i+ can be made avaiable fo the heap Space. 5): [Whar i's namespace In Pyrnon? 7 py namespace 7s naming System used 40 Mekt Sure that names are wnlgue 4o avoid naming conflicts Atul wumpAk (LissKEOIM) TECE RAM" KLOTES GALLERY lahat axe Python modules? Name sone commonly used budlt in_modwes in Pythen ? 6) > Fyrnon medies ave Files con¢elning python lode This Code can be Funions Classes or Yariables. F python modules ia “Py File containing executable Code .« Some of the commonly used bedit-in modules are: os 0 Sys » datatime «json - 7). [buhar Gre focal and 9 /obar Warianje in Python? | > Global variable :- Variables declared Outside a function oy In globe space are Caled globe! Yarlables: These Variables can pe accessed by any Function In the Pregvam. Local Variables :- fing Varviabte declared inside a function is known os @ focal Variable + This Variable is present }n phe Jocel and not in the Hlobay Space: SIPs Pyrron case Sensitive ? > Yes, pyshon 7S @ Case sensitive language. 91. [Kdhet Is 7gPe Conversion Tn Poron? P Tdpe conversion yefers 40 phe conversion of One datg type Indo anogher Pt eX NEC ORE eC eee 10). [TeTnaentation veguised In Python? | > Ihdenration js necessary for python. It spedFies a bok of code . #1) Code within Joops classes function ete within an Indented bros. St Is usuety dene using four spac chavauer. jf your code }s not indented necessarily - Jt will not execure accurately and WI) thyol? eyyorl as well. [lahat 972 Lunerians In Pythons 2] > FF Funution Is a block of Code which IS Exetuted only whtn if is cwled. Te define a pyphon function, qhe def key Word js used. def NewFun( > print (“iri ") 17]. > —Init_ is a method ov Conspyuceor In python. This method is autor wt cally called to etocete memory (ding new object of & Class js Created. M1 Classes have the —Init_. method. for eg!- Class EmP: deb_init_ (ser, name); SUL Name = name E1= Emel *xy2 “) Print (Es. name) 19). Iedhat is lambd9 Function 7 fn anonymous Function 75 knotdn 46 @ lambda Function. Prt funcrion can have ang number oF pavamerert but have gust one Statement. Q= jaonbd9 X,Y: x+y Print (acs ,¢)) ATUL Koma LINKEDIN): 14). [Dhar ig cere In Pyenon 2] > Seite is qn Instane ov an objet oF 9 class. Tn python, pris is explicitly included 4S the Frrst paramerer. This is not the case In Java where t's eptionel+ It helps fo differentiate herween pre methods Qnd attributes of a Class bith Jocal yariables. The self yariable in phe init method yefey 4° the newly created wile in ether method*, it xefers fo the object (oho object Method t0$ called - arut womne (LINKEDIN). “TECCG RAN” NOTES GAULERY. 15)-LKJhet ave on Ttevayors 7 7 Drevators ave objects which can be fraversed phough or itevated upon.

You might also like