You are on page 1of 31
PYTHON BASICS ® General {nformation :- binitespace matters | Indent where needed. Tmport modules " import modulename” th This if @ comment: print ("Hello world]") 4. Prints to screen * Conditional Statements :- tf fsSuany: Print (‘It's Sunny | y) elif gog= temp < 10° and bath > 80: print (‘Bach js hot and Full!’ ) elif not Cc jes == qa’ ox (usr == 4am’): print (‘Match if not ga or adm 2) else: print (‘alo match. job is 't for) AquL eumer (LINKEDIN). x Sri AICTES 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’) “tain (Gl Ad ein ca) fet A Bee Cy nine = str(9) 4# Convert int into stving title. yeplae(‘them’, us’) 4 us and us. x Dicrionaries + votes={'ved’:3 , ‘bue': 5 vores. Keys () + Output :L ‘bue', ‘red'J voterl ‘Jo1d"] =4 # add a key /val del vores [‘go1a'] # deletel Key votes £ blue] =6 # change value ten (votes) e 2 votes. values ( ) # (6,3 J “green' in yotes # False votes. nas__keyl'ved’) # True # Numbers :- total =32*3 # Output :9 tote = F572 *B 4 output itl Cost = 1:50 t 9.95 ae output: §.25 toral = Int ("g")+2 4+ Output : 1/0 ATue kumar (nKedin). uples i- NOTES GALLERY (TELEGRAM), Like Wsts, except they cannot be changed tuple 1 =(1,2,3,"a" "2") # Creates cuple tupte 1 £3] ae x _hists :- sores =1'A" ‘2’ 90, 75, ee, scores [OJ # Output: ‘A’ scores [1:3] #'C', go geores.count (‘c’) ee seores..append ( 100) t Adds 100 fo list Seores for ( ) +t yemoves third jem. yar CLINIKEDIN )- of Dsinon OOPS Concepts Fomon fe 9 mutiparadigm programming fanguage. It Seppoats aeferent Programm|ng eppyoches. One of tre most popular approcher fo solve programming problem by Creating objets This }s fknoWn as objet Ortented programming. ( OOP). “OOP hos 7190 chavacterisHes D> Attrivutes 2). Behavior Eyample A parrot }s an object, as it has Following Properties. + name, age, Color as attyibures. * Singing , Sanding a6 behavior. The conupts of oor: In Python focuses on creating reusable Code. This Concept js also known Qs DPy CDon't Repeat Yourselt ). & Class is a blueprint for the Object. we can think of Class as a skech of parrot with labels. [F contains qil duals Ohout the name, colors, size ete. oy. Class farrot: Pass. AT KUMBRC CINK ED IN) FECES RAN NOTES GALLERY. Spb bbbebbbdeadddddeedeweeres : e Hexe clacs Keyword detiné on empty class parrot from Class We construc fnctances (-)n Instance js a Speelele Objat created From a Particujar class. ru Korn TELEY RIN - NHS GALLERY. #m objet Cinsranee) }s an instantiation pf a class. blhen Cc shh fs defined only phe aiseription #08 phe Class Objet £ defined. Therefore, nO memory ox «forege 1s allocated. exi- Obj = Parrot ¢ ) Here Objet fs On objet of class parrot: Suppose We hove details of parrots. alow (02 axe geing to show howd ¢0 budld the class and Obj er” oF parrots. we can access the Class attribure using — Class_ species - Bonerivane }s qa Way of Creating new class for using doteils of an existing class without modifylng it. The newly formed clots fs derived class, Simillarly , +h2 existing class Is a base class» Ex > Yse of Jnnevifanu in python - Class Bird: der_Init_ (sere): Print ("Bird ie ready") def culm (ree): Print (" susie Fasper") Class Penguin ( Bird)? JS —Init ( sere): SUPeY( ),-Init_( 7 Bh yun (see): Pz fen fon a) Bias Cin ear batty) p. stm) pant) “ATUL KuMAR (INKEDIAY « RC ddd ddeWveeoeoeeer Output Stam Facter yun Fast lAle can use ¢he fupey () Punetton Inside pne—Init_ Cl) Method+ This aloWsS us to yun — Mnit_() method. Using OOP fn python , we can yettrict access 40 methods and Vaylables. Tris prevents deta from dived moufication Which is cated encapsulation. In python We donate private attribute using — at tht prefix. fe Single — ov double —- Glass Computer? def__fnit.. (See): Selk__ Maxprice = 900 ek cetmoxpner ( ert , Price ): SUF, 2 MaxPslee = price, C= cCompurer( ) C.__ Maxpritz -j000 C. Let max Prin (100) ble used_init.-( ) method fo tose the maximum felling Price of Computer. Cc. Max price =1000 Vartable Class Member Access From own | Acces sthte cessible access spetthey Tuk WOMAR (INKED IAI). NOUN L LLL Lecaddddveneeeeresee Poly me rpm fan ability to uLe 4 Common Interfau for mutiple forms (data types) Folymorprism Mn python defines methods in the child class thet have the same name ar the method in phe pasent Class. fh 1s possible +0 modify 9 Method Inq child class thet Mr has Inherited From Cid class ,. Parent Class Class parrot ; def Fly (tele): Print (" Paryot conkiy") def swim (ef) Print (“parrot can't stsim") Clase penguin: def Fly ( sete): Print (“penguin can't Fly") de rulm¢ cere): Print (“Penguin can stoim") der Fuylng_ test (bird): bird. Fly( ) biue = Parrott ) feg = penguin) lying test (blu) Fuying — test (Peg) Ovtpur Poyron Can Fly. Penguin Can't Py. ATU Lumar CLINKEDIN). lthet are Funcefons ? # Fanetlon ic a plouk of Code Only suns bhen Is called: Dh Python a Funetlon ie defined using pre der keyword . def my — Furetion (): print C“yeno") Arguments fn a Funcoion Arguments are specified after the function name, inside the Parentheses. Yeu can add 4S many argument as you tant Leparate ¢hem ith q Comma. deF my — Rinetton CF name) Print (fname + “ ReFsnes") my Fanetion C"Emit") my - Funeton ("Tobias") my — Function Chinas") TECELRAN METES CALEERY. Arbitary Arguments Se you do not know) hou many arguments that toil) be passed inte your Funution, add a bebore the parameter nme in the function definition. Oe ray — Funurton (Mkids) : print ("the youngest child i¢"+ kidsl0) Mg-Fancelon(" Sour” "9031", “txpark") MAK (LINKEDIN) \sbbbbhsikrrreerrReeeeeeecre. DULNULUL UL beTdddddddweneeceser Keyword Arguments ( Kwaxgs) You can alsO sond argument? tolth the Key = value Syntax - def my- Rinefon (ontias, CNida , CMidz) : Print (“tne Youngest cntia it"+ Old 3) my — baneeton Cobdidy = "mtb" childa ="bea", Childs =‘bee") E ATUL KOM BR CLINKEDIA) - Arbitary Keyword Arguments ** Kwargs co not Kn0W ho many Keyword arguments that wil) be pocred Into your function, add 7W2 Qsterisk: * * before the parameter name }n the Function definition . dek my_ Function (#3)? print (“nic last name se" Kid C“tname I) my fanetion (fname = “Tobias”, tname = “ReFenes”) Atul Kumark CLINKEDAI)- PYTiwon Operator CHEATSHEET ‘ reomoal ui nKeDin)- Arithmetic operators: ‘Norer Saar CrSceaaaey An arithmetic operator performs mathematical Operations like addition , subtyacton , division and multiplication. Meaning [ Exampie | Lael eee as Subtract two operands ip oeecn 2: | Multiply +490 operands So > oe a0 divide the left ofevend by Sacshie vight operand 5 ulhich will glve us remindar >>> 8 part a ue which will give Integer >>>sil3 Part 1 raised to the power Pr>O* KZ 125 prucxorpn (einkedial)- Comparisions operator operator] Berevinion __————«i amie IF two operands values are equal, Pr? 553 then the condition becomes true. Fasc Values of two operands ave not >>> Sl=3 equal, then condition become True true. >) IF the value of left operand is >>> 4>3 gyeatey than the value of rignt True operand, then condition bewmes true. < TP the value of 1eFt operand is >>> b<4 less than the volue of vignt false operand, then Condition becomes true. >= Syeater than equai: [F tne value of D> e>=6 left operand is greater tnan or False equal to the value of right operand, then condition bewmes true. less than e Sooa— 4G True ATUL KUMAR (LINKEDIN). ‘RloTes GALLERY (TELEGRAM). Logical oPerators © Logical operators js Boolean expressions Juth as and, or, not. © [t is fusta conditional resr thar @ resuir js either tvue or False. Continue —> Operator Description Example And It two operanas ave true | >?> True and Tue Ft become trues True >>> False and True Falre Or it two operands are non-24r0] y5>Tyue oy False then conalton becomes true. True >>> False oy False False Tt ts used to reverse the p>> not True logical state oF its operand > False >>> not not not True Faice ATUL EUMARLLINKEDIAL). ‘aloTEs GALLERY (TELEGRAM). Assignment operator: Dexvinvon Ea Assigns values from vignt side operands >7>x=20 t© left side operand. It adds right operand { the teft operand >>> Xt 20 and assign tne yesuit to left operand. It Subtvatts vignt operand from the 1eft | >>>x-=20 operand andascign the yesuit to 1¢Fr operand. It multiplies vignht operand wlth the >>>x*#= 5d 1eFt Opevand and qssign tne result to left operand Dr divides left operand With the right >?>x/= 50 operand and assign the vesult to let bpevand. >>>Xy- S50 It takes modulus Using two operands and assign tne result to left opevand. PesPorms exponential (rower) calcujation >?>x #¥=50 on operators And assign value to the let operand. St performs Flooy division on operators And >> x// = 50 assign vatue to tne left epevand. ATUL vomek (LIMIKED IAL): M ember shi P_ Operator [ persiptian pier ges [Ope aa Evaluates to true IF It finds @ vartable In the specified sequence and False omerwice. Evaiuates to true 1 IF does not Finds | >>>x= "Python" Q@ varioble in the spedified sequence >rriz' inx and False otherusice- Folse. ores GALLERY (TELEGRAM), jn both operands Tt copies a bit if it exists In either operand. ° It coples the bit iFit 1s set tn one 2>7 10%20 epevand bur not born. [omane [bem ene | Operator copies a bit fo the vesult TF it exists ° 30 Tris unary and has the effet of ‘ripping’ pits. The left operands value is Moved tert by 2>710<< 2 the number of bits Spedfied by the vight 4o orevand. The 1eFt operands vatue is moved yignt by >>rlor>2 the number of bltry Specfled by the yignt 2 operand: Example. Evaluates t© tvue IF the variables on >>> x= “hello . elther Side of the opevatoy reint to the >>>ys “netlo” fame objet and falre otherwise. a2 KILy Evoluares fo False If the variables on >>> x="hello” elther side o€ tne Operator point to the | >>>¥= “hello” fame orjet and True ornerwl se. D>>x is not ¥ False. Pron Moles BLES 8 DATADIE Python Variables —— Variable 1s a name that is used to vefey to memory tocarion - Python ig also Knoton ag an jdentifier and Used to hold value. Tn python, we don't need to pectFy the type OF variavie python is q infer and smart enough to get variable type. example! x =10 name = Atul kumar” value = 122. Aut koma (Liat edin ). NOTES GALLERY (TELEGRAM) Varlable are the example of identifier. An Identifier is used to identify the literals used In the program. Rules (© name an identifier — © Tne First chavaurey ©F the variable must be alphabet or underscore (_), e@ All chavacrer except First charatrey moy be an alpnabe (A-2) , (A-z) ov digit (0-49). Continue —> YdentiRer name must not contaln any white space or 5 result SS true. andX >I0 ) uLKumen (LIKED. Puthon ide: Operator, Identity Operator are used to compare the objet, not if th are eqial: bur TF they ave actually came objet With the came memory locarion. operaroy | _Desexietion | gearnpte_| Return True TP both yaviables are K ts Se tne came object. ot Rerurns crue TF beth are not is no same Ovseut- thon membership Operator | Membership operaroy are used to test IF 4 Sequence is pretended 1s an objeuw. in Return True if a Sequence with rhe SpedAled value ts present notin Rerun Tyue TF a sequance NOirh the Specified value fs nor present. on Bitwise Operator, Bitrotse operator perform bit by bit operation en rhe values oF tWo Opevand. Consider the Following rable. Continue —> rut xumoer (UuniceDial) Set cath bit to 1 IF poth side axel Sek each pit to | If ene of two pitis | Set each bit to 1 Ff only one OF tWO pirs is 1. Inverts_Qil tne pits Zero FN! ShIFt 1eFt by pushing zeros in fom leet sniet the xignt and let tne lefrmost bits Fall oFF- Signed vignt Gnift wignt vy pusning copies oF se the leftmost bit In Lom the tere and vet the alghtmost bits Fall off. aque ANIDTES GALLERY ( TELEGRAM) python Input 0) Funcion fytnen mpur funuton Js used to get Inpur From user. tt Prompts for the usev Input and vead a line. Afrer reading dora. iF converts If Inte q gtying and yeturns phar. tr rnrows an ervvor E of evo is EOF js yead. (Parameter) prompt: Ir ls a stving message uirn prompt for usex fnpur. CReturn) fr yeruyns user Inpul aFrer converting ino gtying - ler See an example oF Input) function f° understand irs Functionality - Continue — Cunneral). example = Jogut 4 Python Jnput() Funcrion . Val = Input (“enter a vaiue + print (“you enrered! val) ") Ourpur _ Aut compe (Linicedin)- = NOTES GALLERY (TELEGRAM J enpeya value 7 20 you enteved ; 2° p(LINKEDIN ) 1+ Does Pyehon have OOP'S Concept 7 > Farnon is an Object Oxtenred Programming language - This means that any Problem can be Solved In python by Creating 4 model. towever , python can be tregted 9S procedural af well os styactural language - 2. How go add _yalues qo Python array? > Lvements can be added fo an array using the append (), extend () and insert Ci, x) Ainction. a). append () b) extend C) Ob Wkesis (6 2) Arut weomAk (LINKEDIN). 3. How do yey do cata absraction In python ? > Pata abstraction i provicling only phe required details and hiding the implementation From the world. It can be achieved In python by using interface and abstract clase. 4. How will you capitalize the First jetter_of ftring ? > fr pe python , the caplralize() method capitalizes tne First letter of String. fF qe dtving alseady cons shets of @ Capita] letter of tne beginning , then it returns the original ttving « 5+ what are generators In Python? > Functions thar yeturn an Nevable fet of (MS are called generators . ATUL KUMAR (LINKEDIN): 9 6: kthat-arve doc Strings In Lython > Decsrings are not actually comments, but they are clocumentation Strings. These cdocstringt are within Friple quotes - They ave not assigned to any varlable and therefore , at pimes serve the purpose of Comments 4F bell. example t- Using docstying at a Comment x=e | Via Z2=x/y Print(2) 7 that are pullts-in type of Python ? > * Lntegers * Floating - Point * Complex numbers * String se ccine ATUL 1eumak (LINKEDIN, * Bullt in function IOTES - GALLERY (TELEGRAM ). 3. Detine encapfulation In on 7 > Encapsulation means binding phe code and data together» & pyrnon class i$ an example of encapsulation « 4. bdhat does an object() clo? > Lt xetum a featureless object that has a base class for ail classes. AIse if hoes not fake any parargeter. grul kumpk (LINKEDIN): 10. How 40 create empry Class in Python ? > Te empty class i$ 9 class that does not have any code detined Lowhin ity block: Jt can be created using phe pass Keyword « Howevey , you can Creare object of pit clasts outside the clors itell» In python phe Patt Command coer nothing vohen Ite executed ihr a nyll Ssratement + ample i- "Class a: Fast obj = at) onjname = "xyz" pring (iam e "object: name ) pruc koma (LINKEDIN). NOTES GhLLEny (TELEGRAM). Us Does on Le zt _muptipte Lnheritance 7 > Muitiple inheritance means phata ~ (class) can be cerived from more than one parent classes - Fyrnon ves not support multiple inheritance unlike java- 12. pdhat is Polymorenism in python ? > Feryrnowpnism means phe ability fo cake multiple forms..s0 far injrance- LF the parent class hat a method named ABC then the child class also can have refed with Same name ABC having its 0M parameter and variable python allows polymorphism « 3. 'S Split used for? > the splitl) methed i¢ used 72 separate a given stving In Python » oom a= “edureka python" Point (a. Split l) ) ATUL Juma CLINIKEDIN. ly, pov to Import modules In ython ? > Aodules can be imported using the import keyword: You can import modules in three Lays: ample — 2#® import array R* Import array ax arr iL Kempe ‘UNKEDIN) - S# From array import Notes Garvery (TELEGRAM). 15+ What is Fretng andl unpickting ? 7 Pickle module accepts any python object and convert it into string representation @nd dump it using clump Function , this process ig called piekling - hile the process of yetriving original Python objects fro) tne Stored Prewre moduse accepts any python object and convert it into Re?) v utring yepresentation and dump it using sump Finution, pls process 3s called pickling + mle the process of vetriving python objects From pre spored String represenfetion is celled Unpitkding . 2). | bth ave geneyators in python ? > Functions pret rerun an jpevable set of items are called meneratorr: “TELEGRAM NOT CY GALLERY: 3)-[How you will capitalize the Airct settey of string? > fn python, rhe capitalize € ) method capitalizes pre Arst letter of string. IF the string already consists of a Copitel Jotter of phe beginning _ then, (f seturns the Orlgine string. 4). [Tbe ave dbcstving In python ? | > Docstring are nor actually comments , but they axe documentation strings. These docstrings are within triple quotes. They ave not asslgned 40 9ny variable and therefore, at dimes, serve phe purpose of Comments 45 Wel]. example cs wun using doestving as q comment mun x8 Y*g 3 =xX/y Print 63 ) ATUL Jeumar (LINKEDIN): Tn types oF Python. 50. (eahat are bulits. > ° Integers + Floating - Point + Complex number + String * Boolean * Built In funcelon « 4] > Encepsulation means winding phe Lode and data fogethey- A- Python class is an example oF encapsusetion ATUL 1eoMnrR (LINKEDIN). “TECEG RAY - NOTES PALL ERY: 7]. Lihat doet an Objectl ) do? > Et yews a featureless Objet phat }s 9 base close For all classes. Also it dees not qake any Parameter- 3) [How fo create empty class in py¢nen? | > Tre 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 entside pre class iFSEIE. Jn python fre pIss command does nothing when its executed - its a nall steterment : orame)le :- objtacy objname = "x3" Print ( “rlame 2" Obj.name) 9) Does Pynon Support musiele inhevitane ? 7 pyputiple Inheritance means theta class can be derived From more dan One parent classess - Python beer support miuhigle Inhevitanw . untilee . gave. LINKEDIN). 10): [phat Ts Polymorpricm in Pyphon 7 > Foymorprism means phe abitity fo ¢ake multple forms so bar Ingronu FF phe parent class has 9 method named ABC then the child closs also can have method with same name ABC having Itt own paramerey and Variable Python ows polymorphism + uy. awd do you clo lata abstraitlon_in Pyphon ? > Dero abstyartion js providing only phe vegulred teralls and Afding g¢he Implementation from from the World- It can be ackived In python by using tngerface and absbret clas 12)-[How #2 import moduler In Python ? > Moeceules can be Imported using phe Import Keyword - You can impoxt meclafes in phree waus eremele?- @- import avrvoy ®» import avroy as arr © From artoy Import #, 15h 7 The sputl) method Is used 4 seperated @ glen string in python - ovample:- a= “edureka Python" print (4. spurte ). 4). [Does Pyenon have Ooh: Conupe ? ] > Parnon ie an objet Oriented Prgramming Janguage - Thi means thar Qny Program Can be solved jn python by cresting a model. However, Python can be heated as pybwmduyal as Well os styuctural Jang Arutcomar (LINKEDIN). TELEGRAM” Noles GALLERY '5)-[fo yo add Values 40 Purhon avvay 7] 7 Elements can be aaded 40 an qrvay using phe append() , Keng () and Insert (i ,x) function . © appendt) © extendc) ® /nsertc), INKEDIN)- PYTHON INTERVIEW) Choesty ONS Part -1 1). Leahar type oF Tanguage jy Pyghon? Programming or Scyletiag! > Fython Ny capagre of scripting , but In general purpose Programming Janguage 2) [Yow 1s Pychon an Interpreted sanguage : > fin interpreted Janguage 3s any programming janguage vnich is not tn machine level code before yuntime. Thereteve, python is an interpreted sanguage- nae CUNneOn TELEGRAM NOTES GALLERY. 3). [mdhet i's Pers 7 # name PEP stands fer python Chhanument proposal: It is 4 tet of yeyes thar spedhy how t0 format python code for maximum yeadabtlity - wf you is memory manages In Pypron 2 Pe Memesy management In python js managed by python private heop Spar. Ay) python Objects and dard Srruttures Are located sn privete heap. The Programmer does not have access 70 PAIS pyivate hep Tht python Interpreter fakes care of instead. * fru allocation of hep spau for python objects js clone by pythons memory manager. Pmt cove API glues Qecess 40 tome deole for fre pregyammer fo Code, ATUL KUMAR CLINKEDIA ). © Fyrhon also has an inballt garbage Fayrnon mediles ave Files con¢elning python ode. Tals Code can be Functions Classes or Yariables. # python modules ia “Py File containing executable Code . Some of the commonly used bedit-in modules are: os 0 Sys » datatime «son - 7. [huhar Gre focal and 9 /ober Warianje in Python? | > Global variable :- Variables declared Outside a function oy jn globe space are coled globe! Yarlables- These Variables can pe accessed by any Function In the Pregvam. Local Variables :- fing Vaviabte 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 ? 7 Yes, pyshon 75 @ Case sensitive language. 91. [Kdhet Is 7gre Conversion Tn Poron? P Ide conversion yefers 40 the convertion of One datg type Info anogher Pot eh IRE CI PORE Cy A ero 10). [TeTnaentation veguised In Python? | > Ihdenration js necessary for pyphon. It spedFies a bok of code « #1) Code within Joops classes funtion ete Within an Indented bros. It Is usually dene using four space chavauer. jf your code }s not indented necessarily - Jt will not execure accurately and Wl) thyol” eyyorl as well. w)-[lahar 97e Lunerians In Pythons 2] > FF Funution Is a block of Code which IS Exetuted only whin if is cwled. Te deFine a pyphon function, qhe def kay Word js used. def NewFun( > print (“iri ") 17]. > —Init_ is a method ox Constructor In python. This method is autor wt eally called to etvocete 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 (3. name) 19). Ikdhat is lambda Function 7 fn anonymous Function 75 kKnotdn 46 @ lambda Function. Prt funcrion can have ang number oF pavamerert but have gush one Statement. Q= jaonbs9 X,Y: x+y Print (acs ,¢)) ATUL Koma LINKEDIN): su). [thar i serp In Python ? > Self is an Insfane oy an objet CF @ class. Jn python, this ts explicitly included aS the Frrst paramerer. This is not the case In Java where I's optiona » ft helps 4o differentiate Lerween the methods Qnd ettylbutes of a Clots bith Jocal variables. Tre sep Variable in phe init method yofey 4° the newly created object wile in ether methods, i xefers fo the objet” 1dho- Method toGs called. Atul komma CUNKEDIN). TELEGRAM” RITES GRUERY. 15)-LbKhet ave on Ttevayors 7 7 Drevators are objects which can be fraversed though or itevated upon.

You might also like