Python important question
Python important question
P. No:
Assignment .4. (Dale:
P. No:
Dercribe wes defined funion în python
A functioD fs a block of ede-
2EM9 ble code oich cgn be
called wheneve aequirtd Funchionu in pthon ane se|f
Contained bBaeks pregram hat gerfobrms some pariculaz
task
A user defined function s block of causa ble code.
Gettd by uets acording to their Tequrcments lahith
Can be Called aheneue Al¡uirtd
- The main puzpose of usex defined function îs to
Lachieue ndulgaty and pnahle tLuSahilty ck code
- Steps to cCrate use definesl funstion
) Functian defintion :
Function definition is a hlock here 4he stutemgnts
insi de the function bods qe writttn
We se clef keoord to deine a function
The arqunenis ubich ae rtten in functondefnitton
qe KnOn formalaguments
Syntacei
def funion name pazameteas):
Sbk of statcmendts
zekmTxpruion]
2) Functhion Cailing
lhe def stotementt only cacattes afuntion bt does oot cl
e ue foilouiihg syotox to (all that funtion
furction name CAtgumerts) i
Dalo:
Dato:
(P. No: P. No:
def sub a, b):
-Nhen Calling funcion îs execttd hen prngram antolley
This funstion Atbiet Sutast ts humhas ond
gaes to funcion defintien.
Kctum thu CAut
Aftc ucesskully Kuuion cf body progYam Contolles,
ceme hauk to end ef a aling fvndion.
The arqumenh ahich e paales hoye the calloa
def muw Cg,b)
This fupction multiply tan nunbet) 4 arkn thaze"
Khdules arc pinanily the fy fileubich contain python
pnqrammig ecde deininn Anciand, Claes ntobe cte
Mort cfthe time, wie need to use existing code ahik def diy(a,b) :
This fupcton dinde t 0 numbes and oRtim he t
cdeutlaping pxojets. eCan do th wuing macdulea in pgthon
-Module heler o gchieue featuze an pthen.
) arate firt fie a python progam aith extian ertcnsitn -p
-Teapact the deiaiticy nside a mgdule
import P1
2) rtate second file în the Sarne direstry which acel pint ("dditibn " Piadd (1o2o))
meule wing inport tott nentTmgart stutenent taa print " Substaction =",Suh C1o,2o))
pint(" Mutipliation =", P1. Imw 10 20))
pint ("div jsion " P1:div (1o, 20))
fr Crating a module Iyee tha follecing <ode and
save t aJ pi-py
Arite dferent typs of qr¡unnent n 4 tunHen
olef add Cab)
Jhis funcion addc tun numbea3 qnd ttunT thu u orguneott on cahich thy iil cpeaate
retuan raut aamatee
0rgs voriabeleng h ngs.
C Requs rcd an:, eyuond ags defautt
Date:
|P. No: Dale:
(P. No:
DRequied Arguneads /positional
Azquments
Rcqui d ququneats art he axqumnh rassedtoa kotion 4) Votiablc length ArqumentS:
numberof araumnts ih funchon a sboule with mare hun be
The
with amion dehnctoo pararaetres the funton definfion
Eonpk
def Addhon Ca, b) Agunet.
ue an deoe 10iab le engath orqumehts wng ymtol
print(Addition oE to numbezs -"c); - Eagmple.
Adcainn (10,20)
clef diplay (Im):
print ("Value of m);:
2Keord Arqumerts disphy oo,980,300LO0,SOO, Goo, 10D, 80e, gct)
-keaad faqumehà at Te lated tn knction calla.
Calee. identfia the agumenh b the qaramedte. Tame 41 State the use ot goba teuood with stmple eramp le.
def display Chame, age]: \ariahlea n o proqxam may nt he aceatihle ct all locrtigm
Piot ("Name ome) in tbat progam
point ("Ag,age) Global vaiab le an be atceJsed throug h0at the pogram
Tetum - We can aces qloba) VriableA overyacore in he prgam
- Global voriables are deckETd Qutside the al{ funiong.
3 Dejault trqumernts:
| A default asgument is an aqument ttat aumeA o deta
alue if lee ig hot povided in the funchon coll a l00
-Exatple def dlsplay()
def diselay Chane ags =23): b:200 :
prìnt ("student Name "name)
print "student Âgg. :"age) prit(" Grlobat yoàbe"a);
(: Govind") lisplay ()i
Dato:
|P. No: Dote:
P. No:
eal ond alabal variable. xplcHO the Follooin packages th Suttapk erample.
tphin all tho
Yorahic îo a cargm mau not ke qccettlble at
hae dcckarcd a N2iahe Nampyis the fudamerta) terttre-ackaqs fos sientfic
- Store afa yaioble cletunipes the poricn Of the pzngorn Cmputing oith pythnn oth ggthnn: Noy standt for
(chere uu can aelfa paorticual H21ah |Tdentife:. humexialputhan. t prDvidea high perfocnane muti
dibaein sianal Qray ahiet and toos for working uth
U local Vaziahle : these obers.
local ugriabks can be aceared ony i9ste the fuoston - Numpy om isa coljertion af Simir ypes of datn Nump
in which they ar dekaseo
A Global vaxiablesi change Latek
Giobal Waiahles_ Can e acesed ony inide the function Exeuske followlng comnanda ofntall nuraey nuodouA bn
in wbich they a deLheed
eythonm pip întal! num
Tn sumpy lmenaions aat Called
Define package 3 Hatk the steps to Corat a faukage io
pyth on.
-Package is n ellkction st nodu<e4 and sub packageA Dshape - Speiics the boof olnent for coLh dimeaion f tho
- Thig her to auhicUe GCasably in pthon.
-A paskage is o hiearchical fls cdciogy stauckurt tha sie - toal numez nf elemens in h ar ays
defire e single. python applicoticn enYDOnent that s) ndim - etseminea the cimersigny of cty
Coosist cf ooduleA gnd suepackgqeA and so oh
following are the strps tn Ce gte packagea
S Fist x hove tn crate drcctoy and gie package game.
>Sood, need to cRate modulea ptt A indde the pakcge -EXanple :
dizctony Tmport hum
U23], t4,5,6J1) :
3> -Fiallyy e hae to cacate empt, puthan le nomea
initp F)e Thi l ill he ploeÀ ngide t priht CAxay Element ;"a):
package direcyhis uill 4et Athan khoe +that the print No.gf dimeosion : ",a-ndim)i
AcceJ he packagepackyt
in ancthe file print "Shape of aray "Q-shape)
y og ibnport stotemer
(Dato:
P. No Drte:
P. No:
prm(" Size et Anas "gsîze iii) natplotlib
"adtype:
-pritt(Dota Tupe cf amay ese rsent - Matplcthb packagp Is ued for 2 graps n pthen
prograring darguge
i) szipy SeReI and ctheds gqAphical Kea inttzfaLe tod kits
-Supy s a libray tbat uei Nunpy toi ore mathematicol
Thers ar orious prt hich an be ctrd uiag gtan.
funche matplotlis t like bax qraph bhitogram,sKater plat
StructuroOnd
SiR ue rumpy arau a the basic data AC plot pie plt:
cmey aith modules for vanoua Commorly used tasks tn Fallowing Conrond exeute to înctall nmtpist in indous.
sirntikc progzammirgnuding linear algrbxo intcq xGten
ordinany difftertial equation solving sigoal Lpnaig pthen -m eip install matplct lih
- ide ue bebw statzmcnt foy intallatien of sciey ps ckoap txamole #foy line ploB
pthon -m.pip inta)l sipy fam otplct ipart pyeht
Sipy pa kauge is zganizd Is suhpackaaes cenvetng
diftszent sierific domains. Thexc at sumtoaized belou y: Le,s2, 21
Dclurtee -clustring algorrthN Ppotplet( y
)anstants - ghyskal ¢ mathe tnatical constqnts yplot how ();
3) pack - Fagt fouie Taunsform algszithny retinea. # foz bor qraph
X=2,410J
3 dy odhngonal distane Rresion. Y2,8,8,2) :
) signal - signal pitáelsog pyplot -xlabel X- pis;
SpaSe - spase mgtk 4ato igttd goutineg yplot ylabel CY- azis);
S) nditnxge-N-dimeosisngl imoge proceflng
9) Seatial spatal deta stutura gclgaimu
to) 0 - Rad data fam tante cata 40 ile.
Examo le
iv)gandas
Pandas is an open soue, pthan lihany penveing high
frem scily imga Koalq perforbaane data manipaJation qnd ahalysi< tools aaing 5
pouefl datastuctefe
pan+(iba lg Íny Ca))i#find invene cf co #is buitH on the Nucogy gakage ond ih kay data Stt
Print Cinglg. det (a)) ;# fine deteeminart t om iS calld o dato trame. Datarome alloS tn 3tere ¢
Danipclate data in tabtulae fonnot.
( Date:
[P. No: (Date:
P. No:
panda.
Folloaihg statcoot e we for intalatn of
>»otft nath.rt (14)
Pythan -m pip jnta) pardas 12-0
" Nane [" Govind""Arun "karnn" EX2
dict
"Salory [r2000, 13000, 14000, iS0001
MGoneah
df pd. DataFrane. Gict):
pint Cdf):
-3.074 93 232 oc3g35 9ts.71 s49697423 25))
1.s00o00t o000000 2+ 1(390go J3 Zs6 39S)
S] Fxplain pthan buit h ntdule >2> SqtC)
ZDNumeric and matbemaical Modules
C+ss3739 740 00374to 643592s2 oss 326i)
omah ard Cmath odules
pyton provides tun mathematica mocules ngme ly math and. Randonm Module
Cnatth The ngth madule sues ul auenS to hypee balic - Sometiss, we ant tte Compute ta pldk a ogiom numes
jn a giveh range pick a random elsment from 1at ets.
-The tandom module paoutdes Runcions to perkrn thAe tyes
or Compkx numke.
Rneed to meort andommadude. 6 thon e hacod to
>» impot math all th
simpct andnn;
>>> mathfloe 1:001) print rQndon. ondom) # 9enercHes 00trom 00,t-9)
1 printrondam. ran dint(1020))# nerute Instge iD(o,20)
» siaGe mathsinl9o)
0-89299 6G63C O0 sS73
>>> mqth -exe(s)
4.<3I S9L02545-6 76S
>> math. log(16)
Date:
(P. No: (Date:
P. No:
statistis Module Puthon itetools Cucle.)function tate thnugh qsquene.
to ciifzer Statet
Sta stics nodele pide acrers qpto fnfine qhis onKs urt like 4 calar hted
ntians. Exampe incude mean medianmDde inkea list
Skndad deuiahon
Exampk: from tetons îmeott *
>) import Gtatteg statihics for Htm in qcle CrCt',eyth.en fava'])3
statisa meanC 2, 6,6,91) aeL age Index = Index!
5.5 if index =e 10
staistics bmedianC,2,3,SA) # chtta) yalu. break
Print(tem)
>) staistks . no de (C2,S, 3,2,8, 994 125,c]) #pote
functools Modue
>> impot statistics -gthan functoalc module pouide, atais soals sahich
stqtistia. stdev C113,225, 3,3-S,4, 4S,s1) allows and PnCorages Q taaite geusable ode
1.3<3306I937629 153 python functools partial ) functinns Qre sed to rplisats.
exlcting Runctinná with ejrme qrgumen altody pased in
i Funchianal Progranming modules = doccmened manme
Suppase e have a fnstign alled oaltipleT which a
O tertools Modle sautHalfcA tn numbez. zk deinihoa tagts like.
ython pngzamoing iteetonl module prode us naritu cdej mutiplice (xy)
travszsingt - Naw 4aht th mmake. sorne desicatcd functlT ta daubk
gtan tuteol chaac) füncten fast accepts matpie. r trile a hunbes, tho Le Al have to defne
funetion a
def vaut¡lieezy)
fam Hetcols imnrt* Ytum yty
for yalue in choin (i-s 2.51,3 2],C'H Pythcna def docbe+ ()
print (valuel Yetum maltiplies.(x2)
def tipel+ (x):
re tun mutti pliee (K)
Date
P. No: Assignment 5 Date: 1Ap
P. No
f t funN ctocke impt rtial)
Defineclass Hou to crate c s and its ehjcts in pthon
det tip lice (x.Ji >-A class s blueprint fer cRating_ objects ond chit
S nstance cf closs
We an meate multipk chices Þen o closs
-Alas ondajns cata ghd funsticn hat anigukt he ota
tef -A Ett slass can havc manga, aplebanana shicct
deub'e = Aartial ultiptict,y es)
ne þartial(hçlice, ys) -ratng claus syntX :
rint ('dauhle. ef2 is i ' fümat(deuhle (s)))
# itt of class variabs)
H# it ot cas onctctoOr
Spesat Nedue #phonclass metthas definitions
-Tb opceateY Moduk sUgalicg fuhcing hat are
hands in ases ashege callaheg must he stoaed or chcctName a ClacName()
Astate the use of 'se paxamete9, in pthan cles
add Cab) 2Tn Arthan ,Self Ae conentionalls utol paamotc2, in.
instance nethads ot a deas. 2eprUtnh the inctante
diuCab) of the clasr o Qllbos acceAr to intante ctribrtea and
Anethads q+ must be first paranete, in Intante mehads
Omocla,b)
1. Accessing Intahce Yariablex
nsht CGb) -helpr to ctore and aetâre, inctance. spelic daa
(Dato:
(P. No: (Date:
P. No
clas Sstudent
totCselfname age) print CCc nade)
def.
Slf name home #indne vorhb lot c change_model ("mN")
print (" ame 4.DifeArtiating Petlacen (las g instante huiobloi
- Aithut sellnstaxe Narables ould hehove
Sl- Studant (" Goiad 90)
like local aroeables
-ey
clats Tst
2. Acesib Instathe Methode deÆ intCselE, value):
-sCE k eaitd to call othe nstane methocs. GeIf value : Value
def shot selF):
clas Eample '
print (" local 3" value)
print ("This Jr methoda ") pnnt ("Thstahte : self value)
Je|fmethod 2 () nbË= Test (30)
deF method selE ): o . shew )
print (1his is methocde )
obË = xample) Disfezente hetween method aueslooeking method
obimzttod 1 O
greesiaing
3 ModlEying Instahte. Attribute
self allOus moditicoton of instance Vaxlables
class Car
def.initCaEmode:
seIf.model = model
det charnge mode) Cself ne) model:
Self.model new_mdel
(Dato: Date:
(P. No:
(P. No:
Method Overniding FA dass an define a special methad called q dehuctor
Methocd Oyerleading
"uth the help at -del-0 I i Iróked automaically
ahen the. inctance Cobicut) is ahout to be dextoye
Defining mutipls. mettods Redeining a nehod pa T+ is mostely ued to clean up any non meno
child dats that Lalrady cait TeÁOUeTCA eel an qnstane Cohct)
ciAeeht parasnetA in the in tte pantnt clop -Exonple
class student
Sonme cla
defjnit(sele) :
No cf Hqppens h the sone clas Happenç h tuuo claie prin+ (ngn Pasomettaized (ohstuctorr)
defdele (selF):
clane
pobt ('Destructorcälled, sudent deletkd.
SI student )
Raratacta Methsds lhavc diBeaent Dnk»g he method cighstne enaine
the sane 2-studerd()
del s1
pgthon dneA bot aipport
nethad oueabading direaHuihg hhsitznce. S Describe data hiding
-Data hiaing ls a softuar deuclop.ment techoique
speifically used n Chict -Orientca pagramning to.
htde îotksnal obit details Caata membes).
Ex, - Data hidíng nSuTs exduoive dcta aceÁf to clas
# rdefind in child das nembez
and pacterta ohjet Jntzgalay by
-prNCnking undnithdsd or initodedchanga
data hiding fo alko known as Intornatígn hiding
41Explodn diructor hpython dn sbËets Htibuta may or moy not ke v0slble
-4 Constuctor (sa spaclal imethacd that is ued to Ouside the clos deEfaition.
fn4iallze the atane VarabJe of a coa -Je need to name cttibudes wth a dubl undesore
pAx ,ahd thase atributty thn o nt be
dletly uiible th Cutidegs .day satriabe pzchxuith.
-) ccd privats cei ahe hich i as(Esib
onk uth class whee tt is declaetd.
Date:
Deto:
(P. No:
P. No:
-Eampe
slar ounsics clas student
--Se(retCeunt = 0 # privarievaria ble. detft (selE, name):
def count(self) # Public rmethod
stfoutsecretOunt +1
pint ("This is partinsteziztd constauctor ")
Pint (" count"self"-srtount)
#ottesing n heJame çlasS. priat(Hello" sef natae )
C1. count ) # invoke methecd 61-shoe)
. couht()
Print (" Total (ourt", 1.-Se*t lourt)
#(anot qcets priat vriable diaty. tt a pacarom to demanstzate
default agument
clocs Stucent:
61 Egoin ConburtON funcien In puthoh Clag Lith exXample. def initCself):
’-A conctzuctrz sspeaial membek funciion that is ucal gint C"This is non gazarnetized conctzuctor")
|to Inialize tht instance wenable of a class. def shalCself,narne):
-gytbaa cass Coastrustcx Bs the -fhst piec ot (ede print CHetLgL ",hane)
5|- Studert (1
st shoo Giovind Kanpude")
tak i to Initiaize to the datasrneBn ben of the
Class shen an obec+ fs (rtaicd. Qutp1t
(onstnuctos can be idefau consustÖS ane earamt This is on pazanetized constructoz
ZedonstutoK Hallotn Ggovind kanpude.
clos Studert !
prirt (" This îs noA Rgcamett sZed Explaio nherttane în putth on with example.
Canstuio- ") The proress of Crrating neo clos hy urlag te coDET
det shaw(selfnamg)
print( Heljo " nama )
61.Shdet shy C"Gkn)
Dato:
Date:
(P. No:
(P. No:
tha mohettu
Th Taherftgnceobfect of one clas procure
OAjccts of anothr cloas CTeate a clas employee withdata mernteas
Thbrtteoc provideode zcSobillty name departnent and salayCras cwtable ne thods
closseA
he techorism c dertving cloca foam bu old tu radingyaniting cmelayee hfomehan.
chld C¦assncy clatr
The heu closs clleo dezived dasS def init CselEhame depatMPNT Salay)
Ondt old clot fom_hich this clJ i Cotatcd is Selfnanas name
allcd base clas, parcnt claA and old class. slIF depadmert depaatoent
I, inheTitahue the Childclalf acquits tht piopeatie
and can acet al the cata membeza4 funciont ok
parent clas chld ckas an ap provide ts prict (MEnployee sName. "ssIf nae )
Spuific împlttocntation to the Eunctioht of hs Raztnt priint (" bepartment ;"skd<parthent)
Cass. pind "Salay safalaz
def updte infn CselEhame Non. cepasttnecd - Nene
clos A salany =None):
s## propesties of class A
self nome harne
# clars B foberitiog propeties af clas A if depotnert
# TnOTC properties of clas g
- Exarmple sLE salt salay
clas Vehille prinà ("Erngayeo hiomahion ufdata ucerkaly ")
home "Karu
def dspay CsclE )2
pnnt C"Nane ", seif name) emp dsplayy tata()
class Catcgag CVchicle)
price =200 enp displas inia ()
cef dsp-price Csel)
carl.dísplay ()
qot. disP- Prie co
Date:
(P. No: Date:
(P. No:
Hso to oete abchoct methsd fh python Exploin class Progaamnez CZmloyee):
def SanrkK Csel£)
-An gbteat mehod sa method that is delord t ctum scIF-n gme,"i aiting code . )
class but doca not contazh any topkmedotion
base
Subtlasce murt ímpenert AbiTratt thethnde cla rManags CSnpiaye)
def tenzk Cself)
ensure hot subclaster provlde speciir functioro lH aekum selea bame, s managing the tran ")
in gton, abstaction metthods Qre defined uiho he
ABC module. me rNanogeRamezh" g0000
- Steps print (m LOMkC))
1. Tmport AC gnd gbtactmcthcd fom abc module.
2. Crate abose clou that tbheit from ARC.
| hlrie o short not an method oversidng n puthon.
deuontor. Rdefining a method h a chid clact that altads
4. Cotte subcaurea that ihhert om he lsae closs
On d mplchncndet the abstratmethod Methad cvexriding aa featue ot nhertaare aswhteh
q subclass panide a cpelff fapementaom oEa
Gom abc import ABL abtzacnethod hcthad hat is abtady detined fn cts pa¡tnd clast.
clas! Enlayee (ARC ) the method in the <ubclas xeplaces th patntk
def inttCselE natne ,salay ) method.
SUpck.C) can be used to call the oMerzriden methed.
for fono tte poeeAt class.
Qahsthactrnctho Ex class Animal:
def work(sæE): def speakCelt)
Abstrat nethad that nut te imeleme ated 2EhLEn Same. couund"
Pas
clar DogCAninaal)
def speak (ssli):
prt (d- speqk o)
|Date:
P. No: Assignment 6 Date:
P. No:
Iit four fik modttes in python
iriopas fik Jn radig oly mode. The flie paintea
ia
i plaed ot the begirning. cf e le
dofautt ode
fi Cpens a fie for bth aeoading ond cgeina The.
file poirdx is placed.at the. kaginaing of be file.
i. : Qphs n fie fox oitibg omly_. Overrites the fl
i the fle, extsts the le doc nct exlts
a nug Ale for 2mding and caritn
V. Q Opens a file for apperding The fie pointu kat
antey a ne ie for aritin
Cpens a Etile for bxth appmatng ani zoding
ading amd inting
(Date:
P No: Date
P. No:
cseOmethodS
plain OND () and a ttt theuc of ty jinally block ith yntax
opn) Mhod A exKcption can evcnt which ocCrt cluing the crtudion
lof a progzam that dtrusbs the nasnai flovo of the
The opcnc) pmetbed arod to opcn a fleIn diffcrcot mole Prgrank nstuctions
-Syntax Extephien handlig îaa prnceas thbat pmuidey awsy to hanella
ile objcct penfle nanemode QxCertionA that acuk. at untime
fihe bame f the bane af fle witb ath it breded mde ty-xcegt hlack4
Spafi haw the fie should be opened ACriticalopexation ahich can aale erception s plaueol
Soside te ty clawe Qnd the (ode finat hacsla
Eample pxteption i5 aten fn exrept clawa.
file ORen "praople ++""") Sutax
tay
# Code that may saic an szKpion
# Handle the enepion
dore ). Methoc
The closec) bethod i tuec to coe the Opencd Cilet
eseotial 4to rleoje ytem rourreA ehsce data irteqrity eXCept coobihsi on baor
file obfeut , close c
Example.
Condtns e. mad )
Point cccntet)
Date:
P. No: Date:
P. Ro:
Exampk
y=xçpt - clse block
-CXEpt cloute coth no eaeption
Centat file -xad.()
starttmeat Ahaly
print-(nfile daucal suctelsfilly
# odc that mou rae an exception.
#handlcA the excehion 1 i e the syhtay of follaufny Anrtiong quith pxonle.
Eample - print) funchicn is usecl to prtt output
atpst SSICCh
messaes on
This is piedehedl function o python anguage
syntax
eKept 2eoDivicisnEny prdnt ( phects sep :"ehd ^\n"fle S-stiat,
Auch Fale)
- Fxampl
print(* Hello eorld ")
y-fnally kiock
|Ty staknent fn pthon can aue an ogtiono finally douae input ) fnction s Used to take fhput fom uSe througb
Usel to keyboazd.
-This k prtdeined kunctinn of pthn anguags
Syhtax
Suta
ampe
#Ccde hat aill alinyg exeutte bÙ Sot (ihput{ hte, q nunbee : )
xonple - radline()
4)
Syatax :the flecloEe) print ExampleSyntay! ho+ Tais
Eomple
£lle : Sybtax
print(conteot)
cthed
rtad -
tadine()filk openC"ekamplktxt") adCo)fileChoacteefCm fle yau This
ntent. ("Eirst
Lne: medhad
rqd
bae
() file
exanple
ite. tM more
ssticd
ototankuc
wrifile.te 1f nct
ito
we
hot, "ne )
ads
spcificd
an
(" c" a thbe
Im (hing)
onfne sinole
Helow, Camplcle
ad
ctatea n
thù, Ioe value
s q faconthe
conttots
Govind neul
file:i No:P,
\n") ile of (Date:
T
chel
P
oate.
No
- 4)readling ()
Syotax: - -This
xampiefilk the
Waites_ Syntax : hot Thiprlnt(conteot) Sample file . Chara you
Sybtax
file()priot Linc1 Exampe
-close i-2tadline
le fie ) s
file.clo)e ) Contcot 4lle TRadCn)
(nHent. :OpenVeomple
data ("First :cpern : rgd
mcthed you be
mthpd
a tes
e() file
fite. flk. fi spificd
("oxample moe k nctspified
If to ncads fom Tad
te
"exanple
"H")tt"
file. hot, a ine:redine than
tqd)
ite wite fle "ne atyd) nlue the
Cr(" a fle
)tt" 'onsngle
of
Camplek
Tm Gtbjng
Hellctw, If
otateyq thu ) "y) line o n
sad ) line itvalue.
)this ile
is frcmtbe wil cootofu
cxlsts.
Govind nElw xtamig
file [t
\n") fik o Dale:
No: P.
ove
tLmt te
ft fik_if
alocA
Strphin
Example Lopezdireeiog
XeDama Rython
pint4 Tenove
9. osYEnOYs05.("
{oport EbutOseome c imgart ojReraming
Ezarnplc
print import . afile. 0
otion
th
the "( and provides wth
'ik Ak
ile fik ("old_ile af eaample
("qnwonted
.tt) toamed delste
teleted
coe HknamLoith
estxion) eist cniles the
os
hot filea hoD
Jucearuly sucufuly"
renamihg
bforeik. and gnd
t cg to
eiutsthin qircosej.
"ng diru Jhuil Tehgme
torieA.
file.tt)
odules or
erm
Deos delete
to No
|PDato
wil peform {le
occut heus
cT
e
tan
(Date:
|Dsta:
(P. No: [P. No
Sxcegtion handling mechanin depunds on bio) ttops
Ranalng Netuny )find the exeept on
2) thow the exeption
) (atththe crcephion
4) handle the excepion
impot
n Athate ("odfoldee hu) faldeA") -keyunch wsd in oxceptien Aandlliag
pint ("Dbattarg Anamed sutcetfeuly:).
oleine4 a block (ocde athese exeptibng maht cua
2) exapt
Haudlea te Qutepticn aicd fn the ty batk
3) dre.
DS mdir("dirnam")
}xormp 4)fioaly
Raic yntaa ef ixepiion faodling
’-An exeptinni on eun hich cxcurs duaiFqthe excutian
# (ode ttat oy Nai oneterion
ercept FxePHonlhpe:
-Exceptisn hondllng ft hangle the exepio
to bande exceptiena thnt sccur t uNimt handle-eepion O
# ExteutiEmeor()
# code that al0 erRutes
ckanup (de ()
21
Ne
def finalu i
else:.
Chetk g srerkull2
print print(^
Divigicn a
check Valu&
volue(value) proqznm it
Pint ralse
= ("
olse
int
valueyaucfaoy
C fxeutton OputEnk
Cnum:
inpt pytthon a
is
("Enteu valid "ror cmptd)
which numcrator
", :
qnumbes num)
telvalue wil
:))
troug
|No:P. Date:
lesr RCeptinn
than
2er0 if
-sntax B) -
9Explain
Iic lAle. .close)
Lle
file Leile he
print Example"fllenane:
'
Cpenednode; file furtion,
cpen C)
wre
eitin g
("Dta zite oh ërite ("Ale open s
(" înto such fallowing
(uHellow, Text )
ozten examle. function e apmed eeHes Name
Cnfilenams
to file ai
wtte read the of
sutessfuly thìs
")
using ucAfuy
allo ttafig le
")ls zt Cr), mode ",
g caite "nede") lattd r
tet A "2 rite fn to
th () sblkh be opeaation
filk.") function
s0ite
()apgRnd
optsd.
te
data
in.dÍ
(a), neion (Date:
No: P.
ete
Q fle
Hle is
tho
fom
P.No:
Date:
lihe
single
a
yeads
)rndline
finction lÁne
line:"
Reading
UsingThe
tedlac
)
("Read
file
doe
C)
iExa
mple
Syrtay
print