0% found this document useful (0 votes)
2 views45 pages

II IA Python

This is the pdf of questions answers of python programming for 1st year BE students who study under VTU University

Uploaded by

sp5623183
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
2 views45 pages

II IA Python

This is the pdf of questions answers of python programming for 1st year BE students who study under VTU University

Uploaded by

sp5623183
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
Pe | Dichonany * ; fs SR eeicay fs a au of thems -whene dota ‘ts stored -as a -set ass : __ key - value Posns » Unhifee fists» which as = ailesies We elicticaan Padleoces “Can use Many cliffeccet cosa yes not jusl fotegess, able ; coordered, collection az Grating dictonanies » LT Geeeting ‘on fingly Sicfonany An tenply dictionany is defoed using a pasne ean ae Ee: dict name =§ } A Syrtee ated b commas Tose cunly Graces § 2. | Syotere fl? Valued ey Rey A Tmpesttact methods. of hior uh eng Lidichonany with sy tore, WT The get keys) Method Rei _a Dict ~ keys view. object containing all Fhe keys reeset sin the dichonany, Ls Syotasc + dict_name, keyst) 1+ Example + ___stuclest = $*name" : Axjun". "sem": 2} print Mist Ghuclertt feeys OY) #_Ourpus 7 ___T frname', “sem'] ST The wales) Method wt ied Retusns 02 dlict-valus view object containing all the valius present Ta the clicHonan Ly Syotox+ dict mame 4. valus() lL Beample: student : $name": "Arjue" , “semn+ 2¢ mn pooot list Gtuclent. vatwss U0) ——4 Ouspus: | TAgjue'; ae I Li BS The Hemst) Method Rekrans _dict-items viaw object comtainin o value pains as a sequine of ‘tuples. Frequecthy used wrth -fox loops, Syrtare } clict name. tHems oO _b) Eample. aes —____ishtdleot = $name's “Anjuo" 5 “Sem: 9$ + pint Gist Ghiderrt Hems0))) — > Ousputs ae [Coame’, Arjuo') 5 Csem’, 25] key- This lis Bison mea we Used 40_arebieve the valus of. a specified hexp “i foovents cuntime ervrs -by yekemning a Fel back abu if the keys -does not > Syrtecx: dict name. get (key, fallba ag Ayuo , OSM missing * a - y has specific key «does not alneac y exist Pathe dictic Tf the key exists, it acts Hs existe a eatio Ly | Syotace t dickumame. setclefault (kay, default. val} Eeample. om __ishident ¢ ¢"name": Ayjuo" } q istudent. setdefault :@ branch”, “cs €") __ pekot Gtudent) A Ontrpat = “ranch C3} I \ Bepla' the bey fecrhane and operettion of ' Python -clichonanie How -one Pret different a fom fists 2 Develop sustable prgwam +r fr ,. ° ILustrecte insethon , deletic ny ancl Lookuys. E hs Ax dlicHonany in -Pyjhon sis a collection of Ley. 5 E valur pains. T+ stones clata in the form of keys ba eS alut and Ps_woiten using curly braces $ }. Ben » "Name": Ravi", “ch studert = 5" Usni" = 101 Se Re ees ee la 1. Key-valu ‘Pain Storage’! Dova ts stoned _as NI ook ae 25) Mutable + Ego elmerts -can be chaagect —_ fer _encation, n 2 [Woigus Keys: Keys must be u unique, clplicate keys om act —ellowed, LA rast acess A _ Values can a aceessecl_g fotete | a: using keys, eta — 2 Heder genous Daa: _|_Go_stone dif fen emt Velsia® types: Chak Cloteger, ——_|_ sting, list —26), &D jerome sizes j — Ebruals - can, oe “adel ed_0v amoved anytime jelly A Creratior of gh. clase Nuw key pais student frAg « 7 vhor valus Ex Deletion : Elumects can be deleted using of del _ishident Age "] ees using -k Dictionary __priat Ghudet f° Name"T) A Difewee bla cicHoqan dO) 0% popt). Quiche List i. Stones data -as key~ valu “pains 2s re ~brackets 2 Accessed sasing keays. —_ 43 Reys -must be sunigus d3 Stones exceed cluments. [5 Uses T Dbrackets ByAccessed using fadex 4S Duplicate valves Fc lfecveck a sh ipicreFicl -Coonceortuatly| keey—based ) ae ss Ondesed collection -. Program -fo Tllustsafe tn A-Greating a di chon. wy studert = § “usr”: tol, “Name” : "Ravi ” +H Fasertion esttion deletion ¢ >" Branch” + 4S, Vibe! iS _NoumPy 2 How: Arra Pi Hachieved io pythoo2 Winiic a syotax ue > —lecrays io_pythoo ° F_4l NumPy Numescal Python) 7s_a python library used '— x scientific & numerical twomputations. powvides bias -fox_multi-cimensional arrays and nocthurng ~Heal_operctons on ava oumencal ealwlations. Example: ~_jepoat oumpy as 1p _ * Areoy forchionolihes achieved Co python, Fi To Python, aaay -fenctionalities ane achieved! using ae NumPy Iibrany. NumBy peovidles an object called _ndarway (n-dimensional condy)y which allows stoning & | ipreocessing, Langs amounts of data effiderty, E A Rae of NumPy Arrreys: Fast froussing of numerical data 5 5 “multi-climensional oonay Support: 5 3. Mathematical opersections on ammays, 4. [Less memory usage companed to lists. i wz [Easy indlexiag anc alretng “4 VAlnite ssyatax expl, tt c Y plas cnet or ; aod 3-D amays fy pylbor . =aF 3 Bython , arrays an _| library. import NumPy : __impont numpy as ye 35, One~ Dimensional (2-0) Array 2A 3-0 amray contains elements -?n a singh mw > Syoton, + sn Orrroy_ name = Op. ava (Lebments]) > | Exarnple : : ieopenct oumpy os np is arr = Np: onay ([10,20,30, 40) point Carry) > Output: [10, 20, 30, 40] b Two- Dimensional (2-D) Stray +A 2-D amay contains avws and columns (matsx form) > Syrtor(: ane name = opomay (LL 4, 202))) + Bearple: fenpost oumpy as op and = np. omay({Lt) 2,3), (45,671) | print Gx) Seles [cr 23] [4 5 ¢]] 33 | Three~ Dimensional (3-5) Aberay a LA a array eomtains mult ; _Sye xX: Ona y -—__ 6 Brample : ple -9-p a Froys. ham e=np. Orrray (Ce elements 377) ——_| import cumpy as np —____llaw3 imposr_oumpy as oj A opr wandom-randint Gros tass5) ~ pont © Oniginal Matise: ™) of ee ee ret C\0 Shope -of Matix: A eee sh at Asn) oat jo pant CreMean of Elements: %) Awmean()) Sample Ouspur Original Matix: [Tie 45 eT] T3335 347 ae SE? hap-of Matix s3) —Transpose of —trtatizcr Lit + 23—5€ ——- 45 39 78 6134) StI, Mean of clements ? 55-0 files> Fn) , xplarr handling ) Tt —Opamsereey p——* A file -ts o ewllechon of datansbxed permane 7 sntly ‘on a stovoge device. Files ane uw ed +o stone fafirmation so that. 74 can be actessed laters 4 ("Ts python, File handling ts used -to coecete, Tread , wnite , Oppend, and clase les io} Chetaty eT 3) wot Ly A +o wnite data yertox : File_object. unite CHext Ls _Eample f pen Esa, ple. oct", “w) ly. waite Chilis Python") 4S append) (a rode) = ee > Used to add new content fo an existing & Satex : " ae ae if =openC filename", a") f. waite (“ect”) we ants uti as — LE ae Ff =openCsample. tet") Fewaite CWelcome") _ sh close() Method, Ls Used -to close the file aftex opesation ML [ster __ Filecobject. closet) BEG Example nui ———_| f. close) ee od ai 4 a. ane a ¥ Readingftle r Pint Open Csample Oy Cy7eactory Ftlosety the ‘with? statement bai RP nd program, bs L —_hondle #1 re file, so closec) method explicitly, BS __ IT makes File ha ad Syertox : 7 open "filename", File object: 4 File open dling “easie #4 Advarrlac 3: || Preveret 4. Teproves. readability * Ocspus : ~_# | Pnogvam “Using ‘with’ Statement: Hf Waitiag ~bo a with open Csample.+ ") as f: F-waite Cello’ Python") ft Reading from the file __|with opeo-Csample. tet” | content _= f. read ¢) I. file~velated -2 | priot Content) | Hello Python ———_} file using with RT SO Eee binany -files cliffex -fomn troy ile H fn term: oofent anc erate lt ae wih suttable “program segment } A file te Python can be of -two types: iS Text file iS Binany file WText Fie : i WIA tect File stones deta t Gext) that con be read 00 the for of choracters by humans, 2 *Pys + €sv z => Examples : 4x4 4 | Reetaness em —_* | Stones data 2s chanacteys PP ay * | Human= Tidights:Csand is) and is + Ls txamples : image file Gijpg, «mp3, ov Feaunes : ata te binany format Mot fuman~neatable _ Uses modes slike 7b” and "wo «Faster for non-text data handling __ A Waiting bieany dota ‘Anes __|with open (binonyfile. bin”, “wb") as _f-write Co"Hello") Hf Reading binony dasa with open Cbinonyfile. bio”) “76 das f: bint Cf. cod Q) Difference blu Text File and | Inany “File mr: Lert Ble *# Bloony File fab Stones text / chanacters tL Stones binany data ra nae 2 Human~readable 2\ Not human= radable 7 33 Uses 9, 50. modes 3S1Uses “xb, wh modes 43. Slower -for routtimedia [4% Faster for _moultimediq 4 clata clata. a” Ee. A module is _fmposrtec! using the Toport Jeajwoord fe Fe __ 6s | syatiae See ee ee eee ee ee rot moclule_name imple : [Osages oF elles Sag * |Teopont Specific Fu form module name import function Lb Example : Ce fom ma th import sqrt peont -Csqrt-Cie)) SS KK Grecttion of Your oui peette La 5 le can _cneate out own module ile by saving Python Teode jo 0 -Py = __Skep +t Greate a Mtoglule File Geate a file named [Link] def greet (name): return “Hello” + name Step 2 +) Use the Module fn Another Program _ | import mymodule print (nymodule. gneet (Ravi")) IT y a Output « ~ "Hello Ravi P Q ur Hie make 8 they pa roared using the imparts A chaiemet 10 1 ograms modu! (23 Develop Joklites. p npt-fo ¥ wrth -funct of ons Sr Bilt FER Tite 35 | Amport using fom [Link] Repo metige, 409 _name by} Ble name Lpmogrampy Hom uct lites “ienport squane, pts Beas factorial, hum = S$ .. ~ far Ctactomalz, factonat trary} 4S port using From module name tropow t * L J File names deeper Program 3. p ll. roo whites tmport * war = S— 7 pes ot -Csquane =") squane(num)) pint: Cube ="5 cube Coum)) int (Factvial =", factorial Gum) ss ublities. py is a_user—cefned medule ewontaaing functions? + Squane(l Finds squone of a number | + Gabe) —s Finds tube of a aumber * faconal() —3 Finds factor’ a ee | Free e fonpor vaniants 75 Pythoo, | tmpor4 module_name . ee Briiste srodlile ts tewpotted ancl Banc Using “module na. Mey Reis function _ Name : ah directly Sane Called 13S | Explaio cthe use of random and. «hme module. iia ds io. python . Develop ou prmgram that. sirnulales «a Wks isfeplasi ch, Mas secarle Amodonaches tice ~_sals cand caleuloles the average elapsed time at Use of xandom aad tine modules jn Python, 4S Random Moclule Ls he random -module «és used -to generate random fumbers in _pythoo. Ls | Uses: (+ Generates random iotegens is Select tanclom values (* Generate “xanclom Floating aumbers. Ls | Syatax: import rancor |} Example: | ienpost random x =wandom. vanctint Cy 10) ponkeo > Hene, vandin$ (iste) genesates a random number blw 4 aad to. # | Program +o Simulate Pythoo | impoxt raodom Limpost tine “4 Aotal-tme =o —_ Hn {to ange) eat rial TH) ube Scent =tmetoe ole lay = random, xandint G5 PIS a, ¥ tin e-sleep :Clelay) end = time .HimeC) elapsed = end ~ stot freot C Elapsed Time =", elapsed) total-me = folal-me ¥ elapsed (Average = +total_time |s Jrint- Average Elapsecl Time =”, average) 3b [ToherHtance : Ly Ta bevitanc she trrocess_ of dsyivic, from_an existing ela jects. Syatax b class -ChildClass CPanent Cla } _ Pass _ 1S [5 camp ly it class Animal : acti de? sound Geltye Ye Eae oe i fl peiatCAoimal makes sound") ; =H powm ote 35) $ jong, [class age Grimal): _| pass telus BegC) [[Link]) i AE falymar phir Ll hopes means -many forms “The -scme Function | =. jor opescrlos behaves : diffnently to -diffenent 2 Isthsactions. | — Se i Example : it Class “Ai: a def -disphy (self): a peiot (Class A") | class B(A): | ; def display elf): | ~. prot (Class B") a obj = BC) i bj. display ¢) | ttt a so sh ] Encapsulation a FS, e cess 2 combining ol cere “and methods fatto a ee unit called | a elass, a Xn SO EPs - al Zo l~ : sbiodiod data Lod ~ * class Student in sath die tot a sragl unit — is*= = Siecle C* Ramm" DE —_pwint G. aise # Advortages of Oof th. .Gode + ability eh Easy maintenance 3S Decta. “Sewrity 4} 1 Beh program sty 5) Recluces cocle reclundaney, tune ph _________ A Program -to illustrrke shy, excepts else, and finally try? > z — a= tot G@oput ‘Céntor first number < ")) (b =tot Go put CEater second umber +)")) result = a/b mint (Result =”) result) except LeroDivisionEwrvt: prot C Cannot divide by fers) exccept Valus Eso : __poiot C'Invaliel foput s ‘else * prank @ division successful *) | Program cusing Cla € Bank Acoust «class \ Bank Acceount : def init_ elf; balance): _self, balance balance # Pune Funchon. |e def gettalance Gelf):., eke -self. balance. eo FH Wodifiee Function a def -depositf'self amount): self. balance =self. balance + amount acc = Bank Account (ooo) prot -CIoital Balance =") dcget—balance()) acc. deposit(S00) pot C'Balance after Deposit =") [Link]—balance( ) TK [odie : Anitial Balance = 1000 Balane after Deposit =15v0 4 EE priat-CAfies gmat Cr - pix » pl.y) peat (op? =". pia, pry) fSameoess using ‘is’ Opealoy anc Effed of Mata bili: a 4 te Guan Tey: fo WV eieos ‘is Sad to check 4 ive vaniable_sefer tothe same object in menior Lal Tf both nefer to the “same. is it ochvans True. [FTG I natebitity means the objects canbe _amocli fedl 2 affex L cneation. I-f wo ce poiot fo the same mutable object, changes made trough -one aefeance - will affect the other. a Beplanation : 4. | Poiot class is coreated with attr butes x & ye 2. | p2=pt means bath srefeacoces. poiot to the same object- ce 3.| is_opevatow checks “sameness : iE pi _’s po ies Tt returns Tre because both arfes te the Same [object 18], Tusteccte +4 ! a)cla I ne aie 2 Ly |} Acclass -is.a blueprint ov template for Creating 6 a8 - Tt wetains dato members and members function Telos ClassName: ae EE bal oP toss” 2 Tb | Bample: Wi zee lpald geal class Student: Name ="Ram ' aie re pont Csnucentnamey = @ |b\ Sb object Ls Ao object -?s_an instance -of a class. T+ is -used +o access the mem bers -of a class. a Ly | Example : | class Student : name = “Ram” isis Student) Hene st fs anrebject pedo Cot. oame) class Stuclent. , AN |LRinct overtloa } b&b jfuoction overloading mean defining. multiple with the same name -bus diffener| panamnele “ g disecty', but 1 tt can_be achieved _usiog default ongum ents. y l Pe Bric le Sic i - “4 —Helass Demos “+ ssi — pees E def adetGelf¥iaib, c=0): were a+b +c 2 b Python does act Suppert -function overloadin d = Demol) © pat de add (toes) ee _psat Cl. add (lo, 20, 30)) Hene, the same function add() works wrth diffenent lnumber of. arguments. words $1. close) words. sort) saben (Sorted words oes (for word io words? a peat (word) seg i words. sort) [____ [#2sepenCo =open Coutpus-bet" “w ) yo x - [___Hfon_ word P Z fo word fo. write Coord 4 a vwrite(word +"\o") Fa qj / —_loutfile- close) = besos €U) 3 age ‘oop prot: (sorted words wntten tate utpuk tt ‘y (File conteats sosted sucessfully & coved to 24?) ynint

You might also like