You are on page 1of 31
PYTHON BASICS ® General {nfermation :- binitespace matters | Indent’ where needed. Import modules " import modulename” 3h This if @ Comment: print ("Hello world") 4. Prints to screen * Conditional Statements :- tf fs Sunny: Print (‘It's Sunny | iy) elif gog = temp < 10° and bath > 80: print (‘Bach js hot and Full!’ ) elif not Cc fee == qa’ ox (usr == 4am’): print (‘Match if not ya or adm 2) else: print (‘alo math. job is 't for) AquL eumer (LINKEDIN). x Sri :S 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'] (icin (Glad gic) ARC nine=str(9) ## Convert int into stving title. yeplace(‘them’, us’) 4# us and us. x Dicrionaries + votes={'red’:3 , ‘bue': 5 vores. Keys () + Output :L ‘bue', ‘red'J voter l ‘Jo1d"] =4 # add a key /val del votes [‘go01a'] # deletel ley votes £ blue] =6 # Change value ten (votes) 2 votes. values ( ) # (6,3 J “green' in yotes # False votes. nas_keyl'ved’) # True # Numbers :- total =2*3 # Output :9 tote = F572 *B 4 output itl Cost = 1:50 t 9.95 ae output: §.25 toral = Int ("g")+1 4 Output : 1/0 Aru puma (syniKedin). uples i- NOTES GALLERY (TELEGRAM), Like Wsts, except they cannot be changed tupie 1 =(1,2,3,"a" "2") # Creates cuple tupte 1 £3] # 6a? x _hists :- sores =1'A"'e' 90, 75, roel, ceoves [OJ # Output: ‘A’ scores [1:3] #'C', go geores.count (‘Cc’) ev) seores..append ( 100) tf Adds 100 f list Seores PoP ( ) +t yemoves third }tem. mar CLINIKEDIN )- a Dsinon OOPS Concepts Fomon te 9 mutiparadigm programming fanguage. It Seppoats afferent Programm|ng appyoches. One of tre most popular approcher fo solve programming problem by Creating objets This 1s fknoWn as objet Ortented programming ( OOP). “OOP hos 7190 chavacterisHes D> Attrivutes 2). Behavior Eyample A parrot }s an objec, as it has Following Properties. * name, age, Color as attyibures. * Singing , Sanding a6 behavior. The conupts of oor: In Fytnon focuses on creating reusable Code. This Concept js also known Qs DPy CDon't Repeat Yourself). & Class is a blueprint for the Object. we can think of Class as a skech of parrot With labels. [F contains gil duals Ohout the name, colors, size ete. oy. Class farxrot: Pass. ATH KUMBRC CINKED IN) FECES RAM NOTES GALLERY, SpWbubbbebbidccdddddeWdeweeres : e Herve class Keyword detiné on empty class parrot from Class We construc fnctances (-)n Instance js a Speelele Objet created From a Particujar class. ru Korn ELEY RIN - NOS GALLERY. #m objet Cinsrante) }s an instantiation of a class. blhen Cc eee fs defined only phe aiseiption Fos phe Class Objet £ defined. Therefore, nO memory or «forege Is 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 bubld the class and Obj er” oF parrots. we can access the Class attribure using — Class_ species - Gonerivane }s qa Way of Creating new class for using details 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 Jnnevifana in python - Class Bird: der_Init_ (sere): Print ("Bird ie ready") ek culm (ree): Print (" susie Fasper") Class Penguin ( Bird)? Jk —Init ( sere): SUPE ( ),-Init_( 7 Bh xu (see): Pz fen fone o) Boia Cin ea tatty) gp. swam) rant) “ATUL KuMAR (INKED IAL « MOC ddd ddeWveeoeoecer Output Stalm Faster yun Fast lAle can use ghe fupey () Punetton Inside pne—Init_ Cl) Method+ This aloWsS us fo yun — nit_() method. Using OOP fn python , we can yettrict access 40 methods and Vaylables. Tris prevents deta from dived mouFication Which 5 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 setmoxpniee ( sert , Price ): Sak, 5 MAxPslee = price, C= Compurer( ) C.__ Maxpricz .j000 C. Let max Prin (100) ble used_init.-( ) method fo tose the maximum felling Price of Computer. Cc. Max price =1000 Varlable Class Member Access From own | Arccessthte cessiole access spefhey Ud WOMAR (AINKED x1). NOUN L LLL Lacaddddveneeeereser Poly me rpm fan ability to ULe a Common Interfau for mutiple forms (data types) Folymorprism tn python defines methods jn the child class thet have the same name as the method in phe pasent Class. fF 1s possible +0 modify 9 Method In qa child class tht Mr has Inherited from Cid class ,. Parent Class Class parrot ; def Fly (ser): Print (" Paryot conkiy") def swim (ref) Print (“parrot can't ststm") Clase penguin: def Fly ( sete): Print (“penguin can't Fly") de rulm¢ cere): Print (“Penguin can stoim") der Fly ng_ test (bird): bird. Fly( ) biue = Parrott ) feg = penguin) Plytng— test (blu) Fuying — test (Peg) Ovtpur Poyron Can Fly. Penguin Can't Puy. ATU Lumar CLINKEDIN) lthet are Funcefons 2 # Fanetlon ic a plou of lode Only suns bhen Is called: Dh Python a Funetlon he defined using pre de keyrord . def my — Furetion (): print C“yeno") Arguments fn a Funceton Arguments are specified after the function name, inside the parentheses. You can add 4S many argumentr as you tant Leparate ¢hem 9th q Comma. deF my — Rinetton CF name) Print (fname + “ ReFsnes") my Faretton C"Emit") my - Funeton ("Tobias") my — Function Chinas") TECELRAN- NETES CALEERY. Arbitary Arguments Se you do not know) how many arguments that toil) be passed inte your Funution, add a bebore the parameter NIme in the function definition. eF ry — Funurton (*kids) : print ("the youngest child i¢"+ kidsl0) Mg-Fantlon(" Sour” "9031", “txpark") MAK (LINKEDIN) . sbbbbhukrrrreerrreeeeeecre. DUWNULLL UL beTUddddddweeeeceser Keyword Arguments ( Kwaxgs) You can alsO sond arguments Lolth the Key >= value Syntax - def my- Rineeton (onias, CNida , CMidz) : Print (“tne Youngest cntia it"+ Old 3) my — baneeton Cobiidy = "mth" childa ="bea", Childs =‘bte") E ATUL KOM BR CLINKEDIN) Arbitary Keyword Arguments ** Kwargs co not Kn0W ho many Keyword arguments that wil) be pacred Into your Function, add 7W2 Qsterisk: * * before the parameter name }n the Function definition . dek my_ Function (#8 Gd): print (“nic last name se" Kd E“tname I) my fanetion (fname = “Tobias”, tname = “ReFenes”) Atul Kumark CLINKEDAl)- PY Tiwon Operator CHEATSHEET ‘ weomaal i nKEDiN)- Arithmetic operators: “‘Norer eae recat An arithmetic operator pevforms mathematical Operations like Qadition , Subtvacton , division and multiplication. Meaning | eExampie | — wee ‘as Subtract two operands i> 7 onecn z a Multiply +490 operands oo a 20 divide the left ofevend by Saco Le vight operand a ulhich will glve us remindar 2>> 5 part a uy which will give Integer >>>sil3 Part 1 raised to the power Prr>O* «KZ 125 prucxompn (einkepial)- Comparisions operator | Sperator] —Bererinion _————~ixameie IF two operands values are equal, Br? 553 then the condition becomes true. faeces Values of two operands ave not >>> St=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 conditon bewmes true. < TP the value of 1eFt operand it >>> b<4 less than the volue of vignt folse operand, then Condition becomes true. >= Syeater than equai: IF tne value of D> 7 >6 left operand is greater tnan or False equal to the value of vignt operand, then condition bewmes true. less than e D>>4<=8 True ATUL KUMAR (LINKEDIN). ‘NloTes GALLERY (TELEGRAM). Logical oPerators © Logical operators js Boolean expressions Such as and, or, not. © ft is fusta conditional tesr thar @ resuit 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 Falsre Or it two operands are non-24r0] s>>Tyue oy False then conaltHon 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: Descinton Ea Assigns values from vignt side operands >7>x=20 t© left side operand. It adds right operand { the teft operand >>> KXt=20 and assign tne result to left operand. It Subtvatts vignt operand from the eft | >>>x-=20 operand andascign the yesuit to 12FE 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 bpexand. >>>X7>=50 It takes modulus using two operands and assign the result to left opevand. Pesforms exponential (rower) calcuiation >?>x ¥¥=50 on operators And assign value to the let operand. St performs Flooy division on operators And >> x// = 50 assign vatue to the left opevand. ATUL vomek (LIMIKED IAL): M embershi P_ Operator | Dersiptian a. Geese [Omens oa Evaluates to rrue IF It finds @ vartable In the specified sequence and False omerwice. Evaiuates te true TF It does not Finds | >>>x="Python" Q@ varioble in the spedified sequence >>>iz' inx and False orherusice. Folse. ores GALLERY (TELEGRAM), jn both operands Tt copies a bit ie it exists In either operand. o It coples the bit iFit 1s set tn one 2>7 10%20 ePevand bur not born. [omane | beni ene | Operator copies @ 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 >prlor>2 the number of bity Specfled by the yignt 2 operand: Example. Evaluates te true IF the variables on >>> x= “hello . elther Side of the opevatoy peint to the >>>ys “netlo” fame object and falre otherwise. 22 KIL Evoluares fo False If the variables on >>> x="hello” elther side o€ tne Operator point to the | >>>¥= “hello” fame orjet and True ornerwil 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 nold value. Tn python, we don't need to pectFy the tye OF variavie python is q infer and smart enough to get variable type. exampie ! x =10 name = Atul kumar” value = [22 Aut koma (tint edn ). NOTES GALLERY (TELEGRAM) Varlable are tne example of identifier. An Identifier is used to identify the literals used In the Program. Rules (© name an identifier — ° Tne Airst chavaurey ©F the variable must be alphabet or underscore (_), e@ All chavacrer except First charatrey moy be an alphabe (A-2) , (A-z) ov digit (0-49). Continue —> YdentiRer name must net contaln any white space or 5 result SS true. andX >I0 ) uLKumen (LINKED. Python ide: Operator, Identity Operator are used to compare the objet, not if th are eqial: bur TF they ave actually came objet With tne came memory locarion. Operaroy | __Desexietion | gearnpte | Return True TP both yaviables are x ts Se tne game object. ot Reruyns crue TF beth are not xis no same Ovset- thon membership Operator | Membership operaroy are used to test IF a Sequence is pretended 1s an objeu. in Return True if a Sequence With rhe SpedAled value ts present notin fRerurn Tyue TF a sequance NOtrh the Specified value fs nor present. on Bitwise Operator, Bitwtse operaror perform bit by bit operation en rhe values oF tWo operand. Consider the Following rable. Continue —> Aru xumoek (UuniceDial) Set cath bit to 1 IF poth side are Set each pit to | If ene of two pitts | 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 sntet the xignt and let tne lefrmost bits Fall oFF- Signed vignt Gnift wignt vy pusring copies oF se the leftmost bit In Lom te tere and vet the alghtmost pits Fall off. AT ANIDTES GALLERY ( TELEGRAM), python Input 0) Funcion fytnen mpur funuton Js used to get Inpur From uses. [t Prompts for the usev Input and vead a line. Afrey reading dora. iF converts If Inte q gtying and yeturns phar. tr rnvows an ervvor E of evo is EOF js yead. (Parameter) prompt: Ip 1s a stving message uirn prompt for usex fnpur. CReturn) fr yeruyns user Inpul aFrer converting ino dting - ler See an example oF Input() function f° understand irs Functionality - Continue — Cunnenral)« example = Jogut 4 Python Jnput() Function . val = Input (“enter a vaiue + print (“you enrered! val) ") Ourpur _ Aut compe (Linkedin) = 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’ Oxtented Programming language - This means that any Problem can be Solved In python by Creating 4 model. tfowever , python can be tregted 9S procedural af well os styuctural language - 2. tow go add _yalues qo Python array? > Elements can be added fo an array using the append (), extend () and insert Ci, x) Ainction. a). append () b) extend C) c). insert () Aue weap (LINKEDIN). 3. How) do yoy clo cata absraction In python ? > Pata abstraction i$ provicing only ghe required details and hiding ¢he 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 eaplralize() method capitalizes tne First letter of String. fF qhe dtving already cons shets of @ Capita] letrer 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 are not assigned to any varlable and therefore , at fimes serve the purpose of Comments 4F bell. Example t- Using docstying Qt a Comment x=e | Via Z2=x/y Print(2) 7 thot are pullts-in type of Python ? 22 * Lntegers * Floating - Point * Complex numbers * String eo ccine ATUL 1pm (LINKEDIN, * Bult in function AIOTES - GALLERY (TELEGRAM ). 3- Detine encapfulation In on 7 > Encapsulation mens binding phe code and data together» & pyrnon class i$ an example of encapsulation « q. bdhat does an object() clo? > LF xetumn a featureless object that has a base class for ail classes Ase if hoes not fake any parameter. prul kumpk (LINKEDIN): fo. How 40 create empty Class in Python ? > Te empty class i$ 9 class thar does not have any code detined Lowhin ity blocks Jt can be created using phe pass keyword « Howevey , you can Creare object’ of pris clast outside the clors tell» In python phe Patt Command coer nothing vohen Ite executed itr a null Ssratement + ample ir "Class a: Fast obj = at) onjname ="xy2" pring (Nam e "object: name ) prac kumar (LinKeDr) . NOTES GLLeny (TELEGRAM). Us Does on Le zt muptipte Lnheritance 7 > Muitiple inheritance means phata ~ (class) can be erived from more than one parent classes - Fyrnon oces not support multiple inheritance unlike java- 12. pdhat is Polymorenism tn python ? > Feryrnopnism means the ability fo cake multiple forms..s0 far ingrance- SF the parent class hat a method named ABC then the child class also can have rethed with Same name ABC having Its 0'n parameter and variable python allows polymorphism « 3. ‘S Split used for? > the splitl) methed ig used 72 separate a given stving jn Python - oom a = “edureka python" Point (a. split l) ) ATUL Juma CLINIKEDINY. ly, Hoo to Import modules In ython ? > Aodules can be imported using the import keyword: You can import modules in three Lays: ample 7 2 import array R* Import array ay arr , iL Kempe ‘UNKEDIN)- S# From array import * Notes Garvery (TELEGRAM). 15+ What is Freting andl unpickting ? 7 Pickle module accepts any python object and convert it into tring representation @nd dump it using sump Function , this process ig called piekling - hile the process of yetriving original Python objects fron tne stored 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) ). 4). [Dees Pyenon have Ooh: Conupe ? | > Pyrnon is an objet Oriented Prgramming Janguage - Thi means shar Qny Program Can be solved jn python by cresting a model. However, Python can be heated as pvbteduyal as Well os styuctural fang Arutcomar (LINKEDIN). TELEGRAM” Noles GALLERY '5)-[fo yo add Values 40 Purhon avvay 7] 7 Elements can be gaded 40 an qrvay using the append() , KXtend () and Insert (i ,x) fanctton . O appendt) © extendc) ® insert), 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): su). [thar i sere In Python 2 > Self is an Insfane oy an objet oF @ class. Jn python, this ts explicitly included aS the Frrst paramerer. This is not the case In fava where M's optional» fr helps Jo differentiate Lerween the methods Qnd ettyibutes of a Clots with Jocal yarichles. Tre sep Variable in phe init method yofey 4° the newly created object wile in ether method*, ft xefeys fo the object” 1dho- Method toGs called. Atul womak (UNKEDIN) TELEGRAM” RITES GRUERY. 15)-[Khet ave on Ttevayors 7 7 Drevators are objects which can be fraversed phough or itevated upon.

You might also like