0% found this document useful (0 votes)
2 views

Python Notes

Uploaded by

Milan Samantaray
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Python Notes

Uploaded by

Milan Samantaray
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 384

Hi

stor
yofPy
thon

=>ThePythonprogr
ammingLanguagefoundationstonehaslaidintheyear1980
=>ThePythonprogr
ammingLanguagedevelopmentst art
edintheyear1989
=>ThePy t
honprogrammingLanguageoff
ici
allyr
eleasedintheyear1991Feb
=>ThePy t
honprogrammingLanguageDevelopedby" Gui
doVanRossum"
=>ThePy t
honprogrammingLanguagedevel
opedCWIi nNetherl
ands.
=>ThePythonprogr
ammingLanguagemaintainedbynon- commer i
calOrgani
zat
ion
PythonSoft
wareFoundat
ion(PSF)
.

Versi
onsofPy thon
=>Pyt
honPr ogrammi ngCont ai
ns3Ty pesofVersions.
a)Python1.x
b)Python2.x,here xr epresents01234567
c)Python3.xherexr epr
esents012345678910 11 12
=>Pyt
hon3. xdoesnotcont ainbackwar dCompatabil
it
ywi
thPyt
hon2.
x
DownloadingProcessofPy thon
Wecandownl oadt hepythonsof t
war efrom www.pyt
hon.
org

Py
thonPr
ogr
ammi
ngI
nspi
redFr
om

=>Functi
onalProgr
ammi ngFrom C
=>ObjectOri
entedProgrammi ngFrom CPP
=>Modularpr
ogrammi ngf r
om Modulo3
=>Scr
ipti
ngProgrammi ngfrom PERL

Real
TimeAppl
i
cat
ionsdev
elopedbyusi
ngPYTHON

=Py
thonPr
ogr
ammi
ngcanbei
n23di
ff
erentar
ea/appl
i
cat
ions.

1)WebAppli
cati
onDev el
opment(Dj
ango,
fl
ask,
pyr
amid.
..
etc)
2)GamingAppli
cati
ondevel
opment
3)Art
if
ici
alI
ntel
igence(Machi
nel
ear
ningandDeepLear
ning
Appl
i
cat
ions)
4)DesktopGUIAppl i
cat
ions.
5)ImagePr ocessingBasedAppl ications
6)TextprocessingBasedAppl i
cations.
7)BusinessBasedAppl icati
ons
8)EducationSect or
9)AudioandVi deobasedAppl i
cations
10)WebScr apping/Har v esti
ngAppl icati
on
11)DataVi sual
ization.
12)Sci
ent i
ficandNumer icalApplications
13)Softwar edevelopment
14)OperatingSy stem dev el
opment
15)CADandCAM basedAppl i
cations
16)EmbeddedSy stem
17)ConsoleBasedAppl icat
ions.
18)Comput erVi
sion.
19)Languagedev elopment.
20)Automat i
oni
nt esti
ng
21)DataAnalysi
sandDat aAnalayat
ics
22)Devel
opmentofI OT
23)Enter
pri
seAppl icat
ions

Feat
uresofPy
thon

=>Feat uresofal anguagear enothi


ngbutSer vi
ces/Facil
iti
esProvi
dedbyLanguage
Dev eloper sandt hosef eat
uresusedbyreal t
imepr ogr
ammer sfordev
elopingr
eal
ti
meappl icati
ons.
=>Py t honPr ogrammi ngPr ovi
des11Features.Theyare
1.Simpl e
2.Fr eewar eandOpenSour ce
3.Pl at f
ormI ndependent
4.Dy nami call
yTy ped
5.Int erpreted
6.Hi ghLev el
7.Ext ensi ble
8.Embedded
9.Bot hPr ocedural(Functi
onal)andobj
ectorientedProglang.
10.Robust( Strong)
11.Ext ensiveSuppor tsforThir
dPartyAPIS(Numpy, Pandas,Sci
py,
Sciki
t,
mat pol tl
ib..
.etc)

1.Si
mpl
e

=>Pyt honi soneoft heSIMPLEPr ogrammi ngLanguage, bcozof3i mpor


tantTech
Featur es.
1)Py thonPr ogrammi ngPr ovi
des" RICHSETOFAPI s"
.Sot hatPy t
honProgrammer
canr e-uset hepr e-defi
nedcodeanddev elopsr eal t
imeappl icat
ionscasi
lywithout
writ
ingourowncode.
--
--
--
-----
---
--
---
---
--
---
---
--
--
---
--
--
--
--
---
--
--
--
---
---
-
DefofAPI s(
Appl i
cationProgrammi ngI nterface) :
--
--
--
-----
---
--
---
---
--
---
---
--
--
---
--
--
--
--
---
--
--
--
---
---
--
=>AnAPIi sacol lecti
onofModul es.
=>AModul ei sacol l
ecti
onofFunct ions,Var iablesandCl asses.
============================================================
2)Py thonPr ogrammi ngProvidesanI n-bulitfacil
itycal
led" GarbageColl
ector",
whichi sr unningbehi ndofev erypythonpr ogr am forcollecti
ngUn- UsedMemor y
spaceandi mprov estheper f
ormanceofPy thonBasedAppl icat
ions.
DefofGar
bageCol
l
ect
or:

=>GarbageCol l
ect orisoneofBackgr oundpy t
honProgram,whichrunningbehi
ndof
everyregul
arpy thonpr ogram andwhosepur posei
st hatt
ocoll
ectUn-UsedMemory
spaceandi mprov est heperformanceofPy t
honBasedAppl i
cat
ions.
--
--
--
---
--
--
--
--
--
---
--
---
--
---
----
--
--
--
--
---
--
--
---
--
--
--
--
3)Py t
honPr ogrammi ngProv i
des"User-Fri
endl
ySyntaxes"
.SothatPython
programmercandev eloperror-
freeprogram i
nlimi
tedspanoftime.

Fr
eewar
eandOpenSour
ce

=>Fr
eewar
e:

=>SincePythonsof
twar
eisFr
eel
yDownl
oadabl
eandhencePy
thoni
soneoft
he
Freeware.

=>OpenSour
ce:

=>Thest
andardpythonnamer el
easedbyPSFtothereal
timei
scall
ed"CPYTHON".
=>SomeCompaniescamef or
wardandcustomi
zedCPYTHONf ort
heiri
n-house
tool
sdevel
opmentandt hesecustomi
zeddevel
opmentofCPYTHON arecalled
"Pyt
honDist
ri
but
ions".
=>SomeofthePythonDistri
buti
onsar
e.

1)JPython(or)Jython- -
-->I
tisusedf orr
unningJav aBasedAppl i
cati
ons.
2)I
ronPy t
hon( OR)I python---
>Iti
susedf orrunningC#.netAppli
cati
ons.
3)RubyPy t
hon- --
-->I
tisusedt or unRUBYBasedAppl i
cati
ons
4)MicroPython---
->Itisusedt odev el
opMi croControl
l
erApplicati
ons.
5)AnakondaPy thon- -
>Ituseddev elopBigDat a/HadoopBased
Appl
i
cat
ions.
6)Stackl
essPy thon---
>Concur renycy
7)PyPy--
--
>ItprovidesJI T(Just-i
nTi me)compi l
er
.
..
..
..
..
..
..
..
..
etc

I
nter
pret
ed
=>WhenweexecuteanypythonPr
ogr
am,
Int
ernal
l
ythephasest
akespl
ace.Theyar
e
a)Compil
ationPhase
b)Execut
ionPhase

a)Compi
l
ati
onPhase:

=>Thepyt
honCompi l
er,readstheSourceCode(ExampleSum.py
)Li
nebyLi
neand
Conver
tedint
oInt
ermediateCodeofPy thoncal
l
ed" By
teCode"
=>Si
ncePythonCompilerconvert
ingthesour
cecodeintoByt
eCodeLinebyLi
ne
andhenceiti
sInt
erpr
eted.

Exampl
es:
--
-Sum.
py-
--
--
>Py
thonCompi
l
er(
LinebyLi
ne)
--
--
->Sum.
pyc(
Byt
eCode)

b)ExecutionPhase:
=>ThePVM ( PythonVi r
tualMachine)r
eadsLinebyLineofByteCode(.
py c)and
convert
edi nt
oMachi neUnderstandableCodeandItisreadbyOSandProcessorand
GivesFinalResultoftheProgram
=>Sincethisexecuti
onper f
ormedbyPVM Li nebyLineandhenceIti
sInterpret
ed
Programmi ng.

Pl
atf
ormI
ndependent

=>Ifanypr
ogramminglanguagebasedapplicat
ions/ProgramsrunsoneveryOS
theniti
scall
edPlat
formIndependent.
=>Pythoni
soneoft hePl
atformIndependentLanguagebecause"
InPyt
hon
ProgrammingExecuti
onEnv i
ronmentall
Valuesarestor
edi nt
hefor
m OBJECTS"
.

=>Al
ltheObj
ectscanstor
eun-l
imi
tednumberofv
aluesandTheywi
l
lnotdepends
onanyOS.(I
ndependentf
rom OS)

Examples:
-
---
--
--
--
--
--
--
=>C,CPP ar ecomesunderPl atf
orm DependentbecauseC, CPPl angdat atypesare
keywor dsandt heirmemor yspacechangi ngfrom oneOSt oanot herOS.
=>Jav acomesunderPl atf
ormI ndependentbecauseJav alangPr e-DataTypesare
keywor dsandt heirmemor yspacer emainssameonal lTYpesOSesbutt heycan
storesingl
ev alueandunabl etost or
emul ti
plev al
ues.whereasJav aPr ogr
ammi ng
alsocontainsCl assesandObj ectsandinObj ectswecanst oreMul ti
pleValueswit
h
Limitedonly.
=>Wher ePy thonPr ogrammingLanguagei soneoft hePlatf
ormI ndependent
becausepy thonpr ogrammingst oresal
lthev aluesintheform OBJECTSwi thUN-
LIMITEDsi ze.

NOTE:
-inpy
thonv
aluesar
est
oredi
nthef
orm obj
ect
s.

Dy
nami
cal
l
yTy
ped

=>I
ncontextofPr
ogr
ammingLanguages,wehavetwotypesofProgramming
l
anguages.
1)Stat
icTypedProgrammingLanguages
2)Dynamical
lyTypedProgr
ammi ngLanguages

1)St
ati
cTy
pedPr
ogr
ammi
ngLanguages:

=>InStat
icTy
pedProgr
ammingLanguages,
Iti
smandat
oryt
ospeci
fyt
hedat
aty
pe
other
wisewegetCompil
eTi
meEr r
or

Exampl
es: C, CPP,JAVA,.
NET...
etc
I
nstr
uct
ions: i
nta,
b,
c;//Variabl
eDeclar
ati
on-
-Mandat
ory
a=10
b=20
c=a+b

a=12.
34-
--
--
--
--
--
-Er
ror
--
incompat
ibl
ety
pes

2)Dy
nami
cal
l
yTy
pedPr
ogr
ammi
ngLanguages:

=>InDynamical
lyTypedProgr
ammingLanguages,Iti
snotnecessar
ytospeci
fythe
datat
ypeforthevari
abl
esbcozPyt
honProgrammi ngEnvi
ronmentwill
aut
omatical
ly
assi
gnthedatatypedependsont
ypeval
uepr ogr
ammerassi gns.
Example:PYTHON

Inst
ructi
ons:
>>>a=10
>>>b=20
>>>c=a+b
>>>print
(a,
type(
a))
--
--
--
--
--
--
--
--
--
--
10<class'i
nt'
>
>>>print
(b,
type(
b))
--
--
--
--
--
--
--
--
--
-20<class'
int
'>
>>>print
(c,
type(
c))
--
--
--
--
--
--
--
--
--
30<class'i
nt'
>
>>>a=10
>>>b=1.2
>>>c=a+b
>>>pri
nt(a,
type(
a))
--
--
--
--
--
--
--
--
--
--10<class'i
nt'
>
>>>pri
nt(b,
type(
b))
--
--
--
--
--
--
--
--
--
1. 2<cl
ass'fl
oat'>
>>>pri
nt(c,
type(
c))
--
--
--
--
--
--
--
--
--
-11.2<class'
float'
>
================================X==============================

Hi
ghLev
el

=>Inthi
scontext,wehav etwotypesofPr ogrammi ngLanguages.Theyare
a)LowLev elProgrammingLang
b)Hi ghLev el
Progr ammingLang
=>InLowLev elPr
ogrammi ngLang, werepresentdataint hef
ormlowerlevelbi
tsl
ike
Binar
y,OctalandHexaDeci malnumbersy stem.
=>Int
ernal
lyLowLev el dat
ainthef ormlowerlevelbit
slikeBinar
y,Octal
andHexa
Decimalnumbersy stem canbeaut omati
call
yconvertedintoUnderst
andablefor
mat
(Deci
mal NumberSy stem)andHencePy t
honi sconsideredasHighLevel
ProgrammingLanguage.

Ext
ensi
bleandEmbedded

=>AnExt ensibl
eProgrammi nglanguageisone, whichprovi
des/
off
erst
heServi
ces/
Facil
i
tiesofitsCodingtober e-usedinotherLanguages.
=>Exampl e:Pyt
honPr ogrammi ngprovi
desExtensiblebecausePyt
honcodecabbe
cal
ledpar tofC,CPP et clanguages.

=>AnEmbeddedProgr
ammi ngl
anguageisone,whi
chexpect
sSer
vices/Faci
l
iti
es
fr
om ot
herl
anguagesrel
atedt
hei
rcodingtore-
use.

=>=>Example:Pyt
honPr ogr
ammi ngprovi
desEmbeddedbecausePy thonProgr
am
canembedt hecodeofC, CPP etclanguages.
===============================X==============================

Robust

=>APr ogrammi ngissaidtobeRobusti fandonl yifI


talwaysprovidesUser-f
ri
endl
y
Err
orsMessageswhenend- usercommi tsmi stakesatimplementationlev
el.
=>TogetUser -f
riendl
yer r
ormessges, weuseexcept ionhandli
ngfeat ur
e.
=>SincePy t
honPr ogrammi ngPr ovi
desExcept i
onhandl i
ngFacili
tyandhencepy t
hon
i
soneoft heRobust( Str
ong)Pr ogrammi ngLanguage.
--
--
--
---
--
--
--
---
--
--
--
---
--
--
--
---
--
--
--
--
---
--
---
--
--
--
x--
---
--
--
--
---
---
--
--
--
--
--
--
--
--
--
--
--
--
--
----
--
-

Ext
ensi
veSuppor
tsf
orThi
rdPar
tyAPI
S
=>ThePy thonPr ogrammi ngSuppor t
sext ensiv
elyf
ormaki nguseofThi rdparty
APIS((Modul es)tof ordevel
opingther ealti
meapplicati
onswi thHighPerformnace
withpreci
secode.
NOTE:
--
--
--
--
---
--
--
=>Fir
stPar t
y---
LangLi brar
y(API)-
--
PythonI n-
buli
tLi
brary-
-developedbyROSSUI M
=>Secondpar ty-
--OSLi bar
y--
--
--
=>ThirdParty--
--
--
v endors-
--
--Tr
av i
sOliphant--
--
-Numpy (
C+PYTHON)
MCKi nney--
--
--
--
--
--
PANDAS
---
--
--
--
---
--
--
---
--
--
--
--
--
--
--
--
---
--
---
--
---
Scipy
Sciki
t

mat
plot
li
b

seabor
n
NLTP
-
--
--
--
--

pi
p PEP
pi
p3.
10
pi
p3

Dat
aRepr
esent
ati
oni
nPy
thon

=>ToRepresentt
hedat ainPy t
honPr ogr amming,weneed3thi
ngs.
1)Literal
s
2)Dat aTy pes
3)Identtif
ires/Var iables
1)Li
teral
s:
=>Lit
eral
sarenothi
ngbuti nputv aluespassi ngtothepr
ogr
am.
=>Basi
call
y,wehave4t ypesofLi terals.Theyare
a)Numer icLiterals
i)Integer s
i
i)floats
b)Bool eanLi terals
i)True
ii
)Fal se
c)St ri
ngLi terals
Exampl es:" Python"
"Gui doVanRossum"

I
mpor
tanceofI
dent
if
ier(
or)Var
iabl
es

=>Al
ltheLi
ter
alsar
est
oredi
nMai
nMemor
ybyal
l
ocat
ingsuf
fi
cientamountmemor
y
bythehelpofDat aTy pes.ToPr ocesstheLiter
als/Val
ues/datastoredi
nMai n
memor y,aspr ogrammer ,wemustgi vedisti
nctnamestothecr
eatedmemor yspace.
Sincethedisti
nctnamesmakesust oidenti
fytheLi
ter
als/Val
uesforprocessi
ng
andhencedi stinctnamesar ecalled"I
DENTI FI
ERS".
=>Programmat i
call
y, I
dentifi
ervaluescanbechangeddur i
ngexecuti
onofthe
program andHenceI dentif
iersarecall
ed" VARI
ABLES".
=>Henceal lTypesofI nputs/Literals/dataMustbestoredinmainMemor yinthe
form Vari
ables.

=>Def.ofVar
iabl
e:
=>AVar i
abl
eisanIdent
if
ier
,whoseval
uescanbechangeddur
ingexecut
ionoft
he
progr
am.
=>ALLTHEVARI ABLESINPYTHONARECALLEDOBJECTS.
=>BEHINDOFALLOBJECTS, THEREEXISTACLASS.

Rul
esf
orusi
ngVar
iabl
esi
nPy
thonPr
ogr
ammi
ng

1)AVar iableNamei sacombi nat i


onofAl phabet
s,Digit
sandaspeci alsymbol
Underscor e(_) .
2)TheFi rstletterofv ariablenamemustst ar
tswithAlphabet(or)UnderScor
e(_)
Exampl es: sal =1. 2--
--valid
1sal=34- ---Invalid
_sal=3. 4--valid
sal 1=4. 5----
-val
id
_sal _=5. 6--vali
d\
_123=56- --v
alid
_=45- ---valid
3)Withint heVar i
ableName, Speci alSymbol sar
enotal l
owed
exceptUnderScor e(_) .
Examples: t otsal =56- --
--Invali
d
t
ot _sal=45- --
v alid
t
ot -
sal=45- -
-inv ali
d
t
ot $sal=45- ---i
nv alid
_ $sal=34- -
--
-inv al
id
tot_sal #Indi a=56- -
--
--Val
i
d
Her et hesy mbol hash(#)inpythonusedf orcomment i
ng

.4)Nokey
wordst
obeusedasVari
abl
eNames.bcozal
lthekeywor
dsar
ehav
ing
speci
almeani
ngt
othel
anguagecompil
ers.

Examples: whil
e=45--
-i
navli
d
i
f=56-
--
--
inval
id
while1=67- -
--
vali
d
_while=67--vali
d
_i
f_=78- -
-val
id
i
nt=45. 67--
--
--VALID
f
loat=45- -
---
-VALID
=>ALLPr
e-def
inedCl
assNames( i
nt,f
loat..
...
etc)canusedasVar
aibl
e
Names
5)Al
lthevarai
bleNamear eCaseSensit
ive.
Examples:
-
---
--
--
--
--
--
-
>>>AGE=99
>>>age=98
>>>Age=97
>>>aGe=96
>>>agE=95
>>>pri
nt(
AGE, age,
Age,
aGe,
agE)
--
--9998979695
6)ChoosetheVar i
ableNamesinsuchwayt hatTheymustbeuser
-fri
endl
y.

Dat
aTy
pesi
nPy
thon

=>Themainpurposeofdat
atypesist
hatToall
ocat
esuffi
cientamountofmemory
spacef
orinputofthepr
ogram.
=>I
nPythonProgramming,
wehav e14datat
ypesandtheyareclassf
iedi
nto6t
ypes.
I)Fundament alCategor
yDat aTy pes
a)int
b)float
c)bool
d)compl ex
II
)SequenceCat egoryDataTy pes:
a)str
b)by t
es
c)by t
earray
d)range
II
I)Li
stCategoryDat aTypes(Collect
ionsDat
aType)
a)li
st
b)tuple
IV)SetCategoryDat aTy
pes( Collect
ionsDat
aTy
pe)
a)set
b)frozenset
V)DictCategoryDat aTypes(Collect
ionsDat
aType)
a)dict
VI)NoneCat egoryDataTy pe
a)NoneTy pe

I)Fundament
alCat
egor
yDat
aTy
pes

=>ThepurposeofFundamentalCat
egor
yDataTypesi
sthat"
Tost
oreSi
ngl
eVal
ue"
.
=>Fundamental
Categorycontai
ns4dat
aty
pes.Theyare
a)int
b)float
c)bool
d)compl ex

i
nt

=>'
int
'isoneofthepre-defi
nedclassandi ti
streat
edasFundament alDataType.
=>Thepurposeof'i
nt'datatypei
st hat"ToStoreInteger/Whole/Int
egralVal
ues.
"
=>"I
nteger/Whole/IntegralVal
uesar enothi
ngbutdat awi
thoutdeci
mal pl
aces.
Examples:
>>>a=123
>>>print
(a)--
--
--
--
---
-123
>>>type(a)-
--
---
--
---
<class'int'
>
>>>print
(a,type(a),i
d( a)
)--
---
123<class'int'
>2533443702832
>>>a=1567
>>>print
(a,type(a),i
d( a)
)--
-1567<class'int'
>2533444737104
--
--
--
--
--
---
--
--
---
--
--
--
---
---
--
-
=>With'i
nt'datatype, wecanal sostor eNumberSy st em Data.
=>InAnyPr ogrammi ngLanguage(Py thon,C,CPP, JAVA) ,wehav
e4t
ypesof
NumberSy stems.Theyar e
i)Deci mal NumberSy stem (
default).
ii
)Bi naryNumberSy stem.
ii
i)Oct alNumberSy stem.
iv)HexaDeci malNumberSy stem.

i
)Deci malNumberSy stem (def ault) :
--
--
---
---
--
--
--
--
--
---
--
---
--
---
--
---
--
--
---
---
-
=>Iti
soneoft hedef aultnumberSy stem
=>TheDeci mal NumberSy stem ( default)are
Digi
ts:0123456789
TotalNumberofDi git
s:10
Base:10
=>Base10Li t
eralsarecal l
edDeci mal NumberSy st
em Data.
--
--
---
---
--
--
--
--
--
---
--
---
--
---
--
---
--
--
---
---
---
----
--
---
---
--
--
--
--
--
--
---
--
i
i)Bi naryNumberSy stem :
--
--
---
---
--
--
--
--
--
---
--
---
--
---
--
---
--
--
---
---
-
=>TheDi git
sinBi naryNumberSy st
em ar e
Digi
ts:01
TotalNumberofDi git
s:2
Base:2
=>Base2Li teralsarecal l
edBi naryNumberSy st
em Dat a.
=>Tost oreBinarydat ainPy t
hgnPr ogr ammi ngEnv i
ronment
,bi
nar
ydatamustbe
precededwi theither0bor0B.
=>Syntax:-v arname=0bBi nar yDat a
(
OR)
v
arname=0BBi nar yData
=>Evenwest oreBinarydat aandwhenwedi splayTheBinar
yDataconver
tedi
nto
EquivalentDecimal NumberSy stem dat a.

Examples:
--
--
--
--
--
--
--
-
>>>a=0b1110
>>>pri
nt(a,
type(
a))
--
--
--
--
-14<class'int'
>
>>>a=0B1110
>>>pri
nt(a,
type(
a))
--
--
--
--
--14<class'int'
>
>>>
>>>a=0b1010
>>>pri
nt(a,
type(
a))
--
--
--
--
10<class' i
nt '
>
>>>a=0B1010
>>>pri
nt(a,
type(
a))
--
--
--
10<class' i
nt'
>
>>>a=0B10102- -
---
-Synt axError:i
nv al
iddi gi
t'2'i
nbinaryli
teral
--
--
--
---
--
---
--
--
--
---
--
---
--
---
------
---
--
--
--
--
---
--
---
----
---
--
--
--
--
---
--
--
--
--
--
--
--
---
---
--
--
--
-
II
I)Octal NumberSy st em :
--
--
--
---
--
---
--
--
--
---
--
---
--
---
------
---
--
--
--
-
=>TheDi git
sinOct al NumberSy stem ar e
Digits: 01234567
Total NumberofDi gits:8
Base:8
=>Base8Li teralsarecal ledOctalNumberSy stem Data.
=>Tost oreOctal datai nPy thgnPr ogr ammi ngEnv i
ronment, Oct
aldat
amustbe
precededwi theither0oor0O.
=>Syntax:-v arname=0oOct alDat a
(OR)
var name=0OOct alData
=>Evenwest oreOct al dat aandwhenwedi splayTheOct alDataconver
tedi
nto
Equival
entDeci mal NumberSy stem dat a.

i
nt

=>'
int'isoneoft hepr e- definedcl assandi tistreatedasFundament alDataType.
=>Thepur poseof' int'dat at ypeist hat"ToSt oreI nteger/Whole/Int
egralVal
ues.
"
=>"Integer/Whol e/I nt egralVal uesar enot hingbutdat awit
houtdeci
mal pl
aces.
Exampl es:
>>>a=123
>>>pr int(a)--
-----
---
--123
>>>t ype( a)--
-----
--
--<class' int'
>
>>>pr int(a, t
ype( a) ,i
d( a))--
---
123<cl ass' int'
>2533443702832
>>>a=1567
>>>pr int(a, t
ype( a) ,i
d( a))--
-1567<cl ass' int'
>2533444737104
--
--
----
--
----
----
--
-----
---
----
--
-
=>Wi th'int'dat at ype, wecanal sost or eNumberSy stem Data.
=>InAnyPr ogr ammi ngLanguage(Py t
hon, C, CPP, JAVA) ,wehave4typesof
NumberSy stems.Theyar e
i
)Deci mal NumberSy st em (default).
i
i)Bi nar yNumberSy stem.
i
ii)Oct al NumberSy stem.
i
v )HexaDeci mal NumberSy stem.
--
--
----
--
----
----
--
-----
---
----
--
-----
---
---
---
-
i
)Deci mal NumberSy st em (def ault) :
--
--
----
--
----
----
--
-----
---
----
--
-----
---
---
---
-
=>Itisoneoft hedef aul tnumberSy stem
=>TheDeci mal NumberSy stem ( defaul t)are
Digits:0123456789
Total NumberofDi git
s: 10
Base:10
=>Base10Li teralsar ecal l
edDeci mal NumberSy stem Data.
i
i)BinaryNumberSy stem :
=>TheDi git
sinBi naryNumberSy st
em are
Digi
ts:01
TotalNumberofDi gi
ts:2
Base:2
=>Base2Li teralsarecalledBinaryNumberSy st
em Data.
=>Tost oreBinarydat ainPythgnProgrammingEnvironment
,bi
nar
ydatamustbe
pr
ecededwi theither0bor0B.
=>Syntax:-v arname=0bBi naryData
(
OR)
v
arname=0BBi naryData
=>Evenwest oreBinarydataandwhenwedi spl
ayTheBinar
yDataconver
tedi
nto
Equi
v al
entDeci mal NumberSy st
em data.

Examples:
>>>a=0b1110
>>>pri
nt(a,
type(
a))
--
--
--
--
-14<class'int'
>
>>>a=0B1110
>>>pri
nt(a,
type(
a))
--
--
--
--
--14<class'int'
>
>>>
>>>a=0b1010
>>>pri
nt(a,
type(
a))
--
--
--
--
10<class' i
nt '
>
>>>a=0B1010
>>>pri
nt(a,
type(
a))
--
--
--
10<class' i
nt'
>

>>>a=0B10102-
--
--
-Sy
ntaxEr
ror
:inv
ali
ddi
git'
2'i
nbi
nar
yli
ter
al

I
II
)Oct
alNumberSy
stem :

=>TheDi
git
sinOct
alNumberSy
stem ar
e
Digits:01234567
Total NumberofDi gits:8
Base:8
=>Base8Li t
eralsarecal ledOctalNumberSy st
em Data.
=>Tost or
eOctal datai nPythgnProgr ammi ngEnv
ironment,Oct
aldat
amustbe
pr
ecededwi theither0oor0O.
=>Syntax:
-v arname=0oOct alData
(OR)
varname=0OOct alData
=>Evenwest oreOct al dataandwhenwedi spl
ayTheOct al
Dataconver
tedi
nto
Equi
v al
entDecimal NumberSy stem dat a.

--
--
--
--
--
--
--
--
Examples:
--
--
--
--
--
--
--
-
>>>a=0o22
>>>pri
nt(a,
type(a))
--
--
---
--
18<cl ass'int'
>
>>>a=0o345
>>>pri
nt(a,
type(a))
--
--
---
--
---
229<cl ass'int
'>
>>>a=0o299----
--
-SyntaxErr
or:invali
ddi gi
t'9'i
noctalli
ter
al
>>>a=0o288----
SyntaxError:i
nvali
ddi git'
8'inoct
alli
teral

I
V)HexaDeci
malNumberSy
stem :

=>TheDi git
sinHexaDeci malNumberSy stem ar
e
Digi
ts:01234567, 8,9,A(10),
B(11),
C(12),D(13)
,E(
14),
F(15)
TotalNumberofDigit
s:16
Base:16
=>Base16Li ter
alsarecall
edHexaDeci malNumberSy stem Dat
a.
=>Tost oreHexaDeci maldatainPythgnProgr
ammi ngEnvir
onment,HexaDeci
mal
datamustbepr ecededwi thei
ther0xor0X.
=>Syntax:-v ar
name=0xHexaDeci malData
(
OR)
v
arname=0XHexaDeci malData
=>Ev
enwestor
eHexaDecimaldat
aandwhenwedi splayTheHexaDeci
malDat
a
conv
ert
edi
ntoEqui
val
entDeci
malNumberSy
stem dat
a.

Examples:
>>>a=0xAC
>>>pri
nt(a,
type(
a))-
--
--
--
--
172<class'int'
>
>>>a=0x300
>>>pri
nt(a,
type(
a))-
--
--
--
--
768<class'int'
>
>>>a=0xBEE
>>>pri
nt(a,
type(
a))-
--
--
--
--
--
-3054<class'int
'
>
>>>a=0xFACE
>>>pri
nt(a,
type(
a))-
--
--
--
--
64206<class' i
nt'
>
>>>a=0xfacer-
--
--
--
--
SyntaxErr
or:i
nvalidhexadeci
mal
li
ter
al
>>>a=0xzxzx--
--
--
--
--
SyntaxErr
or:i
nvalidhexadeci
mal
li
ter
al

BaseConv
ersi
ont
echni
quesi
nPy
thon

=>ThepurposeofBaseConversi
ontechni
quesi
nPy
thoni
sthat"Conv
ert
ingOne
BaseValueint
oanotherBaseValue.
"
=>I
nPythonPr
ogramming,wehav
e3BaseConv
ersi
ont
echni
ques.Theyar
e
1)bi
n()
2)oct(
)
3)hex()
1)bi
n()
:

=>Thisfunct
ioni
susedforconv
ert
ingOtherNumberSy
stemsdat
aint
oBi
nar
y
NumberSy stem.
=>Syntax:
- v ar
name=bin(
Deci
mal /Oct
al/HexaDeci
malDat
a)

Exampl
es:

>>>a=15#Decmal numbersy st
em data
>>>b=bin(a)
>>>pri
nt(b)-
---
--
----0b1111
>>>b=bin(25)
>>>pri
nt(b)-
---
--
-----
0b11001
>>>a=0o22#oct aldat a
>>>b=bin(a)
>>>pri
nt(b)-
---
--
----0b10010
>>>b=bin(0o45)
>>>pri
nt(b)-
---
--
--0b100101
>>>a=0xF#HexaDeci mal
>>>b=bin(a)
>>>pri
nt(b)-
---
--
-0b1111
>>>a=0xFACE
>>>b=bin(a)
>>>pri
nt(b)-
---
--
--0b1111101011001110
>>>b=bin(0xBEE)
>>>pri
nt(b)-
---
--
---0b101111101110
>>>b=bin(0xBEER) -
---
--
--
SyntaxEr
ror
:inv
ali
dhexadecimalli
ter
al
>>>x1=bin(0x0133f abe11)
>>>pri
nt(x1)-
---
--
-----
-0b100110011111110101011111000010001

2)oct()
:
=>Thisfunct
ionisusedf
orconver
ti
ngOtherNumberSyst
emsdat
aint
oOct
al
NumberSy stem.
=>Syntax:
-v ar
name=oct(
Decimal/Bi
nary/HexaDeci
malDat
a)

Examples:
>>>a=18#Deci mal dat
a
>>>c=oct(a)
>>>pri
nt(c)-
--
--
--
-0o22
>>>c=oct(234)
>>>pri
nt(c)-
--
--
--
----
0o352
>>>a=0b1111
>>>c=oct(a)
>>>pri
nt(c)-
--
--
--
--0o17
>>>c=oct(0b1010)
>>>pri
nt(c)-
--
--
--
----
-0o12
>>>c=oct(
0b10100000011110001111000011)
>>>pri
nt(
c)--
--
--
--
--0o240361703
>>>a=0xACE
>>>c=oct(
a)
>>>pri
nt(
c)--
--
--
--
0o5316
>>>c=oct(
0xDEE)
>>>pri
nt(
c)--
--
--
--
-0o6756
>>>c=oct(
0xDAD)
>>>pri
nt(
c)--
--
--
--
0o6655

3)hex(
)

=>Thisf unct
ionisusedforconver
ti
ngOtherNumberSyst
emsdat
aint
oHexa
DecimalNumberSy st
em.
=>Syntax:-v ar
name=hex(Decimal/Bi
nary/oct
alData)
Exampl es:

>>>a=15 #deci maldata


>>>h=hex(a)
>>>pri
nt(
h)--
--
--
--
--
--
--
--
-0xf
>>>pri
nt(
hex(172))
--
--
---
--
-0xac

>>>a=0o22#oct aldata
>>>b=hex( a)
>>>print(
b)--
---
--
---
0x12
>>>b=hex( 0o34562)
>>>print(
b)--
---
--
---
0x3972
>>>a=0b1111
>>>b=hex( a)
>>>print(
b)--
---
--
-0xf
>>>b=hex( 0b111111111100000000011111111111)
>>>print(
b)--
---
--
-0x3ff007ff
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
---
--
Specialcase:
--
--
--
--
---
--
--
--
---
-
>>>a=15
>>>b=bin(a)
>>>print(
b, t
ype(b))-
--
---
--
-0b1111<class'str
'>
>>>b---
---
--
---'0b1111'
>>>b=oct (
a)
>>>print(
b, t
ype(b))-
--
---
--
--
-0o17<class'str
'>
>>>b=hex( a)
>>>print(
b, t
ype(b))-
--
---
--
--
---
0xf<cl
ass'str'
>

f
loat
=>'
fl
oat
'i
soneoft
hepr
e-def
inedcl
assandt
reat
edasFundament
aldat
aty
pe.
=>Thepurposeoffloatdatatypeisthat"Tostor
eFloat
ingPointVal
ues(
OR)Real
const
antValues(Number swithDecimal Pl
aces)
"
Examples:23.45,
56.990. 99. .
..
etc
-
24.56 -4.5-0.8..
etc
In23.
45,23iscall
edI nt
egerpartand0.45iscall
eddeci
mal part

=>Exampl
es:
>>>a=23.45
>>>pri
nt(a,ty
pe( a))-
--
--
--
----
--
23. 45<cl ass'
float'
>
>>>a=0.99
>>>pri
nt(a,ty
pe( a))-
--
--
--
----
-0.99<cl ass'fl
oat'
>
>>>a=22/ 7
>>>pri
nt(a,ty
pe( a))-
--
--
--
----
3.142857142857143<cl ass'fl
oat'
>
--
--
--
--
--
--
---
--
--
--
----
--
--
---
--
--
----
--
---
---
---
--
---
---
-
=>fl
oatdataty pecanal sor epresentSci entif
icNot ation(Manti
saeExponent)andi
t
canbeconv ertedintoNor mal Floatingpointvalueas
Mant i
sax10t ot hepowerofEx ponent
=>Theadv antageofSci entif
icNot at i
onisthatItsav et hememor yspace.
=>Thefloatdat atypeNev erst oresNumberSy stem dat adir
ectl
y.

Exampl
es:
>>>a=4e2
>>>pri
nt(a,
type(
a))-
--
--
--
---
400.0<cl ass'f
loat'
>
>>>a=10e2
>>>pri
nt(a,
type(
a))-
--
--
--
---
1000.0<cl ass'fl
oat'
>
>>>a=10e-2
>>>pri
nt(a,
type(
a))-
--
--
--
0.1<class' fl
oat'
>
>>>a=3.4e5
>>>pri
nt(a,
type(
a))-
--
--
--
-340000. 0<class'fl
oat'
>
>>>a=0.0000000000000000000000000000000000000000000000002
>>>pri
nt(a,
type(
a))-
--
> 2e- 49<class'fl
oat'>
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
---
---
>>>a=0b1010.0b1010---
--
-SyntaxError:i
nvali
ddecimall
it
eral
>>>b=0o12.0o34--
--
--
---
--
-SyntaxError:i
nvali
ddecimall
it
eral
>>>c=0xA.0xF--
--
--
--
--
-SyntaxError:
invali
ddecimalli
ter
al

bool
=>'
bool
'isoneofthepre-
definedclassandt
reat
edasFundamentaldat
aty
pe.
=>Thepurposeofbooldat
at ypei
st hat"
Tostor
eTrueandFalse(Logi
calval
ues)"
.
=>I
nter
nall
y,TheValueofTrueistakenas1andFal
seiatakesas0
Exampl
es:
>>>a=True
>>>pri
nt(a,
type(a))-
--
--
--
Tr ue<class'bool'
>
>>>b=False
>>>pri
nt(b,
type(b))-
--
--
--False<class'bool
'>
>>>
>>>pri
nt(Tr
ue+Tr ue)--
--
---
---
--
-2
>>>pri
nt(Tr
ue* True)-
--
----
--
---
1
>>>pri
nt(Tr
ue+Fal se)-
--
----
---
-1
>>>pri
nt(Tr
ue* False)-
--
---
---
--
0
>>>pri
nt(Tr
ue+Fal se*False)--
--
1
>>>pri
nt(2*
Tr ue+False)--
-2
>>>pri
nt(Tr
ue+0b1111) --
---
16
>>>pri
nt(Tr
ue+0xF) --
--
16

compl
ex

=>'
compl ex'isoneoft hepr e-
definedcl assandt r
eatedasFundament aldatat y
pe.
=>Thepur poseofcompl exdat atypei sthat" TostoreImaginarydata/compl ex
number s" .
=>Thegener alformatofcompl exnumberi sshownbel low.
a+bj ( OR) a- bj
Her e' a'iscalledReal Par t
'
b' i
scal l
edI magi nar yPar t
and' j
'i
ssqr t(-
1)
=>Togetr eal andi magi nar ypar t
sf rom compl exobjectweuset wopr e-dedi
ned
att
ributes.Theyar e
1)real
2)imag
=>Sy nt
ax:
compl exobj .
real --
-->Givesr eal partofcompl exobject
compl exobj .
imag- -
-->GivesI magi nar ypartofcompl exobject
=>Bydef aul tthev aluesofr eal andi magi narypartsofcompl exobjectsaretreated
i
nternallyasf l
oat i
ngpoi ntv al
ues.
=>Oncompl exdat a, wecanper form oper ati
onslikeAdditi
on, substracti
on,,
multipli
cat i
on...etc
=>InCompl exDat aRepr esent ati
on, forReal part,wecanuseanynumberSy stem
Valuebutf orImagi narypar twemustuseonl yDecimal NumberSy stem Valuesonly
butnotot hernumberSy stem v alues.
--
--
--
----
--
---
--
Exampl es:
--
--
--
----
--
---
--
>>>a=2+3j
>>>pr i
nt(a,type( a))
----
--
--
---
( 2+3j)<cl ass'compl ex'
>
>>>a=- 3-4j
>>>pri
nt(a,type(a) )
--
---
---
--
(-3- 4j)<cl ass' compl ex'>
>>>a=2.3+4. 5j
>>>pri
nt(a,type(a) )
--
---
---
--
(2. 3+4. 5j)<cl ass' compl ex'
>
>>>a=-2.3-
4. 6j
>>>pri
nt(a,type(a) )
--
---
---
-(-
2. 3-4.6j)<cl ass' compl ex'>
>>>a=2+3i-----
---
--SyntaxError : i
nval i
ddeci mal li
teral
>>>a=2j
>>>pri
nt(a,type(a) )
--
---
---
--
2j <cl ass' compl ex'>
--
--
--
--
--
--
--
---
----
---
--
----
---
---
--
--
-----
----
---
-----
---
----
---
---
----
---
Examples:
--
--
--
--
--
--
--
---
----
---
-
>>>a=10+40j
>>>pri
nt(a,type(a) )
--
---
---
(10+40j )<cl ass' compl ex'>
>>>pri
nt(a.real)-
----
--
---
10.0
>>>pri
nt(a.imag) ---
--
---
40.0
>>>b=2.3-4.5j
>>>pri
nt(b.real)-
----
--
--2.3
>>>pri
nt(b.imag) ---
----4.5
>>>b=2+4. 5j
>>>pri
nt(b.real)-
---2.0
>>>pri
nt(b.imag) ---
-4.5
--
--
--
--
--
--
--
---
----
---
--
----
---
---
--
--
-----
----
---
-----
---
----
---
---
----
---
---
>>>a=2+3j
>>>b=5+6j
>>>
>>>pri
nt(a,type(a) )
--
---
---
-(2+3j )<cl ass' compl ex'>
>>>pri
nt(b,type(b) )
---
---
--
(5+6j )<class' compl ex '
>
>>>c=a+b
>>>pri
nt(c,type( c))-
--
---
---
--(7+9j )<cl ass' compl ex'>
>>>
>>>c=a-b
>>>pri
nt(c,type( c))-
--
---
-(-
3- 3j)<cl ass' compl ex '
>
>>>c=a*b
>>>pri
nt(c,type( c))-
--
---
---
(-8+27j )<cl ass' compl ex'>
--
--
--
--
--
--
--
---
----
---
--
----
---
---
--
--
-----
----
---
-----
---
----
---
---
----
--
>>>a=True+2j
>>>pri
nt(a, t
y pe(a))-
---
---
--
--(1+2j )<cl ass' compl ex'>
>>>a=0b1010- 5j
>>>pri
nt(a, t
y pe(a))-
---
---
--
(10- 5j)<cl ass' compl ex '
>

>>>a=0b1010-0b1111j-
--
--
--
---
SyntaxErr
or:inv
ali
dbinaryl
i
teral
>>>a=0xA+0xFj-
---
--
--
--
--
SyntaxErr
or:inv
alidhexadeci
malli
teral
>>>a=0xA+3j
>>>pri
nt(
a,ty
pe( a)
)--
--
--
--
-(
10+3j)<class'complex'
>

I
I)SequenceCat
egor
yDat
aTy
pes

=>ThepurposeofSequenceCat
egoryDataTypesist
hat"ToSt
oreSequenceof
Values.
"
=>Wehav e4datatypesi
nSequenceCategor
y.Theyare
i
)str
i
i
)by t
es
i
i
i)bytear
ray
i
v)range

st
r

I
ndex:
--
--
--
--
--
=>Purpose
=>Numberofway stoorganizestrdata
=>NumberofNotationtoorganizestrdat
a
=>Operati
onsonstrdata
a)Indexing
b)Slici
ng

=>'
str'
isoneoft hepr e-defi
nedcl assandtreat
edasSequenceCategory.
=>Thepur poseof' st
r'datat ypeist hat"
TostoreSt
ri
ng/Text/Alpha-numericdat
a".
--
--
--
--
--
--
---
---
--
--
--
--
--
----
--
--
---
---
--
----
--
--
---
---
--
--
=>Numberofway st oor ganize/st r
orestrdata
--
--
--
--
--
--
---
---
--
--
--
--
--
----
--
--
---
---
--
----
--
--
---
---
--
--
=>InPythonPr ogrammi ng, wehav etwoway stoor
gani
zestrdat
a.Theyar e
a)Singl eLineSt rdata
b)Mul tiLineSt rdata
--
--
--
--
--
--
---
---
--
--
--
--
--
---
a)Si
ngl
eLi
neSt
rdat
a:
--
--
--
--
--
---
--
--
--
--
---
--
---
--
=>Thesingleli
nest ri
ngdat aisone, whichi
senclosedwi
thi
nsi
ngleQuotesor
doublequotes.
=>Inotherwords,Toor ganizesingl
elinestr
ingdata,
wemustusesingl
equotesor
doublequotes.
=>Syntax1: "Si ngl
el i
neSt r
ingdata"
(OR)
=>Syntax2: ' Singl
elineStri
ngdat a'

=>Wecan'
tusesi
ngl
eQuot
esordoubl
equot
esf
oror
gani
zi
ngMul
tiLi
neSt
ri
ngdat
a.

Exampl
es:
>>>s1="GuidoVanRossum"
>>>pri
nt(s1,t
ype(
s1)
)-
--
--
--
GuidoVanRossum <cl ass'st
r'
>
>>>s2='
Gui doVanRossum'
>>>pri
nt(s2,t
ype(
s2)
)-
--
--
--
--
-GuidoVanRossum <cl ass'
str
'>
>>>s3="A"
>>>pri
nt(s3,t
ype(
s3)
)-
--
--
--
--
A<cl ass'str
'>
>>>s4='
A'
>>>pri
nt(s4,t
ype(
s4)
)-
--
--
--
-A<class'str'
>
>>>s5="23456"
>>>pri
nt(s5,t
ype(
s5)
)-
--
--
--
--
-23456<cl ass'st
r'
>
>>>s6="Python3.10"
>>>pri
nt(s6,t
ype(s6))-
--
--
--
--
Python3.10<cl ass'
str
'>
>>>s7="Stri
ng"
>>>pri
nt(s7,t
ype(s7))-
--
--
--
Str
ing<class' st r
'>
>>>s7='
St r
ing'
>>>pri
nt(s7,t
ype(s7))-
--
--
--
-St
ring<class' str'
>
>>>addr1="Gudidov anRossum
SyntaxEr
ror:unt
ermi nat edstr
ingli
ter
al(
det
ect
edatl
i
ne1)
>>>addr1='Gudidov anRossum
SyntaxEr
ror:unt
ermi nat edstr
ingli
ter
al(
det
ect
edatl
i
ne1)

HenceToorgani
zeMultil
i
nest
ri
ngdat
a,wemustuseTr
ippl
esi
ngl
equot
esor
t
ri
ppledoubl
equotes.

b)Mul
tiLi
neSt
rdat
a:
--
--
--
--
--
---
--
--
--
--
---
--
--
-
=>TheMul ti
Linestri
ngdataisone,whichisencl
osedwi
thi
ntri
ppl
esingl
eQuotesor
tr
ippl
edoubl equotes.
=>Inotherwords,Toorgani
zeMul t
ili
nestri
ngdata,wemustuset
ri
pplesi
ngl
e
quotesortri
ppledoublequotes.
=>Syntax1: """
Str
ingData-1
St
ri
ngDat a-
2
-
--
--
--
--
--
--
--
-
St
ri
ngDat a-
n"""

(
OR)

=>Sy
ntax2: '
'' St
ri
ngDat
a-1
Str
ingDat a-
2
-
--
--
---
--
---
--
-
Str
ingDat a-
n''
'
=>HencewithTr
ippleSi
ngleQuot
es(or)t
rippl
edoublequot
es,
wecanor
gani
zebot
h
si
ngleandmulti
linestr
ingdat
a.
--
--
--
--
--
--
--
--
Exampl
es:
--
--
--
--
---
--
---
>>>addr 1="""
GuidovanRossum
..
.HNO: 3-4,Redseaside
..
.PythonSof twareFoundati
on
..
.Centrum Wi scundeI
nformati
ca
..
.NetherLands" ""

>>>pr
int
(addr
1,t
ype(
addr
1))
GuidovanRossum
HNO:3-4,Redseaside
Pyt
honSof twareFoundati
on
Centrum WiscundeI
nformati
ca
NetherLands <class'
str
'>
>>>addr2='''
JamesGosl i
ng
..
.SunMi croSy stem
..
.FNO:5-6Hi l
l Si
de
..
.USA'''
>>>pri
nt(addr 2,t
ype(addr2))
JamesGosl ing
SunMi croSyst em
FNO: 5-6HillSide
USA <cl
ass'
str
'>
--
--
--
--
--
--
--
----
--
---
---
--
---
--
--
--
--
----
---
--
---
---
>>>s1="""Pythoni sanoopl ang" ""
>>>pri
nt(s1,type(s1))-
--
--
--
----
--
----
---
-Pyt
honi sanooplang<class'
str
'>
>>>s2=''
'
javai salsooopl ang' '
'
>>>pri
nt(s2,type(s2))-
--
--
--
-javai salsooopl ang<cl
ass'st
r'
>
>>>s3="""A""
"
>>>pri
nt(s3,type(s3))-
--
--
--
---A<cl ass'
st r
'>
>>>s4=''
'
A' '
'
>>>pri
nt(s4,type(s4))-
--
--
--
----
-A<cl ass'str'
>

=>Hence,
wehav
e4Not ati
onst oorgani
zeSt
ri
ngdat
a.Theyar
e
a)Si
ngleQuot es
b)DoubleQuot es
c)Tr
ippleSingleQuotes
d)Tr
ippleDoubl eQuotes

Oper
ati
onsonst
rdat
a

=>Onst
rdata,wecanper
for
mtwot
ypesofOper
ati
ons.Theyar
e
1)I
ndexing
2)Sli
cing
1)I
ndexi
ng:
=>Theprocessofobt ai
ninganel ementf rom gi
venstrobj
ectbypassi
ngv
ali
dindex
val
ue.
=>Synt
ax: st r
obj[Index]
=>I
ndexcanei t
herPossitiveorNegat ive
=>I
fweent erval
idIndext hengetVal ueatthatIndex
=>I
fweent erI
nvali
dIndext hengetI ndexError
Examples:
>>>s="PYTHON"
>>>pri
nt(s[
0])
--
--
--
-P
>>>pri
nt(s[
-6]
)-
--
--
-P
>>>pri
nt(s[
1])
--
--
--
-Y
>>>pri
nt(s[
2])
--
--
--
--
T
>>>pri
nt(s[
4])
--
--
--
--
O
>>>pri
nt(s[
5])
--
--
--
-N
>>>pri
nt(s[
-1]
)-
--
--
--
-N
>>>pri
nt(s[
-2]
)-
--
--
--
O
>>>pri
nt(s[
-3]
)-
--
--
--
H
>>>pri
nt(s[
-4]
)-
--
--
T
>>>pri
nt(s[
-5]
)-
--
-Y
>>>pri
nt(s[
-6]
)-
--
-P
>>>pri
nt(s[
10])
--
--
-I
ndexEr ror:stri
ngindexoutofr ange
>>>pri
nt(s[
-7]
)-
--
-I
ndexError :str
ingindexoutofr ange

====================================

=>'
by t
es'i
soneoft hepre-
defi
nedclassanditi
streatedasSequenceDat aTy pe.
=>Thepur poseofbytesdatat
ypeisthat"
TostoretheNumer i
cal Possit
iveI
nteger
Valuesrangesf r
om 0to256.i
.eItst
oresNumericalPossi
ti
veIntegerValuesranges
fr
om 0t o255( 256-
1)only.
=>bytesdatatypedoesnothaveanySy mboli
cnotati
onfororganizi
ngt hedat
abut
wecanconv er
tthedataofanyty
pei nt
obytesdatatypebyusingby tes()
.
Sy ntax:v ar name=by tes(obj ect)
=>Ont heobj ectofby tesdat at y
pe, wecanper f
or mI ndexi ngandSl i
cingOperati
ons.
=>Anobj ectofby tesdat at ypemai nt ainsi nser t
ionor der( OR)I notherwords,In
whichev eror derwei nser tt hedat aint hesameor dert hedat awillbedisplay
ed.
=>Anobj ectofby tesbel ongst oImmut ablebcoz' by tes'obj ectdoesnotsuppor ti
tem
assignment .
--
--
--
----
-------
-----
--
----
-
Exampl es:
--
--
--
----
-------
-----
--
----
-
>>>t =(10, 20, 30,256, 34, 0)
>>>pr int( t,
type( t))--
----
-----
----(10,20, 30, 256, 34,0)<cl ass' tuple'
>
>>>b=by tes( t)-
----
--ValueEr ror :bytesmustbei nr ange( 0, 256)
--
--
--
----
-------
-----
--
----
-----
-
>>>t =(10, -20, 30,255, 34, 0)
>>>pr int( t,
type( t))--
----
--(10, -20, 30, 255, 34,0)<cl ass' t
upl e'>
>>>b=by tes( t)-
----
---
---Val ueEr ror
:by tesmustbei nr ange( 0, 256)
--
--
--
----
-------
-----
--
----
-----
--
>>>t =(10, 20, 30,255, 34, 0)
>>>pr int( t,
type( t))--
----
-----
(10, 20,30, 255, 34, 0)<cl ass' tuple'>
>>>b=by tes( t)
>>>pr int( b,ty pe(b) )--
----
-b'\n\ x14\ x1e\ xf f"
\x00' <cl ass' bytes'>
>>>f orvi nb:
..
. pr int(v)
..
.
10
20
30
255
34
0
>>>pr int( b[0])--
----
-----
----
----10
>>>pr int( b[-1])-
----
-----
----
----0
>>>pr int( b[-2])-
----
-----
----
---34
>>>pr int( b[2:5])---
----
-----
--b'\x1e\ xff"'
>>>f orvi nb[ 2:
5] :
..
. pr int(v )
..
.
30
255
34
>>>pr int( b,ty pe(b) ,
id(b) )--
-----b'\
n\x14\ x1e\ xff"\x00' <class' bytes'
>2360235709168
>>>pr int( b[0])--
----
--10
>>>b[ 0]=100- --
--Ty peEr ror :'by t
es'obj ectdoesnotsuppor tit
em assignment
=============================X===============================
>>>l=[10, 20,30, "KVR" ,
34, 56, 78]
>>>pr int( l
,type( l
))---
----
- [
10, 20, 30,'KVR' ,34,56, 78]<cl ass' li
st'
>
>>>b=by tes( l)-
--
---Ty peEr ror :'str'
obj ectcannotbei nterpretedasani nteger
--
--
--
----
-------
-----
--
----
-----
----
>>>l=[10, 20,30, 0,34,56, 78, 255]
>>>pr int( l
,type( l
))---
----
- -
-[10, 20, 30, 0, 34, 56, 78, 255]<cl ass' li
st'
>
>>>b=by t
es( l
)
>>>print(
b,t
y pe(b),i
d(b)
)-
--b'
\n\x14\
x1e\x00"
8N\xff
'<cl
ass'
bytes'
>2360235711472
>>>print(
b[0])-
--10
>>>print(
b[-1])
----
255
>>>forki nb:
..
. pri
nt(k)
.
..
10
20
30
0
34
56
78
255
>>>forki nb[::
-1]:
..
. pri
nt(k)
..
.
255
78
56
34
0
30
20
10
>>>forki nb[::
2]:
..
. pr i
nt(k)
.
..
10
30
34
78
>>>forki nb[::
-2]:
..
. pr i
nt(k)
..
.
255
56
0
20
>>>b[0]=200---
----
--
TypeErr
or:'byt
es'obj
ectdoesnotsuppor
tit
em assi
gnment
==========================X==================================
by
tear
ray

=>'bytear ray 'isoneoft hepr e-


definedclassandi tistreatedasSequenceDat aTy pe.
=>Thepur poseofby tearraydat atypeist hat"Tost oretheNumer i
cal Possi t
ive
IntegerVal uesr angesf rom 0t o256.i .
eItst or
esNumer i
calPossitiv
eI ntegerVal ues
rangesf rom 0t o255( 256- 1)only.
=>by tearr aydat at ypedoesnothav eanySy mbol i
cnot ati
onf ororganizingt hedat a
butwecanconv ertthedat aofanyt ypeintoby tearraydat atypebyusi ngby tear
ray()
.
Syntax:v arname=by tearray(object)
=>Ont heobj ectofby tearraydatat ype,wecanper f
ormI ndexingandSl i
cing
Oper ations.
=>Anobj ectofby tearraydat atypemai ntainsinser t
ionor der(OR)Inot herwor ds,In
whi chev eror derwei nser tthedatai nthesameor derthedat awillbedi splayed.
=>Anobj ectofby tearraybel ongstomut ablebcozI tallowsust odot hechangesat
sameaddr ess.
---
--
---
---
-------
---
---
---
--
--
--
----
---
--
---
--
--
---
--
--
---
--
-

Note:-TheFunct ionali
tyofby tearr
ayisexactlysi
mi l
artoby t
esdatat
ypebutan
objectofby tear raybelongst omut abl
eandanobj ectofbytesbel
ongstoi
mmut abl
e.
--
--
---
--
--
---
---
--
----
---
---
--
--
---
--
---
--
--
--
---
--
--
--
--
--
--
-
Exampl es:
--
--
---
--
--
---
---
-
>>>l=[10,20,30,45,67,89]
>>>pr i
nt(l
,t
ype( l)
)--
---
--
--
-[10,20,30,45,67,89]<cl
ass' l
ist
'>
>>>ba=by t
ear ray(l
)
>>>pr i
nt(ba,
t ype(ba),
id(ba))-
--
by t
earr
ay(b'
\n\x14\x1e-CY'
)<class'
byt
ear
ray'
>
2360235852976
>>>pr i
nt(ba[0])--
---
10
>>>pr i
nt(ba[1])--
---
20
>>>pr i
nt(ba[-1])-
---
89
>>>forxi nba:
..
. pr i
nt(x)
..
.
10
20
30
45
67
89

>>>f
orxinba[
::
-1]
:
..
. pri
nt(
x)
.
..
89
67
45
30
20
10
>>>f
orxinba[
2:5]
:
..
. pri
nt(
x)
.
..
30
45
67
>>>pri
nt(
ba[0]
)-
--
--
--
--
10
>>>ba[0]
=153
>>>pri
nt(
ba,t
ype(
ba),
id(
ba))
--
--
byt
earr
ay(
b'\
x99\
x14\
x1e-
CY'
)<cl
ass'
byt
ear
ray
'>
2360235852976
>>>forkinba:
..
. print
(k)
..
.
153
20
30
45
67
89

r
ange
=>'
range' i
soneoft hepre-defi
nedclassandtreatedasSequenceCategoryData
Type.
=>Thepur poseofrangedat atypeisthat"ToStoreSquenceofNumer i
cal I
nteger
Valueswi t
hEqual I
nterval".
=>Ont heobjectofrange, wecanper formIndexi
ngandSl i
cingOper
ations.
=>Anobj ectofrangedat atypebel
ongst oImmutable
=>rangedat aty
pecont ains3typesofSy nt
axes.Theyare
--
--
---
--
--
--
-
Sy
ntax1:
-
--
--
--
--
--
--
-
varname=range(v
alue)
=>Her
evarnamei sanobjectof<cl
ass,'
range'
>
=>Thi
ssyntaxgenerat
estherangeofv aluesf
rom 0t
oval
ue-
1

Exampl
es:
>>>r=range(11)
>>>pri
nt(r,t
ype(r
))-
--
--
--
range(
0,11)<cl
ass'
range'
>
>>>forvinr:
..
. print(
v)
.
..
0
1
2
3
4
5
6
7
8
9
10

>>>f
orvinrange(
6):
..
. pri
nt(
v)
...
0
1
2
3
4
5
--
--
--
---
--
---
--
---
---
---
--
--
--
---
---
--
--
--
--
--
--
--
---
--
--
---
--
--
--
---
--
--
--
--
Syntax2:-v arname=r ange(st
art
,stop)
=>Thissy ntaxgener atesrangevaluesfrom starttostop-
1val
ues
Exampl es:
--
--
--
---
--
---
>>>r=range( 10,21)
>>>print(r,
type(r)
)--
--
--
---
--
--
range(10,21)<class'range'
>
>>>forvi nr :
..
. pr i
nt(v)
..
.
10
11
12
13
14
15
16
17
18
19
20
>>>forki nr ange(100,106):
..
. pr i
nt(k)
...
100
101
102
103
104
105
>>>f
orkinrange(
50,
56)
:
..
. pri
nt(
k)
.
..
50
51
52
53
54
55
=>NOTE: I
nt heabov et wosy ntaxest hedefaulti
nter val
uei s1andgener
atesr
angeof
valuesi nFor war ddi recti
ononl y.
--
--
-----
--
---
--
---
----
---
--
---
----
--
---
---
--
-----
--
--
---
---
--
--
--
--
--
--
---
---
--
---
---
-
Synt ax-3:
--
--
-----
--
---
-
varname=r ange( start
,st
op,st
ep)
=>Thi ssy ntaxgener atesrangeofv aluesfrom starttost op-1wi
thspeci
fi
edequal
i
nter valofv alue( step)
Exampl es:
--
--
-----
--
---
>>>r =range( 10,21,2)
>>>pr int(r,
type(r))--
--
---
--r
ange( 10,21,2)<class'range'>
>>>f orxi nr :
..
. pr i
nt (
x)
.
..
10
12
14
16
18
20
>>>f orxi nr ange( 10,51,10):
..
. pr i
nt (
x)
.
..
10
20
30
40
50
==========================================================
Not e: r ange( Value)
range( start,
stop)
range( start,
stop,st ep)
--
--
-----
--
---
--
---
----
---
--
---
----
--
---
---
--
-----
--
--
---
---
--
--
--
--
--
--
---
---
--
---
---
--
---
--
-
Q1)Gener ate 01 2 3 4 5 6 7 8 910- --
-range(11)
>>>f orxi nr ange( 11):
..
. pr i
nt (
x)
.
..
0
1
2
3
4
5
6
7
8
9
10
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
Q2)Generate 100101 102103104105- --
--
range(100,106)
>>>forxinrange(
100,106):
..
. print
(x)
.
..
100
101
102
103
104
105
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
Q3)Generate10 15 20 25 30 35 40- -
--
range(10,41,5)
>>>forxinrange(
10,41,
5):
..
. print
(x)
.
..
10
15
20
25
30
35
40
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
Q4)Generate1020 3040 50 60 708090100- --
range(10,
101,
10)
>>>forxinrange(
10,101,
10):
..
. print
(x)
.
..
10
20
30
40
50
60
70
80
90
100
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
Q5)Generate-1- 2- 3-4- 5-6-7- 8-9- 10--
--
-range( -1,
-
11,-
1)
>>>forxinrange(-1,-11,-1):
..
. print
(x)
..
.
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-----
--
----
----
--
--
--
--
---
--
--
--
-
Q6)Generate-10- 20 - 30- 40- 50--
--
-r
ange(-
10,-
51,-10)
>>>forxinrange(-10,-51,-10):
..
. print
(x)
..
.
-10
-20
-30
-40
-50
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-----
--
----
----
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
-
Q6)Generate10 9 8 7 6 5 4 3 2 1- --
range(10,0,
-1)
>>>forxinrange(10,0,-1):
..
. print
(x)
.
..
10
9
8
7
6
5
4
3
2
1
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-----
--
----
----
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
---
-
Q7)Generate100 90 80 70 60 50- -
-r
ange(100,49,-
10)
>>>forxinrange(100, 49,-10):
..
. print
(x)
.
..
100
90
80
70
60
50
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-----
--
----
----
--
--
--
--
---
--
--
--
--
--
--
Q8)gener ate- 5- 4- 3- 2-10 1 2 3 45- -
range(-
5,6,
1)
>>>forxinr ange(-
5,6,1):
..
. print(
x)
..
.
-5
-4
-3
-2
-1
0
1
2
3
4
5
--
--
--
--
--
---
--
---
----
--
--
---
---
--
---
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
---
--
--
--
--
-
>>>r=range( 100,151,10)
>>>pri
nt(r)---
--
---
--
-range(100,151,10)
>>>forxinr :
..
. print(x)
..
.
100
110
120
130
140
150
>>>pri
nt(r[2])-
--
---
--
---
120
>>>pri
nt(r[-1])
--
---
--
---
150

>>>f
orxinr[
2:]
:
..
. pri
nt(
x)
.
..
120
130
140
150
>>>f
orxinr[
::
-1]
:
..
. pri
nt(
x)
.
..
150
140
130
120
110
100
>>>pri
nt(range(
1000,1050,10)
[2])
---
--
--
--
1020
>>>pri
nt(range(
1000,1050,10)
[-1]
)--
--
1040
>>>forxinrange(1000,1051,
10)[:
:
-1]:
..
. pri
nt(x)
.
..
1050
1040
1030
1020
1010
1000
=========================================================
>>>r=range(10,
100,10)
>>>forxinr:
..
. print(
x)
.
..
10
20
30
40
50
60
70
80
90
>>>pri
nt(r[
1])-
--
--
--
--
---
-20
>>>r[
1]=200---
--
-TypeErr
or:'
range'
obj
ectdoesnotsupportit
em assi
gnment
>>>

Example--
--
--
--
--
rangedatatype
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
-
1)01 2 3 4 5 6 7 8 910

2)100101 102103104105

3)10 15 20 25 30 35 40

4)1020 3040 50 60 708090100


--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
5)-1- 2-3- 4- 5-6-7- 8-9- 10
6)-10-20 -30-40- 50
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
7)10 9 8 7 6 5 4 3 2 1
8)100 90 80 70 60 50
9)-5-4- 3-2-10 1 2 3 45
I
II
)Li
stCat
egor
yDat
aTy
pes(
Col
l
ect
ionsDat
aTy
pe)
=>Thepur
poseofListCategoryDat
aTy pesisthat"Tostor
emult
ipl
ev al
ueseit
herof
sametypeordi
ff
erentty
peorbot htypeswithUniqueandDupl
i
catesinsingl
e
obj
ect.
"
=>Wehave2typesofdatat y
pesinListCategory
.Theyare
1)li
st
2)tupl
e

1)l
i
st

=>'
li
st'i
soneoft hepre-definedclassandtreat
edasListcategorydatat y
pe.
=>Thepurposeofl i
stdatat ypeisthat"Tostor
emulti
plevalueseitherofsametype
or
di
ffer
enttypeorbotht ypeswi t
hUni queandDupl
icatesinsingl
eobj ect
".
=>Tostoretheelementsi nlist,
theelementsmustbewr i
tt
en( or
)enclosedwit
hin
SquareBrackets[]andt heelement smustbeseparatedbycomma.

Sy
ntax:
- var
name=[val
1,v
al2,
..
..
,
val
-n]#Non-
empt
yli
st
v
arname=[] #emptylist
v
arname=l
i
st (
) #empt ylist

=>Anobjectofl
istdatatypemai
ntainsinser
ti
onor der
.
=>Ontheobjectofli
st,wecanperform bothIndexi
ngandSl
i
cingOper
ati
ons.
=>AnObjectofli
stbelongstomutable.

Exampl
es:
--
--
--
--
--
---
---
---
>>>l1=[10,20,-30,
40,
10,60,20]
>>>print(l
1,t
y pe(l
1))
--
--
--
-[10, 20,-
30, 40,10,60,20]<cl
ass'
li
st'
>
>>>l2=[100,"Rossum" ,
45.67,True,2+3j,
"Python"
]
>>>print(l
2,t
y pe(l
2))
--
--
--
[100, 'Rossum' ,
45.67,True,(
2+3j
),'
Pyt
hon'
]<cl
ass'
l
ist
'>
>>>
>>>len(l1)
---
----
-7
>>>len(l2)
---
----
6
>>>l3=[]
>>>print(l
3,t
y pe(l
3))
--
--
--
--[]<class'l
ist'
>
>>>len(l3)
---
----
-0
>>>l4=li
st()
>>>len(l4)
---
----
-0
>>>print(l
4,t
y pe(l
4))
--
--
--
--[]<class'l
ist'
>
>>>l2=[100,"Rossum" ,45.67,
True,
2+3j,
"Pyt
hon"]
>>>print(l
2[0])-
--
---
--
100
>>>print(l
2[1])-
--
---
--
Rossum
>>>print(l
2[-1])
--
---
--
-Python
>>>print(l
2[2:5])
---
--
--
[45.67,True,
(2+3j)
]
>>>l2=[100,"Rossum" ,45.67,
True,
2+3j,
"Pyt
hon"]
>>>print(l
2,t
y pe(l
2),i
d( l
2))-
--
[100,
'Rossum',45.67,
Tr ue,(
2+3j
),'
Python'
]
<class'l
ist'
>2438540918080
>>>l2[
2] =66.99
>>>print(l
2,t
y pe(l
2),i
d( l
2))-
--
[100,
'Rossum',66.99,
Tr ue, (2+3j),
'
Python']<cl
ass' l
ist'
>2438540918080
============================X=============================

Pr
e-def
inedFunct
ionsi
nli
st

=>AlongwithIndexi
ngandSlici
ngOperati
ons,ontheobj
ectoflistwecanper
for
m
vari
ousotheroperati
onsbyusingpre-
defi
nedfuncti
onspresentinli
st.
=>Thepre-defi
nedfunct
ionspresenti
nli
stare
--
--
--
--
--
--
--
--
---
1)append(
):
--
--
--
--
--
----
--
--
-
=>ThisFunct i
oni susedf orappending(addingatend)newel ementtoexist
ing
element soflist
=>Syntax:- l i
stobj.append(Value)
--
--
--
--
--
----
-
Exampl es:
--
--
--
--
--
----
>>>l1=[10,"
Rossum" ]
>>>print(l
1,t
ype(l1),
id(l
1))
--
--
---
[10,'
Rossum' ]<cl
ass'l
ist
'>1957574950720
>>>l1.append(23.45)
>>>print(l
1,t
ype(l1),
id(l
1))
--
--
[10,'Rossum',23.45]<cl
ass'li
st'
>1957574950720
>>>l1.append("Py t
hon")
>>>print(l
1,t
ype(l1),
id(l
1))
--
-[
10, '
Rossum',23.45,'Pyt
hon']<cl
ass'
li
st'
>
1957574950720

>>>l2=[]
>>>print
(l2,
type(l
2),
id(
l2)
)--
--
---
--
[]<class'l
ist'
>1957574946752
>>>l2.
append( 100)
>>>l2.
append( "KVR")
>>>l2.
append( "Pyt
hon")
>>>print
(l2,
type(l
2),
id(
l2)
)--
--
[100, '
KVR','
Py t
hon']<cl
ass'li
st'
>1957574946752
>>>l3=li
st()
>>>print
(l3,
type(l
3),
id(
l3)
)--
--
[]<class'li
st'
>1957575198336
>>>l3.
append( True)
>>>l3.
append( 2+3j)
>>>l3.
append( "Pyt
hon")
>>>print
(l3,
type(l
3),
id(
l3)
)--
--
[True,(2+3j),
'Python'
]<class'
li
st'
>1957575198336
--
--
--
--
--
---
--
---
--
--
--
---
--
--
--
--
--
--
--
--
--
---
---
---
--
---
--
--
--
---
--
--
--
--
---
--
--
--
-
2)i
nser
t():
--
--
---
---
-----
=>Thi sf unct i
oni susedf oraddi nganel ementatspecf iedposition/Index.
=>Sy ntax:- l istobj.i
nser t
(I
ndex, Value)
--
--
---
---
-----
----
---
-
Exampl es:
--
--
---
---
-----
----
---
-
>>>l1=[ 10, "Rossum" ,
34.56]
>>>pr int(l1,type( l
1))-
--
--
----[
10, '
Rossum' ,34.56]<cl ass'l
ist'
>
>>>l1. i
nser t(
2,"Py t
hon")
>>>pr int(l1,type( l
1))-
--
--
----[
10, '
Rossum' ,'
Py t
hon', 34.56]<class'li
st'
>
>>>l1. i
nser t(
2,Tr ue)
>>>pr int(l1,type( l
1))-
--
--
-[10, 'Rossum' ,True,'Python',34.56]<class' l
i
st'
>
--
--
---
---
-----
----
---
-----
--
--
--
---
--
----
----
--
--
----
--
--
---
--
3)r emov e( )- -
-contentbasedr emov al
--
--
---
---
-----
--
=>Thi sf unct i
oni susedf orr emov i
ngFi r
stOccur enceofspeci fiedelement.
=>Ifthespeci fi
edel ementnotpr esenti nlistthenwegetVal ueEr r
or.
=>Sy ntax: l i
st obj.r
emov e(Value)
--
--
---
---
----
Exampl es:
>>>l1=[ 10, 20,30, 10,
20,"Rossum" ,"Pyt
hon" ,
20]
>>>pr int(l1)---
-----
-[
10,20, 30, 10, 20,'
Rossum' ,'
Py thon',
20]
>>>l1. r
emov e(10)
>>>pr int(l1)---
----[
20,30, 10, 20,'
Rossum' ,'
Py thon',20]
>>>l1. r
emov e(20)
>>>pr int(l1)---
--[30,10,20, '
Rossum' ,'
Py thon',20]
>>>l1. r
emov e(100) --
--
--
--ValueEr ror:l
ist.
remov e(x):xnotinl i
st

4)pop(
Index)
:-
--
-I
ndexbasedr
emov
al

=>ThisFunct i
onisusedf orr emov i
ngtheelementbasedVal
i
dExi
sti
ngI
ndex
other
wi sewegetI ndexEr ror
=>Syntax:- l i
stobj .pop(index)
Exampl es:
--
--
--
--
--
----
--
--
>>>l1=[10,20,
20,10, 20,30,40,10,20]
>>>print(l
1)--
--
--
--
--[10, 20,20, 10,20,30,40,10,
20]
>>>l1.pop(3)-
---
--
-10
>>>print(l
1)--
--
--
-[
10, 20,20, 20,30,40,10,20]
>>>l1.pop(0)-
---
--
-10
>>>print(l
1)--
--
--
-[
20, 20,20, 30,40,10,20]
>>>l1.pop(-2)
---
--
----
10
>>>print(l
1)--
--
--
--
[20, 20,20, 30,40,20]
>>>l1.pop(-4)
---
--
--20
>>>pr
int(
l1)
--
--
--
-[
20,20,30,40,20]
>>>l
1.pop(-
20)-
--
--
--
IndexEr
ror:
popindexoutofr
ange

5)pop(
):
--
--
--
--
--
----
-
=>ThisFunctioni susedf ordel eti
ngt helastelementofthel
i
stobj
ect
=>Syntax:-l i
stobj .
pop( )
--
--
--
--
--
----
-
Exampl es:
--
--
--
--
--
----
-
>>>l1=[10,"
Arbaj","Python" ,45.67,2+3j ]
>>>print(l
1)-
--
--
------
---
-[10,'Arbaj '
,'
Py thon',45.67,(
2+3j
)]
>>>l1.pop()-
--
--
---
--(2+3j )
>>>print(l
1)-
--
--
------
[10, '
Ar baj'
,'Python' ,45.67]
>>>l1.i
nsert(
2,"
Jav a")
>>>print(l
1)-
--
--
--[10, '
Ar baj','
Jav a'
,'Py thon',45.
67]
>>>l1.pop()-
--
--
---
-45. 67
>>>print(l
1)-
--
--
------
[10, '
Ar baj'
,'Java','Py t
hon']
>>>l1.pop()-
--
--
---
'Py thon'
>>>print(l
1)-
--
--
-----[
10, 'Arbaj','
Java']
>>>l1.pop()-
--
--
---
-'Jav a'
>>>print(l
1)-
--
--
---[10, '
Ar baj']
>>>l1.pop()-
--
--
---
-'Arbaj '
>>>print(l
1)-
--
--
---[10]
>>>l1.pop()-
--
--
--10
>>>print(l
1)-
--
--
[]
>>>l1.pop()-
--
--
---
--IndexEr r or:popf rom empt yli
st

>>>[
].
pop()-
--
--
--
--
-I
ndexErr
or:popf
rom empt
yli
st
>>>l
i
st()
.pop()
--
--
IndexEr
ror:
popfr
om emptyli
st

6)cl
ear
():
--
--
--
--
--
---
-
=>Thisfunct
ionisusedforr
emov
ingal
ltheel
ement
sofl
i
standmakest
hel
i
st
empty.
=>Syntax:
-list
obj.
clear
()

Exampl es:
--
--
--
--
--
----
>>>l1=[10,"
Arbaj"
,"
Py t
hon",
45.
67,2+3j
]
>>>print(l
1)-
--
--
--
--
---
[10,'
Arbaj
'
,'Pyt
hon'
,45.
67,
(2+3j
)]
>>>len(l1)-
--
--
--
--
-5
>>>l1.clear
()
>>>print(l
1)-
--
--
--
--
-[
]
>>>len(l1)-
--
--
--
--
-0

NOTE:
-del
()i
saGener
alf
unct
ionusedf
orr
emov
ingt
heel
ement
sofanymut
abl
e
obj
ectbasedoni
ndexi
ngandsl
i
cingandwecal
lal
sor
emov
eent
ir
eobj
ect
.

Exampl es:
--
--
--
--
--
----
--
---
>>>l1=[10,20,20,10,20, 30,40,10,
20]
>>>print(l
1)--
---
--
--[10, 20, 20,10,20,30,40,10,
20]
>>>del(l1[
1:3])
>>>print(l
1)--
---
--
-[10, 10, 20, 30,
40, 10,20]
>>>del(l1[
2])
>>>print(l
1)--
---
--
[10, 10, 30, 40,10,20]
>>>del(l1[
-2])
>>>print(l
1)--
---
--
-[10, 10, 30, 40,
20]
>>>del l1
>>>print(l
1)--
---
-NameEr ror:name'l1'isnotdef
ined.Di
dyoumean:
'l
2'
?

7)count
():
--
--
--
--
--
-----
-
=>Thisf unctionisusedf orcountingnumberofoccur
encesofaspeci
fi
edel
ement
s
=>Syntax: l istobj.
count(value)
Exampl es:
--
--
--
--
--
-----
>>>l1=[10, 20,20,
10,20,30,40,10,
20]
>>>print(l1)--
---
--
[10,20,20, 10,20,30,
40,10,
20]
>>>l1.count (10)--
--
--
--3
>>>l1.count (20)--
--
--
4
>>>l1.count (40)--
--
--
1
>>>l1.count (400)--
--
---
0

8)i
ndex(
):
--
--
---
--
--
--
--
=>Thisfunctionisusedf orfi
ndingIndexofFir
stOccurenceofthespeci
fiedel
ement
.
=>Ifthethespeci f
iedel ementisnotfoundinli
stobjectthenwegetValueErr
or.
=>Syntax: listobj
.index(element)
--
--
---
--
--
--
--
----
--
=>Exampl es:
--
--
---
--
--
--
--
----
--
>>>l1=[10,20,20,
10,20,30,40,
10,20]
>>>pr i
nt(
l1)---
--
--
--
-[
10, 20,20,10,20,30,40,
10, 20]
>>>l1.i
ndex (10)-
--
--
---
0
>>>l1.i
ndex (20)-
--
--
---
1
>>>l1.i
ndex (40)-
--
--
---
-6
>>>l1.i
ndex (400)-
--
---
Val ueEr
ror:400isnoti
nlist
9)copy
():
(Shal
l
owCopy
)
--
--
---
--
--
----
---
=>Thisf unctionisusedf orcopyingthecontentofonel istobj
ecti
ntoanot
herl
i
st
object(shallowcopy )
=>Syntax:l i
stobj
2=li
stobj1.copy()
--
--
---
--
--
----
---
Exampl es:
--
--
---
--
--
----
---
>>>l1=[10, "
Rossum" ]
>>>pr i
nt(l1,
id(l
1))-
--
--
--
---[
10,'
Rossum' ]1957575199232
>>>l2=l1.copy ()#Shal l
owCopy
>>>pr i
nt(l2,
id(l
2))-
--
--
--
---[
10,'
Rossum' ]1957575198400
>>>l1.append( "Pyt
hon")
>>>l2.append( "DataSci")
>>>pr i
nt(l1,
id(l
1))-
--
--
--
[10,'Rossum','
Py t
hon']1957575199232
>>>pr i
nt(l2,
id(l
2))-
--
--
--
-[10,'
Rossum' ,
'DataSci']1957575198400

I
nnerl
i
st(
or)nest
edl
i
st

=>Theprocessofwr i
tingonel
istintoanot
herlistiscall
edInner/Nest
edl
i
st.
=>Synt
ax:[v al
1,v
al2,[val
11,
val12,v
al13.
..
..]
,
[val22,v
al23.
..
].
..
.,
val
-n]

Example:-
--
--
--
--
--
--
--
--
--
-
=>OnInnerli
st,wecanper form bothIndexi
ngandslici
ngoperat
ions.
=>OnInnerli
st,wecanappl yall
pre-defi
nedfunct
ionsofli
st.
>>>lst
=[10,
"Rossum" ,
[15,
18,
16],
[60,
65,55],
"OUCET"]
>>>pri
nt(l
st)
--
--
[10,'Rossum',
[15,18,16],[
60,65,
55],'
OUCET']
>>>pri
nt(l
st[
0])
---
--
-10
>>>pr
int(
lst[1])----
----Rossum
>>>pr
int(
lst[2])----
---[15, 18, 16]
>>>pr
int(
lst[2][0]) ----
----15
>>>pr
int(
lst[2][1]) ----
---18
>>>pr
int(
lst[2][2]) ----
----16
>>>pr
int(
lst[2][-1]) ---
-----16
>>>pr
int(
lst[2][-2]) ---
-----18
>>>pr
int(
lst[2][-3]) ---
------15
>>>pr
int(
lst[-3])---
-----[15, 18, 16]
>>>pr
int(
lst[-3][-1])---
-----16
>>>pr
int(
lst[-3][-2])---
-----18
>>>pr
int(
lst[-3][-3])---
--15
>>>pr
int(
lst[-3][:
:-1] )
---------
-[16, 18, 15]
>>>pr
int(
lst[3])----
----[60, 65, 55]
>>>pr
int(
lst[3].sor t())------None
>>>pr
int(
lst[3])----
-----[55, 60, 65]
>>>pr
int(
lst[4])----
----OUCET
>>>l
st[
2].append( 14) -----
--
>>>pr
int(
lst[2])----
----[15, 18, 16,14]
>>>l
st[
3].i
nser t(2. 58) ------Ty peEr ror:inser texpected2ar guments,
got1
>>>l
st[
3].i
nser t(2, 58) -----
--
>>>pr
int(
lst[3])----
--[55, 60, 58, 65]
>>>pr
int(
lst)---
---[10, 'Rossum' ,[15, 18, 16, 14],[
55,60,58,65],
'OUCET'
]
>>>l
st.
pop( 2) -
-----
-[15, 18, 16, 14]
>>>pr
int(
lst)---
----[10, 'Rossum' ,[55, 60, 58, 65]
,'
OUCET' ]
>>>l
st.
pop( -2)-----
--[55, 60, 58, 65]
>>>pr
int(
lst)---
-----[10, 'Rossum' ,'
OUCET' ]
>>>l
1=[18,16,14]
>>>l
2=[67,34,80]
>>>l
st.
insert(2,l1)
>>>pr
int(
lst)---
-----[10, 'Rossum' ,[18, 16, 14],'
OUCET']
>>>l
st.
append( l2)
>>>pr
int(
lst)---
--[10, 'Rossum' ,[
18, 16, 14] ,'
OUCET' ,
[67,34,80]]
2)t
upl
e

=>'
tupl
e'i
soneoft
hepr
e-def
inedcl
assandt
reat
edasLi
stcat
egor
ydat
aty
pe.

=>Thepurposeofli
stdat
atypei
sthat"Tost
oremul
ti
plevaluesei
therofsamet
ype
ordif
fer
enttypeorbotht
ypeswi
thUniqueandDupl
i
catesinsingl
eobject
".

=>Tostoret
heel ementsintuple,t
heelementsmustbewrit
ten(
or)encl
osedwi
thi
n
Braces()andt heel
ement smustbesepar at
edbycomma.
Syntax:
- varname=(val1,
val2,
..
..
,
val-
n)#Non- emptyt
upl
e
var
name=() #emptytupl
e
var
name=t upl
e() #empt ytuple

=>Anobjectoftupledatatypemaint
ainsinserti
onor der
.
=>Ontheobjectoftupl
e, wecanperform bothIndexingandSli
cingOper
ati
ons.
=>AnObjectoftuplebelongstoimmutable.
Note:
-TheFunct i
onali
tyoftupl
eisexactl
ysi mil
artoFuncti
onali
tyofl
ist
.Butan
obj
ectofli
stbelongstoMut abl
eandanobj ectoftuplebel
ongstoimmutabl
e.

Exampl es:
--
--
--
--
--
-----
---
>>>t1=( 10,20,10,34, 56, 20)
>>>print(t1,type(t1) )---
---
--
(10, 20,10, 34, 56,20)<cl ass'tuple'>
>>>t2=( 10,"KVR" ,33. 33,"Py t
hon" ,
True)
>>>print(t2,type(t2) )---
---
(10,'KVR', 33.33, '
Python',True)<cl ass'tupl
e'
>
>>>len(t1) -
---
6
>>>len(t2) -
---
5
>>>t3=( )#empt yt uple
>>>print(t3,type(t3) )---
---
-()<class'tupl e'
>
>>>t3=t uple()#empt yt uple
>>>print(t3,type(t3) )---
--(
)<class' tuple'>
>>>
>>>t4=10, "Trav i
s" ,
56. 78,"OUCET" ,
2+3j
>>>print(t4,type(t4) )---
---
(10,'Travis',56.78,'OUCET' ,(2+3j))<class't
upl
e'
>
>>>print(t4[0])--
---
- 10
>>>print(t4[1])--
---
Tr av i
s
>>>print(t4[-1])-
---
- -(
2+3j )
>>>print(t4[-2])-
---
- --
OUCET
>>>print(t4[2:5])-
-----(56.78, '
OUCET' ,(2+3j))
>>>print(t4[::
-1])-
------
((2+3j )
,'OUCET' ,56.78,'Tr
av i
s',10)
--
--
--
--
--
-----
---
---
----
--
------
---
---
----
--
>>>lst=[10,20, 30,40, "Python"]
>>>print(lst,
type( lst))--
---
[10,20, 30, 40, '
Python']<class'list'
>
>>>tpl=tuple( l
st )
>>>print(tpl,
ty pe(tpl))--
---
-(10, 20,30, 40, '
Python')<class' tupl
e'>
>>>lst1=list(tpl)
>>>pr
int
(l
st1,
type(
lst
1))
--
--
-[
10,
20,
30,
40,
'Py
thon'
]<cl
ass'
l
ist
'>

Pr
e-def
inedFunct
ionsi
ntupl
e

=>tuplecont ainstwopr e-
defi
nedf
unct
ions.Theyar
e
a)index()
b)count()
--
--
---
--
--
----
--
--
----
--
--
--
Exampl es:
--
--
---
--
--
----
--
--
----
--
--
--
>>>t1=( 10,
20, 10,
34,56,
20)
>>>t1.count( 10)-
--
--
2
>>>t1.count( 20)-
--
--
--2
>>>t1.index(10) -
--
--
--
0
>>>t1.index(56) -
--
--
--
4

=>t
upl
edoesnotcontainsthefol
l
owi
ngf
unct
ions.
a)append( )
b)insert(
)
c)remov e()
d)pop( i
ndex)
e)pop( )
f)copy (
)
g)sort()
h)reverse()
i
)extend( )
I
V)SetCat
egor
yDat
aTy
pes(
Col
l
ect
ionsDat
aTy
pe)

=>ThepurposeofSetCat egoryDataTy pesist hat"Tost


oremult
ipl
eval
uesei
therof
samet ypeordiff
erenttypeorbot hty
peswi thUniqueVal
uesinsi
ngle
object
(Dupli
catevaluesarenotal l
owed) ."
=>SetCategoryDatacont ai
nst wodatat ypes.Theyare
1)set( Mut able&Immut able)
2)f r
ozenset( I
mmut able)

1)set

=>'
set 'isoneoft hepr e-defi
nedcl assandt r
eat edasSetCat egoryDat aTy pe.
=>Thepur poseofsetdat atypei sthatTost or
emul ti
plev alueseit
herofsamet y
pe
ordifferentt ypeorbot htypeswi thUni queVal uesi nsingl eobject(Duplicateval
ues
arenotal l
owed) ."
=>Theel ement sofsetmustbewr i
ttenwi t
hincur lybraces{}andel ement s
separ atedbycomma.
=>Sy ntax:- set obj={Val1,Val
2. .
.Val-n}#non- empt yset
setobj=set () #empt yset
=>Anobj ectofsetnev ermai ntainsi nsert
ionor der.Inot herwords,what everthe
el
ement swear eor gani zi
ngint heobj ectofset, t
hoseel ement scanbedi spl
ayedin
anyor deroutofi tsmanypossi bili
ties.
=>Ont heobj ectofset, wecan'tper formI ndexingandsl icingOper ati
onsbcozset
objectnev ermai ntainI nsert
ionOr der .
=>Anobj ectofsetbel ongst obot hImmut able('set'objectdoesnotsuppor ti
tem
assignment )andmut abl e(inthecaseadd( )).

Exampl es:
--
--
--
--
--
----
---
--
>>>s1={ 10,20,30,40,50,
60,10,100}
>>>print(s1,type(s1))-
--
--
--
--
--{50, 100, 20,40,10,60,
30}<class'set
'>
>>>s2={ 10,"KVR" ,
33.33,"
Python" ,True}
>>>print(s2,type(s2))-
--
--
--
--
-{33.33, 'Python'
,True,'
KVR',
10}<class'set
'>
>>>
>>>s4=set ()#empt yset
>>>print(s4,type(s4))-
--
--
--
--
set (
)<cl ass' set
'>
>>>len(s4)----
---
--
0
>>>len(s1)----
---
--
-7
>>>s5={ }#notempt ysetbuti tisdi ct
>>>print(s5,type(s5))-
--
--
--
-{}<class' dict'
>
>>>s1={ 10,20,30,40,50,
60,10,100}
>>>print(s1[0])-
--
---
-TypeError:'
set 'objectisnotsubscri
ptable
>>>print(s1[0:6])
---
--
-TypeError:'set'objectisnotsubscri
ptable
>>>
>>>s1[
0]=100--
--
TypeError:'
set'objectdoesnotsupportit
em assi
gnment
>>>pri
nt(
s1,i
d(s1)
)-
--
-{50,100, 20,40,10,60,30}2190683253088
>>>s1.
add("HYD")
>>>pri
nt(
s1,i
d(s1)
)-
--
{50, 100,20,'HYD',40,10,60,
30}2190683253088

>>>s1={10,10,
10,
10,
10,10}
>>>pri
nt(s1,t
ype(
s1))
--
--
--
--
--
{10}<cl
ass'set
'>
============================X=============================

pr
e-def
inedf
unct
ionsset

=>Ont heobjectofsetwecanper f
or mv ari
ousoper at
ionsbyusi ngpr e-
def
ined
funct
ionspresenti nset.Theyar e
--
--
--
--
--
---
--
--
--
----
-----
--
--
---
--
--
--
--
--
1)add():
--
--
--
--
---
=>Thisfunctioni susedf oraddi ngt heelement stothesetobj ect.
=>Syntax:
- set obj.
add(Value)
--
--
--
--
--
---
--
-
Examples:
--
--
--
--
--
---
-
>>>s1={10,"KVR" }
>>>print(
s1,type( s1),
id(
s1))-
---
---{10, '
KVR'}<class' set
'>2190683253088
>>>s1.add("Py thon")
>>>s1.add(45. 67) -
--
--
--
>>>print(
s1,type( s1),
id(
s1))-
---
{'
Py thon',10,45.67, '
KVR'}<class'set'
>
2190683253088
>>>s1.add("sat i
sh" )
>>>print(
s1,type( s1),
id(
s1))-
--{
'Py thon',10,45.67, '
KVR','sat
ish'}<cl
ass'set
'>
>>>s2=set()#empt yset
>>>print(
s2,type( s2),
id(
s2))-
---
--set ()<cl
ass' set'>2190683254432
>>>s2.add(100)
>>>s2.add(200)
>>>s2.add(100)
>>>s2.add("Django" )
>>>print(
s2,type( s2),
id(
s2))-
---
--{200, 'Dj
ango' ,100}<class'set'
>2190683254432

2)cl
ear
():
--
--
--
--
--
-----
--
-
=>Thisf uncti
onisusedf orremvoi
ngalltheelementsofsetobj
ectandmakesempt
y
setobject.
=>Syntax:-set obj.
clear()
--
--
--
--
--
-----
-
Exampl es:
--
--
--
--
--
-----
-
>>>s1={ 10,"
Rossum" ,
"Python",
45.
67,
True,2+3j}
>>>print(s1,
type(s1),
id(s1))-
--
{'
Pyt
hon'
,True,'Rossum'
,10, (
2+3j
),45.
67}
<cl
ass' set'
>2190683252640
>>>len(s1)--
--
---
--
6
>>>s1.clear()
>>>print(s1,
type(s1)
,i
d(s1)
)-
--
--
-set
()<cl
ass'
set
'
>2190683252640
>>>len(s1)--
--
--0

3)copy
():
--
--
---
--
--
---
-
=>ThisFunct ionisusedf orcopy i
ngt hecontentofonesetobjectobjectintoanother
setobject(I mplement ingShal l
owCopy)
=>Syntax:- set obj2=setobj1.
copy ()
--
--
---
--
--
---
---
--
Exampl es:
--
--
---
--
--
---
---
--
>>>s1={ 10,"
Rossum" ,
"Python",45.67,Tr
ue,2+3j}
>>>pr i
nt(s1,
type( s1)
,i
d(s1))--
-{
'Python',Tr
ue,'Rossum'
,10,(2+3j)
,45.67}<cl
ass'set'
>
2190683253088
>>>s2=s1. copy ()#shal l
owCopy
>>>pr i
nt(s2,
type( s2)
,i
d(s2))--
-{
'Python',Tr
ue,'Rossum'
,10,(2+3j)
,45.67}<class'set'
>
2190683253984
>>>s1. add("
Jav a")
>>>s2. add("
Dj ango")
>>>pr i
nt(s1,
type( s1)
,i
d(s1))--
-{
'Python',Tr
ue,'Rossum'
,'Jav
a',10,(2+3j
),45.67}
>>>pr i
nt(s2,
type( s2)
,i
d(s2))--
--
{'Python'
,True,'
Django'
,'
Rossum' ,
10, (
2+3j),
45.67}<class'set'
>2190683253984
--
--
---
--
--
---
---
--
--
----
--
---
--
--
-
DeepCopyExampl
es:
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
>>>s1={10,"
Rossum","Python",
45.67}
>>>pri
nt(s1,
type(
s1),
id(s1))-
-{
'Python',10,'Rossum',45.
67}<class' set
'>
>>>s2=s1#DeepCopy
>>>pri
nt(s2,
type(
s2),
id(s2))-
--
---
--
{'
Py thon'
, 10,'
Rossum',45.67}<class'set'
>
>>>s1.add("
Django")
>>>pri
nt(s1,
type(
s1),
id(s1))-
--
{'
Py thon','
Django','
Rossum',10,45.67}<class'set'
>
>>>pri
nt(s2,
type(
s2),
id(s2))-
--
-{'
Pyt hon'
,'
Dj ango'
,'
Rossum',10,45.67}<cl ass'set
'>
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
---
--
---
--
--
---
--
-----
--
--
--
--
----
--
--
--
--
--
--
--
--
--
--
-
4)r
emov
e():
--
--
---
--
--
--
--
---
=>Thisfunctioni
susedforremovingt
heelement
/keyf
rom setobj
ect.
=>Iftheelementdoesnotexist
sinsetobj
ectt
henwegetKey t
Err
or.

=>Syntax:-set obj.
remov e(
element/key )
--
--
--
--
--
----
--
Exampl es:
--
--
--
--
--
----
--
>>>s1={ 10,"
Rossum" ,"
Py t
hon",
45.67}
>>>pri
nt (s1)-
--
---
--
--
-{'
Python'
,10,'
Rossum',45.
67}
>>>s1.remov e("Python")
>>>pri
nt (s1)-
--
---
--
-{
10, '
Rossum',45.67}
>>>s1.r
emov e(45.67)
>>>pri
nt(s1)---
--
---
{10,'
Rossum' }
>>>s1.r
emov e("Rossum" )
>>>pri
nt(s1)---
--
---
--
{10}
>>>s1.r
emov e(10)
>>>pri
nt(s1)---
--
---
set()
>>>s1={10,"Rossum" ,"
Python",45.67}
>>>pri
nt(s1.remov e(1000))-
--
--KeyError:
1000
>>>set()
.remov e(10)--
--
--
--
Key Error:10
--
--
--
--
--
--
--
----
--
---
--
---
--
--
---
--
--
--
--
--
----
--
---
--
---
--
--
--
--
--
--
--
--
--
--
--
5)di
scar
d()
:
--
--
---
---
--
---
---
=>Thisf unctionisusedf orremovinganspecif
iedel
ementf
rom setobj
ect
.
=>ifthespeci fi
edel ementdoesnotexi stinsetobj
ect
,wenevergetKey
Err
or.
=>Syntax: - setobj.di
scar d(Val
ue)
--
--
---
---
--
---
-
Exampl es:
--
--
---
---
--
---
-
>>>s1={ 10,"Rossum" ,
"Python",
45.
67}
>>>pr i
nt(s1)---
--
--{
'Python',10,45.
67,'
Rossum'}
>>>s1. discard(10)
>>>pr i
nt(s1)---
--
-{'
Py t
hon',45.67,'
Rossum'}
>>>s1. discard("Rossum" )
>>>pr i
nt(s1)---
--
-{'
Py t
hon',45.67}
>>>s1. discard(100)#noer r
or

6)pop(
):
--
--
--
--
---
----
=>Thisf unctionisusedf orremovinganyar
bit
aryel
ementpr
ovi
dedel
ementpr
esent
i
nset obj otherwisewegetKey Err
or
=>Syntax:-set obj.
pop( )
--
--
--
--
---
---
Exampl es:
--
--
--
--
---
----
>>>s1={ 10,"Rossum" ,
"Python"
,45.67}
>>>s1.pop( )---
--
--
'Python'
>>>s1.pop( )---
--
--
-10
>>>s1.pop( )---
--
-45.67
>>>s1.pop( )---
--
--
'Rossum'
>>>s1.pop( )---
-KeyError:'
popf r
om anemptyset'

7)i
sdi
sjoi
nt(
):
--
--
--
--
--
---
--
--
---
-
=>Thisfuncti
onretur
nsTr ueprovi
dedthetwoset
sar
edi
sjoi
nt(
ther
ear
eno
commonel ements)otherwiseret
urnsFal
se.
=>Syntax:
- setobj1.i
sdisj
oint
(set
obj2)

Examples:
-
---
--
--
--
--
--
--
>>>s1={10,20,30,40}
>>>s2={"apple",
"banana" ,
"kiwi
"}
>>>s3={10,"apple",
20,"ki
wi "
}
>>>pri
nt(s1)--
---
--
{40, 10,20,30}
>>>pri
nt(s2)--
---
--
--{
'apple'
,'ki
wi'
,'
banana'
}
>>>pri
nt(s3)--
---
--
--{
'apple'
,10,20,'
ki
wi'}
>>>
>>>s1.
isdisjoint
(s2) -
---
--
True
>>>s1.
isdisjoint
(s3) -
---
--
False

8)i
ssuper
set
():
--
--
--
---
--
----
--
--
--
--
---
Syntax:
-set obj1.i
ssuper set(setobj
2)
=>Thisf uncti
onr eturnsTr uepr ovi
dedsetobj1contai
nsallt
heel
ement
sofset
obj
2
otherwiseitreturnsFal se.
--
--
--
---
--
----
--
Exampl es:
--
--
--
---
--
----
--
>>>s1={ 10,20,
30,40}
>>>s2={ 10,20}
>>>s3={ 10,20,
50,60}
>>>s1.issuperset (
s2) -
--
---
-True
>>>s1.issuperset (
s3) -
--
---
False
--
--
--
---
--
----
--
--
--
--
----
--
---
---
--
--
---
--
----
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
9)i
ssubset
():
--
--
--
---
--
---
--
--
--
Syntax:
- set obj1.i
ssubset(set
obj2)
=>ThisFunctionr et
urnsTr ueprovi
dedalltheelementsofset
obj
1pr
esenti
nset
obj
2.
OtherwisewegetFal se.
Exampl es:
--
--
--
---
--
---
>>>s1={ 10,
20,30,40}
>>>s2={ 10,
20}
>>>s3={ 10,
20,50,60}
>>>
>>>s1.issubset(s2)-
---
--
--
False
>>>s2.issubset(s1)-
---
--
--
True
>>>s3.issubset(s1)-
---
--
False
--
--
--
---
--
---
--
--
--
--
---
---
--
--
---
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
-
10)uni
on(
):
--
--
--
---
--
---
--
-
Syntax:
- set obj 3=set
obj1.
union(
set
obj2)
=>ThisFunct iont akesallt
heelementsofsetobj
1andset
obj
2andcol
l
ect
suni
que
el
ement sthepl acet hem i
nsetobj3
--
--
--
---
--
---
-
Exampl es:
--
--
--
---
--
---
-
>>>s1={ 10,20,30,40}
>>>s2={ 10,50,60,70}
>>>s3=s1.union(s2)
>>>pri
nt(s3)-
---
--
---
{70,40,10,50,20,60,30}
--
--
--
--
--
--
--
---
--
--
---
--
---
--
--
--
---
--
--
--
--
--
--
--
---
--
--
--
--
---

11)i
nter
sect
ion(
):

Sy
ntax:set
obj
3=set
obj
1.i
nter
sect
ion(
set
obj
2)

=>Thi
sFuncti
ontakest
hecommonel
ement
sfr
om set
obj
1andset
obj
2andpl
ace
them i
nset
obj3.

Examples:
--
--
--
--
--
--
--
---
>>>s1={10,20,30,40}
>>>s2={10,50,60,70}
>>>s3=s1.intersecti
on(s2)
>>>pri
nt(s3)--
---
---
--
-{10}
>>>s1={10,20,30,40}
>>>s2={60,70,50,80}
>>>s3=s1.intersecti
on(s2)
>>>pri
nt(s3)--
---
---
--
-set(
)
>>>
>>>s1={10,20,30,40}
>>>s2={50,60,10,70}
>>>s3={10,70,80,90}
>>>s4=s1.intersecti
on(s2).
inter
secti
on(s3)
>>>pri
nt(s4)--
---
---
-{
10}
--
--
--
--
--
--
--
---
---
--
---
---
--
---
--
--
--
--
--
---
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
12)di
ff
erence(
):

Syntax:
- set obj3=setobj1.di
ffer
ence(
setobj2)
=>ThisFuncti
onremov esthecommonel ementsfr
om setobj1andsetobj2andtakes
remaini
ngelementsf r
om set obj1andplacethem i
nsetobj3
(
OR)
Syntax:
- set obj3=setobj2.di
ffer
ence(
setobj1)
=>ThisFuncti
onremov esthecommonel ementsfr
om setobj2andsetobj1andtakes
remaini
ngelementsf r
om set obj2andplacethem i
nsetobj3
=>hencesetobj1.
dif
ference(setobj
2)isnotequaltoset
obj2.dif
fer
ence(set
obj1)

--
--
--
--
--
--
--
Examples:
--
--
--
--
--
--
--
>>>s1={10,
20,
30,
40}
>>>s2={30,
40,
50,
60}
>>>s3=s1.
dif
fer
ence(s2)
>>>pri
nt(
s3)-
--
--
-{
10,20}
>>>s4=s2.
dif
fer
ence(s1)
>>>pri
nt(
s4)-
--
--
--
{50,60}

13)sy
mmet
ri
c_di
ff
erence(
):
--
--
--
---
--
----
--
--
----
---
---
---
---
--
---
Syntax:
- set obj3=set obj1.symmet r
ic_di
fference(setobj2)
=>Thisf unctionr emov est hecommonel ement sf r
om set obj1andsetobj
2andtakes
all
ther emai ningel ement sf r
om bothsetobj1andset obj2andpl acet
hem inset
obj3.
--
--
--
---
--
----
-
Exampl es:
--
--
--
---
--
----
-
>>>s1={ 10,20,30,40}
>>>s2={ 30,40,50,60}
>>>s3=s1.sy mmet ric_diff
erence(s2)
>>>print(s3)---
---
--{
10, 50,20, 60}
>>>s3=s2.sy mmet ric_diff
erence(s1)
>>>print(s3)---
---
--{
10, 50,20, 60}
--
--
--
---
--
----
--
--
----
---
---
---
---
--
---
--
---
--
--
--
--
---
--
--
--
--
---
--
---
--
---
--
--
---
--
---
--
---
--
--
--
--
--
--
---
--
----
--
--
UseCase:
--
--
--
--
--
--
---
--
--
Letconsiderthefol
l
owingproblem
cri
cketplayer
s={"
Sachi
n","
Kohli
",
"Rohi
t"}
Tennisplayer
s={"
Rohit
",
"Ram","
Sindu"
}

Q1)Fi
ndal
lthepayer
swhoarepl
ayi
ngeitherCr
icketortenni
sorall
Q2)Fi
ndal
lthepl
ayerswhoar
eplay
ingboththegames.
Q3)Fi
ndal
lthepl
ayerswhoar
eplay
ingOnlyCri
cketbutnottennis
Q4)Fi
ndal
lthepl
ayerswhoar
eplay
ingOnlyTennisbutnotCricket
Q5)Fi
ndal
lthepl
ayerswhoar
eexcl
usiv
elyPlayi
ngeitherCri
cketorTenni
s
==========================================================
Solvi
ng:
--
--
--
--
--
---
Q1)Findal lthepay er swhoar epl ayingei therCricketortenni
sorall
ANS:>>>cr icket={"Sachi n","
Kohl i",
"Rohi t"
}
>>>t ennis={"Rohi t",
"Ram" ,
"Sindu" }
>>>pr int(
cricket)----
----
-{'
Rohi t
','Sachin',
'Kohli
'
}
>>>pr int(
tenni s)--
---
----
{'
Sindu' ,'
Ram' ,'Rohit
'}
>>>al lpl
ayer s=cricket .
union( tennis)
>>>pr int(
allplayers)-----
-{
'Sachi n','
Sindu','
Ram','
Rohit
',
'Kohl
i
'}
--
--
--
--
--
----
---
------
---
--
--
---
----
--
----
----
---
--
---
---
----
---
---
--
--
---
---
--
--
--
-
Q2)Findal lthepl ayer swhoar eplay i
ngbot hthegames.
ANS:-
>>>cricket ={"Sachin" ,
"Kohl i"
,"Rohit"
}
>>>tennis={ "Rohi t"
,"
Ram" ,"Sindu"}
>>>print(cricket )-
--
--
---{'
Rohi t'
,'Sachin','Kohli'
}
>>>print(tenni s)--
--
--
{'Sindu' ,
'Ram' ,'
Rohi t'
}
>>>bot hplay ers=cricket .
intersect i
on( tennis)
>>>print(bot hplayers)---
---
-{'
Rohi t'
}

Q3)Findalltheplayerswhoar epl
ayi
ngOnlyCri
cketbutnott
enni
s
ANS:
--
--
--
-
>>>cri
cket={"Sachi
n",
"Kohli"
,"Rohi
t"
}
>>>tennis={
"Rohit"
,"
Ram" ,"
Sindu"}
>>>print
(cri
cket)-
--
--
--
--{
'Rohit
','
Sachi
n'
,'
Kohl
i'
}
>>>print(tenni s)--
--
----{'
Sindu' ,'Ram' , '
Rohi t
'
}
>>>only cri
cket =cri
cket .
diff
er ence( t
enni s)
>>>print(onl ycricket)----
--
-{'
Sachi n','
Kohl i'
}
--
--
--
--
--
-----
---
----
----
--
---
-----
--
----
-----
---
-----
----
---
----
--
---
---
--
--
--
--
--
--
Q4)Findal lthepl ay erswhoar epl ay i
ngOnl yTenni sbutnotCricket
ANS:
--
--
--
-
>>>cri
cket ={"Sachi n","Kohli","Rohi t"
}
>>>tenni s={"Rohi t"
,"Ram" ,"
Si ndu" }
>>>print(cricket )-
--
----{'
Rohi t
', '
Sachi n' ,'
Kohl i'
}
>>>print(tenni s)--
--
---{'
Sindu' ,'Ram' ,'
Rohi t'
}
>>>only tennis=t enni s.dif
ference( cricket )
>>>print(onl ytennis) -
----
-{
'Sindu' ,'Ram' }
--
--
--
--
--
-----
---
----
----
--
---
-----
--
----
-----
---
-----
----
---
----
--
---
---
--
--
--
--
--
Q5)Findal lthepl ay erswhoar eexcl usiv el
yPl ayi
ngeitherCr
icketorTenni
s
ANS:
--
--
--
--
>>>cri
cket ={"Sachi n","Kohli","Rohi t"
}
>>>tenni s={"Rohi t"
,"Ram" ,"
Si ndu" }
>>>print(cricket )-
--
-----
---
{'Rohi t',
'Sachi n'
, '
Kohli'}
>>>print(tenni s)--
--
----{'
Sindu' ,'Ram' , '
Rohi t
'
}
>>>cri
t en=cr icket.sy mmet ric_ dif
f erence( t
ennis)
>>>print(criten) -
--
---
-{'Sachin' ,'Kohl i
','Sindu','
Ram' }
(
OR)
>>>cri
t en=t enni s.
sy mmet r
ic_ difference( cri
cket)
>>>print(criten) -
--
---
-{'Sachin' ,'Kohl i
','Sindu','
Ram' }
--
--
--
--
--
-----
---
----
----
--
---
-----
--
----
-----
---
-----
----
---
----
--
---
---
--
--
--
--
--

--
--
--
--
--
--
---
--
---
--
--
---
---
---
--
--
--
---
--
---
--
---
--
UseCase:Sol v
ing Bi twiseOper ator
s
--
--
--
--
--
--
---
--
---
--
--
---
---
---
--
--
--
---
--
---
--
---
--
Letconsiderthef ol
lowingpr oblem
cri
cketplayers={"Sachin"
,"Kohli
",
"Rohi
t"}
Tennisplayers={"Rohit
","
Ram" ,"
Sindu"
}

Q1)Fi
ndal
lthepayer
swhoarepl
ayi
ngeitherCr
icketortenni
sorall
Q2)Fi
ndal
lthepl
ayerswhoar
eplay
ingboththegames.
Q3)Fi
ndal
lthepl
ayerswhoar
eplay
ingOnlyCri
cketbutnottennis
Q4)Fi
ndal
lthepl
ayerswhoar
eplay
ingOnlyTennisbutnotCricket
Q5)Fi
ndal
lthepl
ayerswhoar
eexcl
usiv
elyPlayi
ngeitherCri
cketorTenni
s

>>>cri
cket={"Sachin",
"Kohl
i"
,"Rohit
"}
>>>tennis={
"Rohit"
,"Ram","
Sindu"}
>>>all
players=cri
cket| t
ennis--
--
--
--
--
--
--
--
ANS--Q1
>>>print
(all
player
s) -
--
--
--
{'
Sachin',
'Si
ndu'
,'Ram',
'Rohi
t'
,'
Kohl
i
'}

>>>bothplay
ers=cri
cket&tennis--
--
--
-ANS-
-Q2
>>>pri
nt(bot
hplayer
s)--
--
--
-{
'Rohit
'
}
>>>onl
ycri
cket=cri
cket-
tennis-
--
---
ANS- -
-Q3
>>>pri
nt(
only
cricket
)--
--
--
-{'
Sachin'
,'Kohli
'}

>>>onl
ytenni
s=tenni
s-cri
cket
---
--
--
ANS--
-Q4
>>>pri
nt(
only
tennis)
--
---
--
-{
'Si
ndu',
'Ram'
}

>>>cr
iten=tenni
s^cri
cket
--
--
--
--
ANS--Q5
>>>pr
int(cr
iten)
--
--
--
{'
Sachi
n',
'Kohl
i
','
Sindu'
,'
Ram'
}

f
rozenset
=>'fr
ozensetisoneoft hepre-
definedclassandt r
eatedasSetCategoryDataTy pe.
=>Thepur poseoff r
ozensetdataty peist
hatTost oremulti
pleval
ueseitherofsame
typeordiffer
enttypeorbotht y
peswi t
hUniqueValuesinsingl
eobject(Dupli
cate
valuesarenotall
owed) ."
=>Wedon' thaveanysy mbolicNot ati
onforstori
ngtheelementsinfr
ozensetbutwe
canconv ertanytuple,
li
st,settypeelementst ofr
ozensetbyusingfr
ozenset()
.

=>Sy
ntax:
- f
rozenset
obj=f
rozenset
({Val
1,Val
2..
.Val
-n})
or
fr
ozensetobj
=fr
ozenset([
Val
1,Val
2..
.Val
-n])
or
fr
ozensetobj
=fr
ozenset((
Val
1,Val
2...
Val
-n))

=>Anobj ectoffr
ozensetnev ermaint
ainsinserti
onor der
.Inot herwords,
what ev
er
theelement sweareor ganizi
ngintheobjectoffrozenset,thoseel ementscanbe
displ
ayedi nanyorderoutofi tsmanypossibi
li
ties.
=>Ont heobjectoffrozenset,wecan'tperfor
mI ndexingandsl icingOperat
ionsbcoz
setobjectnevermaintainInserti
onOrder.
=>Anobj ectoffr
ozensetbel ongstoImmut able('f
rozenset
' objectdoesnotsupport
i
tem assignment).

=>Note:
-TheFunctionali
tyoffr
ozenseti
sexact
lysi
milartot
hefunct
ional
i
tyofset
butanobjectofsetbelongsbothMutabl
eandimmut ablewher
easanobjectof
fr
ozensetbelongstoimmut abl
eonly.

Examples:
--
--
--
--
--
--
--
---
---
--
>>>s1={10,20,"Ram" ,
"Python",
34. 56}
>>>pri
nt(s1,type(s1) )
---
--
{34.56, 20,'
Ram' ,
10, '
Py t
hon'}<cl ass'set '
>
>>>fs1=frozenset (s1)
>>>pri
nt(fs1,t
y pe(fs1))-
--fr
ozenset ({
34.56, 20,'Ram',10, 'Python'})
<cl ass ' frozenset'
>
>>>pri
nt(fs1[0])-
--
-Ty peError:'
frozenset 'objectisnotsubscr iptable
>>>fs1[
0]=100- --
Ty peError:'f
rozenset 'objectdoesnotsuppor titem assignment
>>>fs1.
add( 100) -
--Attri
buteError:'f
rozenset 'objecthasnoat tr
ibute'add'
>>>lst
=[10,10,20,30, "
KVR" ,
"Python" ,
True]
>>>pri
nt(l
st,type(l
st ))
---
[10,10,20, 30,'KVR' ,'
Python',
Tr ue]<cl ass'li
st'
>
>>>fs2=frozenset (l
st)
>>>pri
nt(fs2,t
y pe(fs2))-
--fr
ozenset ({
True, 10,'Python'
,20, '
KVR' ,30})<class
'f
rozenset '
>
>>>tpl
=(10,10,20,30, "
KVR" ,
"Python" ,
True)
>>>pri
nt(tpl,
type(tpl))-
--
-(10,10, 20,30,'KVR' ,'
Python'
, True)<cl ass'tuple'
>
>>>fs3=frozenset (tpl
)
>>>pri
nt(fs3,t
y pe(fs3))-
--fr
ozenset ({
True, 10,'Python'
,20, '
KVR' ,30})<class
'
fr
ozenset '>
=========================X==========================

pr
e-def
inedf
unct
ionsi
nfr
ozenset
=>Thefol
lowingarepr e-definedf uncti
onsi
nf rozenset
a)copy (
)
b)isdisjoint()
c)issuper set (
)
d)issubset ()
e)uni on()
f)i
nt ersection()
g)difference( )
h)sy mmet ric_di
ffer
ence(
)
=>Thefol
lowingpre-def i
nedf uncti
onsnotpresentinfr
ozensetbcozanobj
ectof
fr
ozensetispurel
yImmut abl e.
a)add( )
b)clear (
)
c)remov e()
d)pop( )
f)discard( )

VI
)NoneCat
egor
yDat
aTy
pe

=>Thiscont
ainsclassnameas" NoneType"
=>ThevalueofNoneTy peisNone
=>Noneisapr e-
definedVal ueforNoneTy pedat atype
=>AnobjectofNoneTy pecan' tbecreatebcozi tcontai
nssi
ngleval
uecalledNone.
=>ThevalueNonei snotaFal se,space,empt y.HenceNonei ssel
fist
hev al
ue.
=>Ifwewanttomaket heobj ectandwhosememor yspacetodestroy/removeby
theGarbageColl
ectort henwhoseobj ectv al
uemustbemadeasNone.
=>IfaFuncti
onisnotr etur
ninganyv aluethenitsvalueisNone.

Examples:
--
--
--
--
--
---
--
-
>>>d1={10:3.4,
20:4.5,30:6.7,40:3.4}
>>>val=d1.get(
10)
>>>pri
nt(val)
---
---
3.4
>>>pri
nt(type(val
))-
---
---
---
--<class'float'>
>>>val=d1.get(
20)
>>>pri
nt(val,t
ype(val))-
---
----
4.5<cl ass' f
loat
'>
>>>val=d1.get(
200)
>>>pri
nt(val,t
ype(val))-
---
--None <cl ass'NoneType'
>
>>>
>>>
>>>None=23. 45---
--
---
---
Sy ntaxError: cannotassigntoNone
>>>True=23----
---
--
--
-SyntaxEr ror:cannotassi gntoTrue
>>>False=34---
---
--
--
Sy ntaxEr r
or :cannotassi gntoFalse

>>>n1=NoneType(
)--
--
--
--
-NameEr
ror
:name'
NoneTy
pe'
isnotdef
ined
>>>None==Fal
se--
--
--
--
--
False
>>>None==""
--
--
--
--
--
--
Fal
se

Myr equir
ement
--
--
--
---
--
--
--
--
---
Iwantt ostorestno, name, i
nter
nal
mar
ks(
sub1,
sub2,
sub3)
,Ext
Marks(sub1,sub2,sub3)col
l
egnename

[
10,
"Rossum"
,15,
20,
18,
606555,
'
OUCET"]
--
-nopr
operar
ragement

[
10,
"Rossum"
,[15,
20,
30]
,[
60,
65,
55]
,
"OUCET"
]

r
ever
se(
) sor
t() ext
end(
)

Ty
peCast
ingTechni
quesi
nPy
thon

=>Thepur poseofTypeCast i
ngTechniquesinPyt
honisthat"Toconv
ertOne
Possi
bleTy peofValueintoAnotherPossibl
eTypeofValue"
.
=>I
nPy thonProgrammi ng,wehave5f i
veFundamentalTypeCast
ingt
echni
ques.
Theyare.
1)int()
2)float(
)
3)bool()
4)compl ex(
)
5)str()

1)i
nt(
)
=>int(
)i susedconv erti
ng" AnyPossi bleTy peValuei
ntoi
ntt
ypev
alue"
.
=>Syntax:- v arname=int(f loat/bool /compl ex/st
r)
--
--
--
--
--
----
---
---
---
---
--
--
--
--
---
--
----
----
----
---
---
--
--
--
Exampl es:-)(floatValue--
-->i ntv alue--
->Possi bl
e)
--
--
--
--
--
----
---
---
---
---
--
--
--
--
---
--
----
----
----
---
---
--
--
--
>>>a=10. 24
>>>print(a, t
ype(a))-
--
---
--
10. 24<cl ass'fl
oat'>
>>>b=int (
a)
>>>print(b,type(b))
--
--
---
--
--10<cl ass' i
nt'
>
>>>a=0. 99
>>>print(a, t
ype(a))-
--
---
--
-0.99<cl ass'float'
>
>>>b=int (
a)
>>>print(b,type(b))
--
--
---
--
--0<cl ass'int'
>
--
--
--
--
--
----
---
---
---
---
--
--
--
--
---
--
----
----
----
---
---
--
--
-
Exampl es:-(bool Value--
-->intv alue--
->Possible)
--
--
--
--
--
----
---
---
---
---
--
--
--
--
---
--
----
----
----
---
---
--
--
--
>>>a=Tr ue
>>>print(a, t
ype(a))-
--
---
--
----
Tr ue<cl ass' bool'
>
>>>b=int (
a)
>>>print(b,type(b))
--
--
---
--
--1<cl ass'int'
>
>>>a=Fal se
>>>print(a, t
ype(a))-
--
---
--
--False<cl ass'bool'>
>>>b=int (
a)
>>>print(b,type(b))
--
--
---
--
-0<cl ass' i
nt'
>

--
--
--
---
--
---
---
--
--
---
--
---
--
--
--
--
--
--
--
---
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
-
Exampl es:-(Compl exValue--
--
>intvalue-
--
>NotPossibl
e)
--
--
--
---
--
---
---
--
--
---
--
---
--
--
--
--
--
--
--
---
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
>>>a=2. 3+4.5j
>>>print(a,type(a)
)--
--
--
--
(2.
3+4.5j)<cl
ass'complex'
>
>>>b=int (
a)--
---
--
TypeError:
int(
)argumentmustbeast r
ing,
aby
tes-
li
keobj
ectora
realnumber ,not'complex'

Examples:-(StrValue---
->i
ntv alue)POSSIBLE
--
--
--
--
--
--
--
---
--
---
---
---
--
--
---
--
--
--
--
---
---
---
--
--
--
--
--
--
--
---
--
--
--
--
>>>a="100"#i tisaintstr
>>>pri
nt(a,t
ype( a)
)--
---
--
--
--
100<cl ass'str
'>
>>>a=a+1- -
--
--
---
-TypeError:canonl yconcatenat
estr(
not"
int
")t
ost
r
>>>b=int
(a)#POSSI BLE
>>>pri
nt(b,type(b))-
---
100<cl ass'i
nt'
>
>>>b=b+1
>>>pri
nt(b,type(b))-
---
101<cl ass'i
nt'
>

>>>a="KVR"#i tispurest r
>>>pri
nt(a,t
ype( a))
--
--
--
KVR<cl ass'str'
>
>>>b=int(a)-
--
--
-ValueError:i
nvalidli
teralforint(
)wit
hbase10:'
KVR'
--
--
--
--
--
---
--
---
--
--
---
---
--
--
--
--
---
---
--
---
--
---
--
-
>>>a="12.34"#i tisfloatstr
>>>pri
nt(a,t
ype( a))
--
--
--
---
-12.34<class' str
'>
>>>b=int(a)-
--
-ValueError:i
nvalidli
teralforint(
)wit
hbase10:'
12.
34'
--
--
--
--
--
--
--
---
--
--
--
--
----
----
--
--
--
---
--
--
--
---
--
--
---
----
--
--
>>>a="True"#i ti
sbool str
>>>pri
nt(a,
type(a))---
--
--
--
-True<class' str
'>
>>>b=int
(a)--
--
--
-Val ueErr
or:inval
idliteralforint
()wi
thbase10:
'Tr
ue'
--
--
--
--
--
--
--
---
--
--
--
--
----
----
--
--
--
---
--
--
--
---
--
--
---
----
--
---
--
--
---
--
-
>>>a="2+3j"#iti scompl exst r
>>>pri
nt(a,
type(a))---
--
--
--
-2+3j<class' str
'>
>>>b=int
(a)--
--
--
Val ueError:i
nvali
dl i
teralforint(
)wit
hbase10:'
2+3j'

2)f
loat
()
=>fl
oat(
)isusedconv
ert
ing"AnyPossi
bleTypeVal
ueint
ofl
oatt
ypev
alue"
.
=>Sy
ntax:
- v ar
name=fl
oat(i
nt/bool/complex/
str)

Example(intvalue--
->fl
oat--
->Possibl
e)
--
--
--
--
--
--
--
---
--
--
--
--
---
--
--
---
--
---
--
--
---
--
--
--
--
---
--
--
--
--
-
>>>a=12
>>>pri
nt(a,
type(
a))--
---
--
-12<class'i
nt'>
>>>b=fl
oat(a)
>>>pri
nt(b,
type(b))
--
---
--
12.0<class'fl
oat'
>

Exampl
e(bool
val
ue-
--
>fl
oat
--
->Possi
ble)

>>>a=Tr ue
>>>pri
nt (a,t
ype(a))-
----
--True<cl ass'bool '
>
>>>b=float (
a)
>>>pri
nt (b,t
ype(b))--
---
---1.0<class' f
loat '
>
>>>a=Fal se
>>>pri
nt (a,t
ype(a))-
----
-False<cl ass'bool '>
>>>b=float (
a)
>>>pri
nt (b,t
ype(b))--
---
--0.0<class' fl
oat '
>
--
--
--
--
--
--
-----
--
---
--
--
---
--
----
-----
--
---
--
--
---
---
--
-----
--
--
-
Example(compl exval ue--->f
loat---
>NotPossi bl
e)
--
--
--
--
--
--
-----
--
---
--
--
---
--
----
-----
--
---
--
--
---
---
--
-----
--
--
-
>>>a=2+3j
>>>pri
nt (a,t
ype(a))-
----
--(2+3j)<class' compl ex'>
>>>b=float (
a)--
--
---
Ty peEr ror:fl
oat (
)ar gumentmustbeast
ri
ngorar
eal
number
,not
'
complex'
--
--
--
--
--
--
-----
--
---
--
--
---
--
----
-----
--
---
--
--
---
---
--
-----
--
--
--
---
---
--
--
--
--
Example(St rvalue--
-->floatVal ue)
--
--
--
--
--
--
-----
--
---
--
--
---
--
----
-----
--
---
--
--
---
---
--
-----
--
--
-
>>>a="123"#i ti
si ntst r
>>>pri
nt (a,t
ype(a))-
----
---
--123<cl ass'st r'
>
>>>b=float (
a)#POSSI BLE
>>>pri
nt (b,type(
b) )
----
---123.0<cl ass'float'
>
--
--
--
--
--
--
-----
--
---
--
--
---
--
----
-----
--
---
--
--
---
---
--
---
>>>a="12. 34"#i tisf l
oatst r
>>>pri
nt (a,t
ype(a))-
----
12. 34<cl ass'str'>
>>>b=float (
a)#POSSI BLE
>>>pri
nt(b,ty
pe(b))
--
--
--
12.34<class'fl
oat
'>
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
---
--
--
--
-
>>>a="KVR"#I tispurestr
>>>pri
nt(a,
type(
a))-
--
--
--
KVR<cl ass'st
r'
>
>>>b=fl
oat(a)-
--
--
ValueEr
ror:couldnotconver
tst
ri
ngt
ofl
oat
:'
KVR'

>>>a="True"#itisboolstr
>>>pri
nt (
a,t
ype(
a))-
--
--
-True<cl ass'str
'>
>>>b=float(
a)-
--
--
-Val
ueError:coul dnotconvertstri
ngtofl
oat:'
True'
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
---
---
--
---
-
>>>a="2+3j"#itiscompl exst r
>>>pri
nt (
a,t
ype(
a))-
--
--
--
-2+3j <class'st
r'
>
>>>b=float(
a)-
--
-Val
ueError:couldnotconv ertstr
ingtofl
oat:
'2+3j'

3)bool
()

=>bool()i susedconv erting" AnyPossi bleTy peValueint


obool
typev
alue"
.
=>Syntax:- v arname=bool (int/f loat/compl ex/str)
=>ALLNON- ZEROVal uesar eTr eat edasTRUE
=>ALLZEROVal uesar eTr eat edasFALSE
--
--
--
--
--
---
----
----
--
---
---
--
--
--
---
-----
---
----
----
---
-----
---
--
--
--
---
--
--
--
---
--
Exampl e(i ntv al
ue---
--
->bool -
-->Possi ble)
--
--
--
--
--
---
----
----
--
---
---
--
--
--
---
-----
---
----
----
---
-----
---
--
--
--
---
--
--
--
---
-
>>>a=123
>>>pri
nt (a,type(a))-
--
--
---
---123<cl ass' i
nt'>
>>>b=bool (a)
>>>pri
nt (b, ty
pe(b))--
--
---
----True<cl ass' bool'>
>>>a=0
>>>pri
nt (a,type(a))-
--
--
---
-0<cl ass' int'
>
>>>b=bool (a)
>>>pri
nt (b, ty
pe(b))--
--
---
--Fal se<cl ass' bool'>
>>>a=-123
>>>pri
nt (a,type(a))-
--
--
---
123<cl ass' int'>
>>>b=bool (a)
>>>pri
nt (b, ty
pe(b))--
--
---
--Tr ue<cl ass' bool'
>
--
--
--
--
--
---
----
----
--
---
---
--
--
--
---
-----
---
----
----
---
-----
---
--
--
-
Exampl e(f loatv al
ue--
---
->bool --
->Possi ble)
--
--
--
--
--
---
----
----
--
---
---
--
--
--
---
-----
---
----
----
---
-----
---
--
--
--
---
--
--
--
---
-
>>>a=12. 34
>>>pri
nt (a,type(a))-
--
--
---
-12. 34<cl ass' float'
>
>>>b=bool (a)
>>>pri
nt (b, ty
pe(b))--
--
---
-Tr ue<cl ass' bool '
>
>>>a=0. 0
>>>pri
nt (a,type(a))-
--
--
---
0.0<cl ass' f
loat '
>
>>>b=bool (a)
>>>pri
nt (b, ty
pe(b))--
--
---
Fal se<cl ass' bool '
>
>>>a=0. 00000000000000000000000000000000000000001
>>>print(a,t
ype(a))-
--
--1e- 41<cl ass' fl
oat'
>
>>>b=bool (
a)
>>>print(b,type(b))
--
----
Tr ue<cl ass' bool '
>
--
--
--
--
--
----
---
--
---
--
--
---
--
--
----
---
-----
--
----
---
----
---
--
--
---
--
--
--
Exampl e:
-(compl exvalue- ---
--
>bool --
->Possible)
--
--
--
--
--
----
---
--
---
--
--
---
--
--
----
---
-----
--
----
---
----
---
--
--
---
--
--
--
--
--
--
--
--
>>>a=2+3j
>>>print(a,t
ype(a))-
--
-(2+3j )<cl ass' compl ex'
>
>>>b=bool (
a)
>>>print(b,type(b))
--
--True<cl ass' bool'>
>>>a=0+0j
>>>print(a,t
ype(a))-
--
-0j<cl ass' compl ex'
>
>>>b=bool (
a)
>>>print(b,type(b))
--
--False<cl ass' bool'
>
--
--
--
--
--
----
---
--
---
--
--
---
--
--
----
---
-----
--
----
---
----
---
--
--
---
--
--
--
--
--
--
--
-
Exampl e:
-(st rvalue-
----
->bool )
--
--
--
--
--
----
---
--
---
--
--
---
--
--
----
---
-----
--
----
---
----
---
--
--
---
--
--
--
--
--
--
--
--
>>>a="123"
>>>print(a,t
ype(a))-
--
---
---
123<cl ass' str
'>
>>>b=bool (
a)
>>>print(b,type(b))
--
----
--True<cl ass' bool'
>
>>>a="12. 34"
>>>print(a,t
ype(a))-
--
---
-12. 34<cl ass'str'
>
>>>b=bool (
a)
>>>print(b,type(b))
--
----
--True<cl ass' bool'
>
>>>a="0"
>>>print(a,t
ype(a))-
--
---
---
0<cl ass' str'
>
>>>b=bool (
a)
>>>print(b,type(b))
--
----
--True<cl ass' bool'
>
>>>len(a)---
--
---
--
---
1
>>>a="Fal se"
>>>print(a,t
ype(a))-
--
---
-Fal se<cl ass' str'
>
>>>b=bool (
a)
>>>print(b,type(b))
--
----
Tr ue<cl ass' bool '
>
>>>a=""
>>>print(a,t
ype(a))-
--
---
- <cl ass' str'>
>>>b=bool (
a)
>>>print(b,type(b))
--
----
-Fal se<cl ass' bool'
>
>>>l
en(a)----
--
---
--
--0

>>>a=" "
>>>pri
nt(
a,t
ype(a)
)-
--
-- <cl
ass'
str
'>
>>>b=bool(
a)
>>>pri
nt(
b,type(
b))
--
--
-Tr
ue<class'
bool'
>
>>>l
en(a)-
--
--4

4)compl
ex(
)
=>compl ex()isusedconv erti
ng" AnyPossi bleTy peValueint
ocompl
ext
ypev
alue"
.
=>Syntax:- v arname=compl ex (int/f l
oat/ bool /str)
--
--
--
--
--
----
---
---
--
---
----
---
----
--
------
----
---
----
---------
-
Exampl es:(i
nt---
-->compl ex- -
-->Possi bl e)
--
--
--
--
--
----
---
---
--
---
----
---
----
--
------
----
---
----
---------
-
>>>a=10
>>>pri
nt (a,ty
pe( a))--
---
---
--10<cl ass' i
nt '>
>>>b=compl ex(a)
>>>pri
nt (b,ty
pe( b))--
----
--(10+0j )<cl ass' compl ex '>
>>>a=-4
>>>pri
nt (a,ty
pe( a))--
---
---
---- 4<cl ass' int '
>
>>>b=compl ex(a)
>>>pri
nt (b,ty
pe( b))--
-- ( -4+0j )<cl ass' compl ex '
>
--
--
--
--
--
----
---
---
--
---
----
---
----
--
------
----
---
----
---------
----
-
Exampl es:(fl
oat----
->compl ex---
->Possi ble)
--
--
--
--
--
----
---
---
--
---
----
---
----
--
------
----
---
----
---------
----
--
>>>a=2. 3
>>>pri
nt (a,ty
pe( a))--
---
---
-2. 3<cl ass' float '
>
>>>b=compl ex(a)
>>>pri
nt (b,ty
pe( b))--
----
---
( 2.3+0j )<cl ass' compl ex'>
>>>a=-4.5
>>>pri
nt (a,ty
pe( a))--
--- 4. 5<cl ass' float '
>
>>>b=compl ex(a)
>>>pri
nt (b,ty
pe( b))--
----( -4.5+0j )<cl ass' compl ex' >
--
--
--
--
--
----
---
---
--
---
----
---
----
--
------
----
---
----
---------
----
--
-
Exampl es:(bool---
-->compl ex ---
->Possi ble)
--
--
--
--
--
----
---
---
--
---
----
---
----
--
------
----
---
----
---------
----
--
-
>>>a=Tr ue
>>>pri
nt (a,ty
pe( a))--
---
--Tr ue<cl ass' bool '
>
>>>b=compl ex(a)
>>>pri
nt (b,ty
pe( b))--
--(1+0j )<cl ass' compl ex'>
>>>a=Fal se
>>>pri
nt (a,ty
pe( a))--
---
Fal se<cl ass' bool '
>
>>>b=compl ex(a)
>>>pri
nt (b,ty
pe( b))--
---0j <cl ass' compl ex'>
--
--
--
--
--
----
---
---
--
---
----
---
----
--
------
----
---
----
---------
----
--
-
Exampl es:(str
---
-->compl ex)
--
--
--
--
--
----
---
---
--
---
----
---
----
--
------
----
---
----
---------
----
--
---
>>>a="12"#i tisi ntst r
>>>pri
nt (a,ty
pe( a))--
---
---
--12<cl ass' str '
>
>>>b=compl ex(a)
>>>pri
nt (b,ty
pe( b))--
----
(12+0j )<cl ass' compl ex'>
>>>a="12. 3"#i tisf l
oatst r
>>>pri
nt (a,ty
pe( a))--
---
-12. 3<cl ass' st r'
>
>>>b=compl ex(a)
>>>pri
nt (b,ty
pe( b))--
----
--(12. 3+0j)<cl ass' compl ex'>
>>>a="Tr ue"#i tisbool st r
>>>pri
nt (a,ty
pe( a))--
--True<cl ass' st r'>
>>>b=compl ex(a) --
--ValueEr ror:compl ex()ar gisamal for
medstri
ng
>>>a="KVR"#i tispurest r
>>>pri
nt(a,
type(
a))
--
--
--
--KVR<class'st
r'
>
>>>b=complex(a)-
--
--
--
-ValueEr
ror:
complex(
)ar
gisamal
for
medst
ri
ng

================================================================
5)st
r()
================================================================
=>str(
)i susedf orconverti
ng" All TypesofVal uesint
ost
rty
pev
alue"
.
=>Syntax:- v arname=st r
(int/f loat/ bool /
complex)
--
--
--
--
--
----
----
-
Exampl es:
--
--
--
--
--
----
----
-
>>>a=12
>>>pri
nt (a,t
ype( a))
--
--
--
--12<class' i
nt'>
>>>b=st r(a)
>>>b--
----
----' 12'
>>>pri
nt (b,type(b))
--
--
--12<class' str'
>
>>>a=2. 3
>>>pri
nt (a,t
ype( a))
--
--
--
--2.
3<cl ass' float '
>
>>>b=st r(a)
>>>b--
----
----
---
---'2.
3'
>>>pri
nt (b,type(b))
--
--
---
-2.3<cl ass' str'>
>>>a=Tr ue
>>>pri
nt (a,t
ype( a))
--
--
--
---
True<cl ass' bool'>
>>>b=st r(a)
>>>b--
----
----
---
-'True'
>>>pri
nt (b,type(b))
--
--
---
-Tr ue<cl ass' st r'
>
>>>a=2+3j
>>>pri
nt (a,t
ype( a))
--
--
--
---
(2+3j)<cl ass' complex'
>
>>>b=st r(a)
>>>b--
----
----
--'(2+3j
)'
>>>pri
nt (b,type(b))
--
--
--(
2+3j)<cl ass' st r'
>
================================================================

Numberofappr
oachest
odev
eloppy
thonpr
ogr
ams
I nreal ti
me, wecandev el
oppy t
honpr ogramsin2appr oaches.Theyare
a)Interacti
veMode
b)Bat chMode
--
--
---
--
----
--
--
--
--
---
---
--
---
---
--
---
---
--
---
---
-
a)Interacti
veMode:
--
--
---
--
----
--
--
--
--
---
---
--
---
---
--
---
---
--
---
---
-
=>Inthi smode, PythonPr ogr ammeri ssuedast atementandget sanoutputata
ti
me.
=>Thisi suseful t
ot estoneI nstructi
on/st atementatatime.
=>Thismodeofdev elopmenti snotr ecommendedt osolveBigProbl
emsbcozt he
i
nst ructi
onsr el
atedbi gpr oblem solvi
ngar enotabletosaveandwecan' tret
ri
eve
thosei nstr
uct i
ons.
=>Exampl esSof t
war e:-
Py thonCommandPr ompt ,PythonIDLE.( Thesethingsare
commi ngal ongwi t
hPy thonSof twareInstal
lat
ion)
=>Hencet osolveBigPr obl ems/Bi gprograms, wemustgof orBatchMode
Pr ogrammi ng.
--
--
---
--
----
--
--
--
--
--
--
----
--
--
---
---
----
--
---
--
---
--
---
--
--
--
--
---
--
---
--
--
--
---
--
-
b)Bat chMode:
--
--
---
--
----
--
--
--
--
--
--
----
--
--
---
---
----
--
---
--
---
--
---
--
--
--
--
---
--
---
--
--
--
---
--
=>Inthismodeofdev elopment ,PythonProgr ammerdev elopsgr oup/bat chof
I
nst ructi
onsinasi ngleuni tandi tmustbesav edonsomef i
lenamewi t
han
extension.py(FileName. py)
=>Oncewesav ethet hei nstructi
onsonsomef il
enamet henwecanopenand
access t hatfi
lenameanyt i
mei nourprojects.
--
--
---
--
----
--
--
--
--
--
--
-
Exampl eSoft
war es:
--
--
---
--
----
--
--
--
--
--
--
-
1)Py thonI DLE- -
--(PythonSof twareInstal
l
ation)

Thefol
lowingI
DEsneedtoinst
allSeparat
ely--
2)JupiterNoteBook( Anakonda)
3)Spider(Anakonda)
4)VSCode
5)SublimeText
6)PyChar m
7)EditPlus
Note:
-Thesearecal
l
edIDEs(Integrat
edDev el
opmentEnv i
ronment
)usedf
or
devel
opingPyt
honProgr
ams

#ThisProgram comput essum oft


wonumber
s
#sumex 1.
py
a=10
b=20
c=a+b
pri
nt(
"-
--
---
--
---
--
---
--
---
--
--
--
-"
)
pri
nt(
"\t
Resul t"
)
pri
nt(
"-
--
---
--
---
--
---
--
---
--
--
--
-"
)
pri
nt(
"\t
Val ofa=",
a)
pri
nt(
"\t
Val ofb=",b)
pri
nt(
"\t
Sum=" ,c)
pri
nt(
"-
--
---
--
---
--
---
--
---
--
--
--
-"
)

#Thi
sPr
ogr
am comput
essum oft
wonumber
s
#sumex 2.
py
a=fl
oat(
input("
EnterFirstVal
ue:
")
)
b=fl
oat(
input("
EntersecondValue:
")
)
c=a+b
pri
nt(
"-
--
---
--
---
--
---
--
---
--
--
--
-"
)
pri
nt(
"\t
Resul t"
)
pri
nt(
"-
--
---
--
---
--
---
--
---
--
--
--
-"
)
pri
nt(
"\t
Val ofa=",
a)
pri
nt(
"\t
Val ofb=",b)
pri
nt(
"\t
Sum=" ,c)
pri
nt(
"-
--
---
--
---
--
---
--
---
--
--
--
-"
)

Di
spl
ayt
heDat
a/r
esul
tofPy
thonPr
ogr
am

=>Todisplayther esul
tofthepythonprogr
am,wehaveapre-
defi
nedFunct
ion
cal
ledprint
().
=>InOtherwor ds,pri
nt(
)isusedfordispl
ayi
ngt
heresul
tofpyt
honprogr
am onthe
console(Monitor)
=>pri
nt()cont
ai nsthe5syntaxes.Theyare

Sy
ntax-
1: pri
nt(
value)
(or)
pr
int
(value1,
val
ue,
.
..
value-
n)
=>Thi
ssy
ntaxdi
spl
ayonlyt heval
uesontheconsol
e.

Exampl
es:
--
--
--
---
--
--
--
>>>stno=10
>>>sname=" Rossum"
>>>print(stno)--
---
--
---
--
---
-10
>>>print(sname) -
--
---
--
--
--
Rossum
>>>print(stno,sname) --
--
---
-10Rossum
Syntax-2: pri
nt(Message)
=>ThisSy ntaxdi splaystheMessages( str
s)ont heconsol
e
--
--
--
---
--
--
-----
--
Examnpl es:
--
--
--
---
--
--
-----
--
>>>print("Hell
oPy t
honWor l
d" )
---
--
---
-Hell
oPy thonWorl
d
>>>print('
Hel l
oPy thonWor ld')-
---
-Hell
oPy thonWorld
>>>print('
''
HelloPy thonWor ld''
'
)---
--
HelloPy t
honWor l
d
Syntax-3: print(Messagecum Val ue)
(OR)
print(
Valuecum Message)
=>ThisSy ntaxdi splaystheMessages( str
s)alongwithval
uesont
heconsol
e
--
--
--
---
--
--
-----
--
Examnpl es:
--
--
--
---
--
--
-----
--
>>>a=10
>>>b=20
>>>c=a+b
>>>print("sum=" ,
c)---
--
--
--
--sum=30
>>>print(c,"i
st hesum" )---
---
--30i sthesum
>>>print("sum of" ,
a,"and" ,
b,"=",c)-
--
sum of10and20=30
>>>a=1
>>>b=2
>>>c=3
>>>d=a+b+c
>>>print("sum of" ,
a,",
",
b,"and" ,c,"
=",
d)--
--
-sum of1, 2and3=6

Sy
ntax-
4: pri
nt(
Messagecum Val
uefor
mat())
(OR)
pri
nt(
Val
uecum Messagewit
hformat
())

=>ThisSy ntaxdisplay
sthev aluesandmessagesbyusi ngfor
mat()
=>Thepur poseoff ormat()i
st hatitsuppli
esthespecifi
edvar
iabl
estot
heempt
y
curl
ybr aces{}.
--
--
--
--
--
----
--
Exampl es:
--
--
--
--
--
----
--
>>>a=10
>>>b=20
>>>c=a+b
>>>print("
sum={ }"
.for
mat (
c))---
--
--
---
--
-sum=30
>>>print("
{}isthesum" .
format (
c))-
--
---
-30isthesum
>>>print("
sum of{ }and{}={}
".
format (
a,b,
c))-
--
-sum of10and20=30
>>>a=1
>>>b=2
>>>c=3
>>>d=a+b+c
>>>print
("
sum of{}
,{}and{}={
}".
format (a,
b,c,d))
---
sum of1, 2and3=6
>>>stno=10
>>>sname="Rossum"
>>>print
("
MyNumberi s{}andnamei s{ }
".format(stno,sname))
--
MyNumberi
s10
andnamei sRossum
>>>a=10
>>>b=20
>>>c=a*b
>>>#mul (
10,
20)=200
>>>print
("
mul(
{},
{})
={}".
for
mat(a,b,c))-
--
-mul( 10,
20)=200
>>>print
("
sum({}
,{
})={}
".f
ormat(a,b,a+b))-
--
-sum( 10,20)=30

Sy
ntax-
5: print(Messagecum Val uewi thf or matspeci fi
er s)
(OR)
print (Val
uecum Messagewi thf ormatspeci fi
ers)
=>ThisSy ntaxdisplayt hev aluescum messageswi thf ormatspeci f
iers.
=>Thef ormatspeci fier%di sf ordispl yingI ntegerdat a,%fforf l
oatv alueand%sf or
strvalue.
=>Ifdon'thaveanyf ormatspeci fi
ert hent hosev al uesconv ertedintost randuse%s
--
--
---
--
---
--
--
-
Exampl es:
--
--
---
--
---
--
--
--
-
>>>a=10
>>>b=5
>>>c=a+b
>>>pr i
nt("
sum=%d"%c) --
--
--
--sum=15
>>>pr i
nt("
sum=%f "%c) -
--
--
-sum=15. 000000
>>>pr i
nt("
sum=%0. 2f"%c) ---
---
-sum=15. 00
>>>pr i
nt("
%di sthesum"%c) --
---
--
--15i st hesum
>>>pr i
nt("
sum of%dand%d=%d"%( a,
b, c))-
---sum of10and5=15
>>>pr i
nt("
sum of%fand%f =%f "%( a,b,c)) -
--
sum of10. 000000and
5.000000=15. 000000
>>>pr i
nt("
sum of%0. 2fand%0. 2f=%0. 3f "%( a,b,c) )--
sum of10. 00and5. 00=15.000
>>>pr i
nt("
sum of%0. 2fand%0. 2f=%d"%( a,b,c))--sum of10. 00and5. 00=15
>>>pr i
nt("
sum( %d,%d) =%0.2f"%( a,b,c))---
sum( 10, 5) =15. 00
>>>pr i
nt("
sub(%d,%d) =%dmul (%d,%d) =%d"%( a,b, a-b,a,b,
a*b))
sub(10,5)=5
mul (
10,5)=50
>>>
>>>stno=10
>>>name=" Rossum"
>>>pr i
nt("
MyNumberi s%dandnamei s%s"%( st no, name) )
MyNumberi s10and
namei sRossum
>>>lst=[10,
"KVR" ,
22.22, "Hyd","
Py t
hon" ]
>>>pr i
nt("
contentofl st=",
l
st)--
cont entofl st=[ 10, '
KVR' ,22.
22, '
Hy d'
,'Python']
>>>pr i
nt("
contentofl st={}
".f
ormat (lst))--cont entofl st=[10,'
KVR' ,
22.22, '
Hy d'
,
'Pyt
hon'
]
>>>pr
int
("
cont
entofl
st=%s"%l
st)
--
-cont
entofl
st=[
10,'
KVR'
,22.
22,
'Hy
d',
'
Pyt
hon'
]

Readi
ngt
hisDat
aDy
nami
cal
l
yfr
om KeyBoar
d

=>Tor
eadt
hedat
afrom KeyBoard,wehav
e2pr
e-def
inedFunct
ions.Theyar
e
a)input
()
b)input
(Message)

1)i
nput
():

=>Thi sfunctionisusedf orreadinganytypeofdatafr


om KeyBoardint
hefor
m ofst
r.
Progr amatically
, wecanconv ertstrt
ypevaluesi
ntoothert
ypeofval
uesbyusi
ngType
castingTechni ques.
=>Synt ax: v arname=input()
=>Her e'varname' i
sanobjectoft y
pestr.
=>input (
)ispr e-
def i
nedfuncti
onandr eadsanytypeofdatafr
om Keyboar
d.

Exampl
es:

#mulex5.
py
pr
int
("Ent
ert
wov
alues:
")
a=input (
)
b=input ()
x=float(a)
y=float(b)
z=x* y
pri
nt ("
mul ({
},
{})={
}"
.f
ormat
(x,
y,
z))
OUTPUT:
Entert wov alues:
12
30
mul (12.0,
30.0)=360.0

--
--
---
--
--
--
--
--
---
--
--
---
--
--
--
--
--
--
--
--
--
----
--
--
--
--
--
---
--
--
--
--
--
--
--
--
b)input(
Message) :
--
--
---
--
--
--
--
--
---
--
--
---
--
--
--
--
--
--
--
--
--
----
--
--
--
--
--
---
--
--
--
--
--
--
--
--
=>Thisfuncti
oni susedforreadinganyt ypeofdatafr
om KeyBoardint
hefor
m ofst
rby
giv
ingUser -
Prompt i
ngMessages.
=>Syntax: v arname=input(Message)
=>Here'varname' i
sanobjectoft ypestr.
=>input(
)ispre-defi
nedfunctionandr eadsanytypeofdat
afrom Keyboar
d.
=>Messager epresentsUser-PromptingMessages.

--
--
--
---
---
---
--
Exampl es:
--
--
--
---
---
---
--
#Thispr ogram readst wov al
uesandmult
ipl
ythem
#mul ex9.py
#conv ertstrt
y peintof l
oattype
x=fl
oat (
input(
"EnterFi r
stValue:
")
)
y=fl
oat (
input(
"EnterSecondVal ue:
")
)
z=x*y
pri
nt("mul of{}and{ }={}
".
format
(x,
y,
z))
OUTPUT:
EnterFirstValue:30
EnterSecondVal ue:20
mul of30. 0and20. 0=600.0

#thisprogram calareaofcir
clebyaccept
ingr
adi
ous
r=fl
oat(
input("
EnterRadious:
"))
ac=3.14*r*
* 2
pri
nt("
AreaofCi rcl
e={}"
.f
ormat(ac)
)
OUTPUT:
EnterRadious:27
AreaofCi r
cle=2289.06

#Thisprogram r
eadstwovaluesandmul
ti
plyt
hem
#mulex3.py
pri
nt(
"EnterFi
rstVal
ue:
")
a=i
nput()#a=12
pri
nt(
"EnterSecondVal
ue:"
)
b=i
nput()#4
pri
nt("Val ofa={}andi t
st ype={}"
.f
ormat(a,type(a)
))
pri
nt("Val ofb={}andi t
st ype={}"
.f
ormat(b,type(b)
) )
#c=a* b# 12*4- --
--
-error
#conv ertaandbi ntofloat
x1=float(a)
x2=float(b)
pri
nt("Val ofx1={}andi tstype={}"
.f
ormat(x1,type(x1))
)
pri
nt("Val ofx2={}andi tstype={}"
.f
ormat(x2,type(x2))
)
x3=x1* x2#- -val
id
pri
nt("Mul ={}andi t
st ype={}"
.f
ormat (
x3,type(x3))
)
OUTPUT:
EnterFi r
stValue:
30
EnterSecondVal ue:
20
Valofa=30andi tstype=<class'str'
>
Valofb=20andi tstype=<class'str'
>
Valofx1=30. 0andi t
st ype=<class'fl
oat
'>
Valofx2=20. 0andi t
st ype=<class'fl
oat
'>
Mul =600. 0andi t
st ype=<class'fl
oat'
>

#Thispr ogram readst wov al


uesandmul ti
plythem
#mul ex4.py
pri
nt("EnterFirstValue:")
a=i
nput ()#a=12
pri
nt("EnterSecondVal ue:")
b=input()#4
pri
nt("Val ofa={}andi t
st ype={}
".
format(
a,type(a)
))
pri
nt("Val ofb={}andi t
st ype={}
".
format(
b,type(b)
) )
#c=a* b# 12*4- --
--
-error
#conv ertaandbi ntofloat
x1=float(a)
x2=float(b)
pri
nt("Val ofx1={}andi tstype={}
".
format(
x1,type(x1))
)
pri
nt("Val ofx2={}andi tstype={}
".
format(
x2,type(x2))
)
x3=x1* x2#- -val
id
pri
nt("Mul ={}andi t
stype={ }"
.f
ormat(x3,
type(x3))
)
OUTPUT:
Ent
erFi
rstVal
ue:
30
Ent
erSecondVal
ue:
20
Val
ofa=30andi
tstype=<cl
ass'
str
'>
Val
ofb=20andit
stype=<cl
ass'
str
'>
Val
ofx1=30.
0andit
st y
pe=<cl
ass'f
loat
'>
Val
ofx2=20.
0andit
st y
pe=<cl
ass'f
loat
'>
Mul=600.
0andi
tsty
pe=<class'
fl
oat'
>

#Thi spr ogram readst woval


uesandmul
ti
plyt
hem
#mul ex5. py
pri
nt ("
Ent ertwov alues:
")
a=input (
)
b=input ()
x=float(a)
y=float(b)
z=x* y
pri
nt ("
mul ({}
,{}
)={}
".for
mat(x,
y,
z))
OUTPUT:
Entert wov alues:
12
30
mul (12.0,30.0)=360.0

#Thispr ogram readst woval


uesandmul
ti
plyt
hem
#mul ex6. py
pri
nt("Ent ertwov alues:
")
x=fl
oat (input (
))
y=fl
oat (i
nput ()
)
z=x*y
pri
nt("mul ({}
,{}
)={}
".for
mat(x,
y,
z))
OUTPUT:
Entertwov alues:
30
20
mul(30. 0,20.0)=600.0

#Thispr ogram readstwovaluesandmulti


plyt
hem
#mul ex7.py
pri
nt("Entertwov al
ues:"
)
pri
nt("mul={}"
.f
ormat (
fl
oat(
input
())
*fl
oat
(i
nput(
))))
OUTPUT:
Entertwov alues:
12
15
mul=180.
0

#Thi spr ogram readst wov al


uesandmult
ipl
ythem
#mul ex8.py
a=input ("EnterFi
rstValue:")
b=input ("EnterSecondVal ue:"
)
#conv ertstrtypeintof l
oattype
x=float (
a)
y=float (
b)
z=x* y
pri
nt ("mul of{}and{ }={
}".
format(
x,y
,z)
)
OUTPUT:
EnterFi rstValue:30
EnterSecondVal ue:15
mul of30. 0and15. 0=450.0

#Thi
spr ogram readst
wov al
uesandmulti
plythem
#mulex11.py
pr
int
("Mul={}"
.f
ormat(f
loat
(i
nput
("
EnterFi
rstValue:
")
)*f
loat
(i
nput
("
Ent
erSecondVal
ue:
")
)))
OUTPUT:

Ent
erFirstVal
ue:
20
Ent
erSecondValue:
30
Mul=600.0

================================================================
Operat
orsinPython
=================================================================I
nd
ex:
--
--
--
--
--
=>PurposeofOperator
s
=>Expressi
on
=>TypesofOperator
s
=>ProgrammingExamplesonEv eryOperatort
ype.

Operat
orsinPy t
hon
================================================================
=>Anoperatorisasymbol .
=>ThepurposeofOper ator
sisthattoper
form cert
ainoperat
iononthegivendat
a.
=>I
ftwoormor eVari
ables/Objectsar
econnect edwit
hanoper at
ortheniti
s
cal
ledExpression.
=>I
nPy t
honPr ogrammi ng,
wehav e7typesofOper at
ors.Theyare

1.Ar
it
hmet
icOper
ator
s
2.AssignmentOper at
or
3.RelationalOperat
ors
4.Logical Operat
ors
5.BitwiseOper at
ors(MostI
mp)
6.Member shipOperat
ors
a)in
b)notin
7)IdentityOperat
ors
a)is
b)isnot

Note:
-Unar yIncr
ement/DecrementOpertator-
--
C,CPP,JAVA,.
NET++- -
NotThereinPython
?:Ter nar
yOperator--
notther
einPy t
hon
================================================================

1.Ar
it
hmet
icOper
ator
s

=>ThepurposeofAr i
thmeti
cOper ator
sisthat"
ToPerf
orm Ar
it
hmet
icOperat
ionssuchas
Addit
ion,
subtracti
on,multi
pli
cati
onetc..
"
=>I
ftwoormor evari
abl
es/obj ect
sconnectedwit
hAri
thmeti
cOper
ator
sthenitiscal
l
ed
Ari
thmeti
cExpr essi
on.
=>Thefol
lowingTablegivesli
stofAr i
thmeti
cOper
ator
s

Sl
NO Sy
mbol Meani
ng Exampl
e a=10b=3

1. + Addi
ti
on pr
int
(a+b)
--
--
--
--
--
>13

2. - Subt
ract
ion pr
int
(a-
b)-
--
--
--
--
--
>7

3. * Mul
ti
pli
cat
ion pr
int
(a*
b)-
--
--
--
--
>30

4. / Di
vi
sion pr
int
(a/
b)-
--
--
--
>3.
33333333333335

5. /
/ Fl
oorDi
vi
sion pr
int
(a/
/b)
--
--
--
--
>3

6. % Modul
oDi
vi
sion pr
int
(a%b)
--
--
--
--
>1

7. *
* Exponent
iat
ion pr
int
(a*
*b)
--
--
--
->1000

#ThisProgram demonst r
atestheari
thmet
icOper
ator
s
#aop.py
a=i
nt(i
nput("
EnterVal
ueofa: "
))
b=i
nt(i
nput("
EnterVal
ueofb: "
))
pri
nt(
"-"
*50)
pri
nt(
"Ari
thmet i
cOperati
onResul t
s")
pri
nt(
"-"
*50)
pri
nt(
"{}
+{}={}
".
format
(a,b,a+b))
pri
nt(
"{}
-{}
={}"
.f
ormat(
a,b,a-b))
pr
int
("
{}*{
}={}
".
format(
a,b,a*b))
pr
int
("
{}/{
}={}
".
format(
a,b,a/b))
pr
int
("
{}//
{}={
}".
for
mat(a,b,a//
b))
pr
int
("
{}%{}={
}".
for
mat(a,b,a%b))
pr
int
("
{}**
{}={
}".
format
(a,b,a**
b))
pr
int
("
-"
*50)

OUTPUT:
EnterValueofa:20
EnterValueofb:7
--
--
---
--
--
--
--
--
--
--
--
--
---
---
--
--
--
--
--
--
--
--
--
-
Ari
thmet i
cOperationResults
--
--
---
--
--
--
--
--
--
--
--
--
---
---
--
--
--
--
--
--
--
--
--
-
20+7=27
20-7=13
20*7=140
20/7=2.857142857142857
20//7=2
20%7=6
20**7=1280000000

EXAMPLE: 2
#Thi spr ogram calculat
es'
a'tot
hepowerof'
m'
#power ex1.py
a=f l
oat(input("
EnterBase:"
))
m=f loat(input(
"EnterPower")
)
res=a* *
m
print("
pow( {
},
{}
)={}
".format
(a,
m,r
es)
)
OUTPUT:
Ent
erBase:9
Ent
erPower 3
pow(9.
0,3.
0)=729.
0

EXAMPLE:

#Thi sprogram calculat


essquar erootofgi
vennumber
#sqr t
ex1.py
n=f l
oat(i
nput("
Enteranumber :"
))
res=n**0.5 #OR r es=n* *(1/
2)
print(
"sqrt
({})
={}
".f
ormat (n,
res))
print(
"--
--
--
--
---
OR---
---
---
--
--
-")
pr
int
("
sqrt
({}
)={}
".
format(n,
round(
res,
2))
)
pr
int
("
--
--
--
--
--
-OR--
--
---
--
--
--
-")
pr
int
("
sqrt
(%f)=%0.2f
"%(n,res)
)
OUTPUT:
Enteranumber :
30
sqrt(
30.0)=5.477225575051661
--
--
--
--
---
OR- -
--
---
--
---
--
sqrt(
30.0)=5.48
--
--
--
--
---
OR- -
--
---
--
---
--
sqrt(
30.000000) =5.48

2.Assi
gnmentOper
ator

=>Thesymbolforassi
gnmentoper atoris=
=>ThepurposeofAssignmentOper at
ori st
hat"Tot r
ansferRHSv
alue(
s)t
oLHS
Vari
abl
e(s)"
=>Wecanuset heAssignmentOper atorint
woway s.Theyare
1)SingleLineAssignmentOperator
2)Mul t
iLineAssignmentOperator

1)Singl
eLineAssi
gnmentOper
ator
=>Thisoperat
ort
ransf
erSi
ngl
evaluef
rom RHSt
oSi
ngl
eVar
iabl
eofLHS.

=>Syntax: var
name=v
alue
--
--
--
--
--
----
--
--
Exampl es:
--
--
--
--
--
----
--
--
>>>a=123
>>>b=100
>>>c=a+b
>>>pri
nt (
a,b,
c)-
--
--123 100 223

2)Mult
iLi
neAssi
gmentOper
ator
=>Thi
soperat
ort
ransf
erMul
ti
plev
aluesf
rom RHSt
oMul
ti
pleVar
iabl
esofLHS.

=>Syntax: var
1,var
2..
..
.v
ar-n=val
1,v
al2,
..
..
val
-n
=>heretheval
uesofval
1,v
al2.
..
..
val-
nareassignedtovar
1,v
ar2.
..
var
-nr
espect
ivel
y.

Exampl es:
--
--
--
--
--
-----
>>>a,b=10, 20
>>>sum, sub,
mul =a+b,a-b,a*b
>>>print(a,b)
----
--
--
--
-1020
>>>print(sum, sub,
mul )-
----
-30-10200
>>>sno, sname, marks=100, "Rossum"
,44.
44
>>>print(sno,sname, mar ks)-
--
--
100Rossum 44.
44
#Thisprogram swapst wov alues
#swap.py
a=i
nput("EnterValueofa:"
)
b=i
nput("EnterValueofb:"
)
pri
nt("
-"
*50)
pri
nt("
Ori
ginal Val
ueofa:{}
".format(
a))
pri
nt("
Ori
ginal Val
ueofb:{}
".format(
b))
pri
nt("
-"
*50)
#swappinglogi c
a,
b,=b,
a
pri
nt("
SwapopedVal ueofa:{}"
.f
ormat(
a))
pri
nt("
SwapopedVal ueofb:{}"
.f
ormat(
b))
pri
nt("
-"
*50)

PROGRAM:

#Toper
for
m al
lAr
it
hmat
icOper
ati
onusi
ngMul
ti
li
neAssi
gnmentOper
ator
s
#mul
ti
Asgn.
py
a=f
loat
(i
nput
("
Ent
erf
ir
stnumber
:"
))
b=f
loat
(i
nput
("
Ent
ersecondv
alue:
")
)
pr
int
("
_"*
50)
add,
sub,
mul
,
div
,fl
oor
_di
v,
modul
o,pow=a+b,
a-b,
a*b,
a/b,
a//
b,a%b,
a**
b
pri
nt(
"{}+{}
={}\n{
}-
{}
={}\
n{}*{}={
}\n{
}/{
}={
}\n{
}//
{}={}
\n{
}%{
}={
}\n{
}**
{}={
}"
.f
ormat
(a,
b,
add,
a,
b,
sub,
a,
b,
mul
,
a,
b,
div,
a,b,f
loor_di
v,
a,b,
modulo,
a,b,
pow))

OUTPUT:
Ent
erf
ir
stnumber
:10
Ent
ersecondv
alue:
3
_
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
_
10.
0+3.
0=13.
0
10.
0-3.
0=7.
0
10.
0*3.
0=30.
0
10.
0/3.
0=3.
3333333333333335
10.
0//
3.0=3.
0
10.
0%3.
0=1.
0
10.
0**
3.0=1000.
0
3.Rel
ati
onal
Oper
ator
s
=>Thepur poseofRel at
ionalOperator
sisthat"Tocompar etwovalues"
=>iftwoormor evalues/vari
ablesconnect edwithRelat
ional
Operator
st heni
tis
call
edRel ati
onalExpression.
=>Ther esultofRelati
onalExpressioni
seitherTrueorFalseandtheyhelpsusfor
takingdecisions.
=>Relati
onal Operatorsaregi
v eninthefol
l
owi ngTable:

SLNO Sy
mbol Meani
ng Exampl
ea=10b=20,
c=10

1. > gr
eat
ert
han pri
nt (
a>b)--
--
---
--
---
-False
pri
nt(b>c)--
--
--
--
---
-True
2. < Lesst
han pr
int(a<b)-
--
--
---
---
-True
pr
int(a<c)-
--
--
---
--
---
False
3. == Equal
i
ty pr
int(a==b)-
---
--
---
-False
pr
int(
a==c) -
--
--
---
--
-True
4. !
= notequal
to pri
nt(a!=b)-
--
--
---
--
--True
pr
int(
a!=c)--
--
--
---
--
--
False

5. >= greaterthan pr
int
(a>=b)
--
--
--
--
--
Fal
se
orequal
to pri
nt(a>=c)-
--
--
--
--
-Tr
ue
6. <= Lesst han pr
int
(a<=-2)-
--
--
--
--
-Fal
se
orequal to pr
int
(a<=c)-
--
--
--
--
--
True

#Thisprogram swapst wov alues


#swap.py
a=i
nput("EnterValueofa:"
)
b=i
nput("EnterValueofb:"
)
pri
nt("
-"
*50)
pri
nt("
Ori
ginal Val
ueofa:{}
".format(
a))
pri
nt("
Ori
ginal Val
ueofb:{}
".format(
b))
pri
nt("
-"
*50)
#swappinglogi c
a,
b,=b,
a
pri
nt("
SwapopedVal ueofa:{}"
.f
ormat(
a))
pri
nt("
SwapopedVal ueofb:{}"
.f
ormat(
b))
pri
nt("
-"
*50)
OUTPUT:
Ent
erVal ueofa:20
Ent
erVal ueofb:30
-
--
--
--
---
--
--
---
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
Ori
ginalValueofa:20
Origi
nal Valueofb: 30
--
--
---
--
---
---
--
-----
----
----
--
--
-----
----
---
--
--
SwapopedVal ueofa: 30
SwapopedVal ueofb: 20
--
--
---
--
---
---
--
-----
----
----
--
--
-----
----
---
--
--
#Thispr ogr am demonst artesRel ati
onalOper
ator
s
#rop.py
a=int(
input(" Enterv alofa: "))
b=int(
input( "Enterv alofb: "))
pri
nt("*"
*60)
pri
nt("Resul tsofRel at
ional Oper ator
s")
pri
nt("*"
*60)
pri
nt("{}
>{}={ }"
.for mat(a,b,a>b) )
pri
nt("{}
<{}={ }"
.for mat(a,b,a<b) )
pri
nt("{}
=={} ={}".
f ormat( a,b,a==b))
pri
nt("{}
!={}={ }
".format( a,b,a!=b))
pri
nt("{}
>={}={ }".
for mat(a,b,a>=b) )
pri
nt("{}
<={}={ }".
for mat(a,b,a<=b) )
pri
nt("*"
*60)
OUTPUT:
Ent
erv
alofa:
30
Ent
erv
alofb:
20
*
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
**
Resul
tsofRel
ati
onal
Oper
ator
s
*
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
**
30>20=Tr
ue
30<20=Fal
se
30==20=Fal
se
30!
=20=Tr
ue
30>=20=Tr
ue
30<=20=Fal
se
*
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
***
**
===================================================================

4.Logi
cal
Oper
ator
s

=>Thepur poseofLogi calOper ator


sisthat"Tocombinet woormorer
elati
onalexpr
essi
ons"
=>I
ft woormor erelat
ionalexpressionsareconnectedwithl
ogi
cal
Operator
stheniti
scall
ed
LogicalExpression.
=>Ther esul
tofLogi calexpressionsiseit
herTrueorFalse.
=>LogicalExpressionalsocalledCompundCondi t
ion.
=>Wehav
e3t
ypesofLogi
cal
Oper
ator
s.Theyar
egi
veni
nthef
oll
owi
ngt
abl
e.

SLNO Sy
mbol Meani
ng

1. and Physi
calANDing
2. or Physi
calORing
3. not -
--
--
---
--
--
--
--
--
--
--
--

1)and oper
ator
:
=>Thefunctionali
tyof'and'operatorisshowni nthefoll
owingTruthTabl
e.
-
---
---
--
--
--
--
--
--
---
--
---
--
--
--
--
---
---
---
--
----
--
--
--
--
--
--
---
--
--
--
--
--
--
---
-
RelExpr1 RelExpr 2 Rel Expr1andRel Expr
2
-
---
---
--
--
--
--
--
--
---
--
---
--
--
--
--
---
---
---
--
----
--
--
--
--
--
--
---
--
--
--
--
--
--
---
-
True Fal se False
False Tr ue False
False Fal se False
True Tr ue True
-
---
---
--
--
--
--
--
--
---
--
---
--
--
--
--
---
---
---
--
----
--
--
--
--
--
--
---
--
--
--
--
--
--
---
-
Examples:
--
--
--
--
--
--
--
---
-
>>>pri
nt(100>20and20>10) --
--
---
--
--
Tr ue
>>>pri
nt(100<20and20>10) --
--
---
--
--
Fal se
>>>pri
nt(100!=20and20! =20)--
---
--
---
Fal se
>>>pri
nt(20!=20and20! =20)--
--
---
--
-False

2)oroper ator:
=>Thefuncti
onal i
tyof'or'operatorisshowni nthefoll
owingTruthTabl
e.
-
--
--
----
--
--
--
--
--
---
---
---
--
--
---
--
---
--
--
---
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
RelExpr 1 RelExpr 2 Rel Expr1orRelExpr
2
-
--
--
----
--
--
--
--
--
---
---
---
--
--
---
--
---
--
--
---
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
True False True
False True True
False False False
True True True
-
--
--
----
--
--
--
--
--
---
---
---
--
--
---
--
---
--
--
---
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
Examples:
>>>pri
nt(100!=20or20! =20)--
---
--
---
True
>>>pri
nt(100<=20or2! =20) -
--
---
--
---
True
>>>pri
nt(100>=20or- 12!=-12)--
--
---
--
-True
>>>pri
nt(100==20or- 12!=-12)--
---
--
--
-False

Note:
-TheShortCir
cuitEvaluati
oninthecaseof'or'
operat
oristhat"Iforoper
atori
s
connect
edwithn-r
elati
onalexpressi
onsandifFi
rstrel
ati
onalExpressi
onisTruethen
remaini
ngr
elati
onalexpressionswil
lnotbeeval
uatedandresulti
sconsideredasTrue"
.

Note:
-TheShortCir
cuitEvaluati
oninthecaseof'
and'operatoristhat"If'
and'operat
ori
s
connect
edwithn-r
elati
onalexpressi
onsandifFir
strel
ati
onal Expressi
onisFalsethen
remaini
ngr
elati
onalexpressionswil
lnotbeeval
uatedandr esulti
sconsideredasFalse"
.

3)notoper
ator
:-
-
--
--
--
--
--
--
--
--
--
--
--
--
--
=>Thi
soperatorgi
vesopposit
er esul
tofBool
eanVal
ue.
=>Thefunct
ional
it
yof'
not'operatori
sshowninthef
oll
owi
ngTr
uthTabl
e.

-
--
---
--
--
--
--
---
---
---
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
RelExpr1 notRelExpr1
-
--
---
--
--
--
--
---
---
---
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
True False
False True
-
--
---
--
--
--
--
---
---
---
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
Examples:
>>>pr
int(10<=2and1000>=200) -
--
--
--
--
--Fal
se
>>>pr
int(not(10<=2and1000>=200)) --
---
--
-True
>>>pr
int(not(not(
10<=2and1000>=200)) )-
--
-Fal
se
>>>pr
int(10>2)-
--
-True
>>>pr
int(not10>2)---
--
False
>>>pr
int(10==2)-
---
-False
>>>pr
int(not10==2) -
--
---
True

5.Bi
twi
seOper
ator
s(MostI
mp)
=>BitwiseOper atorsareAppl i
cableonI nt egerdataonl ybutnotappl i
cabl
eon
fl
oatingpoi ntvaluesbecauset heyar ev aryi
ngprecision.
=>Thepur poseofBi twi
seOper atorsist hat" Converti
ngI ntegerdat
ainter
nall
yinto
BinaryFor matandPer f
or msBinaryOper at i
onsinthef orm BitbyBitandfi
nalresul
t
al
way sdi splayedinthef orm deci
mal numbersy stem ".
=>Sincet heoper ati
onsar ecarryi
ngouti nt heform ofBi tbyBitandHencethese
operatorsar enamedasBi t
wiseOper ator s.
=>InPy thonPr ogrammi ng,wehav e
1.BitwiseLeftShiftOper ator(<<)
2.BitwiseRightShiftOper ator(>>)
3.Bitwise'and'Operator(&)
4.Bitwise'or'
Operat or(| )
5.Bitwisecompl ementOper ator(~)
6.Bitwise'xor'
Oper ator(^)

1.Bitwi
seLeftShif
tOperator(<<):
Syntax:
- v arname=Giv enData<<No.ofBi
ts
=>Theconceptofbitwi
sel ef
tshif
toperat
orsayst
hat"Shiftspeci
fi
ednumberofbi t
s
towardslef
tbyaddingnumberofzer osatri
ghtsi
de(no.ofzeros==no.ofspeci
fi
ed
numberofbi t
s)
================================================================

Exampl es:
>>>a=10
>>>res=a<<3
>>>print(res)
--
--
--
--
--
-80
>>>print(24<<2)-
--
--
--
-96
>>>print(2<<2)-
--
--
--
--
8
>>>print(12<<3)-
--
--
--
-96
>>>print(5<<4)-
--
--
--
--
-80

2.Bi
twi
seRi
ghtShi
ftOper
ator(>>)
:

Sy
ntax:
- v
arname=Gi
venDat
a>>No.
ofBi
ts

=>Theconceptofbi
twi
serightshi
ftoper
atorsay
sthat"Shif
tspeci
fi
ednumberof
bi
tstowardsri
ghtbyaddi
ngnumberofzer osatl
eftsi
de(no.ofzer
os==no.of
specf
iednumberofbit
s)
Examples:
>>>c=a>>3
>>>pri
nt(c)-
--
--
--
-1
>>>pri
nt(12>>2)-
--
--
-3
>>>pri
nt(12>>3)-
--
-1
>>>pri
nt(12>>4)-
--
-0
>>>pri
nt(36>>4)-
--
-2

3.Bit
wise'and'Operator(&) :
=>Syntax:
-v ar
name=Val ue1&Val ue2
=>TheFunctionali
tyofBi t
wise'and'Operatorisexpressedinthef ol
l
owi
ngt
rut
h
tabl
e.
-
--
--
--
---
--
--
---
--
--
--
--
--
--
--
---
--
--
--
---
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
Input1 Input2 I
nput1&I nput2
-
--
--
--
---
--
--
---
--
--
--
--
--
--
--
---
--
--
--
---
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
0 1 0
1 0 0
0 0 0
1 1 1
-
--
--
--
---
--
--
---
--
--
--
--
--
--
--
---
--
--
--
---
--
--
--
--
--
--
--
--
--
---
--
--
--
--
---

Example1:
--
--
--
--
--
--
--
--
--
>>>a=10-
---
--
--
--
--
--
--
--
--
--
--1010
>>>b=15-
---
--
--
--
--
--
--
--
--
--
--1111
>>>c=a&b--
--
--
--
--
--
--
--
--
--
-1010---
--
>resul
tis10
>>>pri
nt(
c)-
---
>10
Examples:
>>>pr
int(3&4)-
--
--
--
--
-0
>>>pr
int(10&3)-
--
--
--
-2

SpecialCase:
>>>s1={10,20,
30}
>>>s2={40,30,
50}
>>>s3=s1.int
ersecti
on(s2)
>>>pri
nt(s3)-
--
--
---
--
{30}
>>>s4=s1&s2
>>>pri
nt(s4)-
--
--
--{
30}
4.Bit
wise' or
'Operator(|):
=>Syntax:-v arname=Val ue1|
Val
ue2

=>TheFunctionali
tyofBitwise'or'
Oper at
orisexpressedinthefol
lowi
ngt
rut
htabl
e.
-
--
--
--
--
--
--
--
--
---
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
I
nput1 Input2 Input
1| I
nput2
-
--
--
--
--
--
--
--
--
---
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
0 1 1
1 0 1
0 0 0
1 1 1
-
--
--
--
--
--
--
--
--
---
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
Examples:
>>>a=10---
--
--
--
--
---
--
--
--
->1010
>>>b=7---
--
--
--
--
--
---
--
--
--
>0111
>>>c=a|b--
--
--
--
--
--
---
--
--
->1111--
--
---
--
-->resul
tis15
>>>pri
nt(c)-
--
--
--
--
-15
>>>pri
nt(3|
4)--
--
--
---
-7
5.Bi
twisecompl ementOper at
or(~) :

Syntax:
-v arname=~Val ue
=>Thisoper atorobtainscompl ementofthegivennumber
Exampl es:
>>>a=10----
--
--
---
---
--
--
--
----
>1010
>>>b=~a- -
--
---
---
--
--
--
--
---
--->~(1010+0001)
-(1010)
0001)
=-(1011)
--
--
>Resul
tis-
11
>>>a=15
>>>b=~a- -
--
---
---
--
--
->~( 1111+1)
-
(1111
+0001)=-10000---
--
->r
esul
tis-16
>>>a=13
>>>b=~a
>>>print(b)
---
---
--
--
---
--- 14
>>>a=345
>>>print(~a)-
---
---
--
--
--
-- 346
6.Bi
twi
se'
xor
'Oper
ator(^)
:
--
--
--
--
--
------
--
--
----
---
--
--
--
---
--
--
--
---
--
--
---
=>Syntax: -v arname=Val ue1^Val ue2
=>TheFunct ionalit
yofBi twise'xor'
Oper atorisexpressedinthefol
l
owi
ngt
rut
h
tabl
e.
--
---
--
--
--
--
--
---
---
--
--
--
--
---
--
--
---
---
--
--
--
--
--
--
--
--
--
---
I
nput1 I
nput2 I nput
1^I nput2
--
---
--
--
--
--
--
---
---
--
--
--
--
---
--
--
---
---
--
--
--
--
--
--
--
--
--
---
--
0 1 1
1 0 1
0 0 0
1 1 0
--
---
--
--
--
--
--
---
---
--
--
--
--
---
--
--
---
---
--
--
--
--
--
--
--
--
--
---
--
--
Exampl es:
>>>a=3-----
--
----
--
---
-0011
>>>b=4-----
--
----
--
---
-0100
>>>c=a^ b---
--
----
---
--
-0111- ---
--
--
--
--
-Resultis7
>>>pri
nt (c)-
--
-7
>>>print(15^ 10)---
5

Speci
alCase:
>>>s1={10,20,
30,40}
>>>s2={10,40,
50,60}
>>>s3=s1.symmet ri
c_ difference(s2)
>>>pri
nt(s3)-
--
--
--
---
{50, 20, 60,30}
>>>
>>>s4=s1^s2
>>>pri
nt(s4)-
--
--
--
---
-{50, 20, 60,30}

#Swappi
ngofv
aluesusi
ngxor(
^)oper
ator

a=i
nt(i
nput("Ent
erav al
ueofa:"
))
b=i
nt(i
nput("Enteraval
ueofb:"
))
pri
nt(
"-"
*50)
pri
nt(
"Valuesofaandbaf terswappi
ng"
)
pri
nt(
"-"
*50)
a=a^b
b=a^b
a=a^b
pri
nt(
"a:{
}\nb:{
}".
for
mat(a,
b))
pri
nt(
"-"
*50)

OUTPUT:
Ent
erav al
ueofa:30
Ent
erav al
ueofb:40
-
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
---
Val
uesofaandbaf terswapping
-
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
---
a:40
b:30
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-

==================================x============================

6.Member
shi
pOper
ator
s

=>Thepur poseofMember shipOper ator sist hat"Tocheckt hespecif


iedvalueinany
It
erableobj ect" .
=>AnI terableobj ecti sone, whi chcont ainsmul ti
pleelements(Sequencet ype,li
st
type,sett ypeanddi ctt y pe) .
=>InPy thon, Wehav et wot y peofMember shi pOper ator
s.Theyar e
a)i n
b)noti n
a)in:
--
---
--
---
--
---
Syntax:- v arname=Val uei nI t
erable_obj ect
=>Ifthe" Value"pr esenti nI terable_objectt henI tretur
nsTr ueotherwiseitretur
ns
False.
=>Her e"var name"cont ainsTr ueorFal seandwhoset ypeisbool.
b)noti n:
--
---
--
---
--
---
--
Syntax:- v arname=Val uenoti nI terable_ object
=>Ifthe" Value"notpr esenti nIterabl
e_ objectt henI tr
eturnsTrueot herwi
sei t
retur
nsFal se.
=>Her e"var name"cont ai nsTr ueorFal seandwhoset ypeisbool.
Exampl es:
--
---
--
---
--
---
--
>>>s=" PYTHON"
>>>" P"ins- --
--
---
---
--Tr ue
>>>" P"noti ns- --
--
--Fal se
>>>" T"noti ns- -
---
--
Fal se
>>>" T"ins- --
--
---
---
Tr ue
>>>" K"ins- --
--
---
---
-Fal se
>>>" K"noti ns- --
--
----
Tr ue
>>>" TH"i ns- -
---
--
--
----Tr ue
>>>" TH"noti ns---
-------
Fal se
>>>" THON"noti ns- ----
---Fal se
>>>" THON"i ns- -
--
-----Tr ue
>>>s=" PYTHON" --
----
----
>>>" PTO"i ns- --
--
--
---Fal se
>>>" PYT"i ns- --
--
--
----Tr ue
>>>" PYON"i ns- -
--
----
---Fal se
>>>" PYON"noti ns- -
-------Tr ue
>>>" HON"noti ns-------
-Fal se
>>>" HON"i ns- -
--
--
----Tr ue
>>>" NOH"i ns- -
--
--
----Fal se
>>>"
NOH"noti
ns--
--
--
--
--
True
>>>"
NOH"i
ns[:
:-
1]-
--
--
--
--
-Tr
ue

>>>lst
=[10,20,30, 40,"py thon"]
>>>10noti nl st-----
---
--Fal se
>>>10i nlst-
----
------
-Tr ue
>>>"python"i nlst --
---
-----
Tr ue
>>>"python"noti nlst------
--
---
-False
>>>"pyt"i
nl st---
- -
---
-Fal se
>>>pri
nt (
lst[
4])------
---
-py thon
>>>"pyt"i
nl st[4]----
---
---Tr ue
>>>"pyt"noti nl st[4]-
-----
----
False
>>>"pt"notinl st [4]--
----
-----
True
>>>"noh"noti nl st[4]-
------
--Tr
ue
>>>"noh"inl st[4]----
--
----False
>>>"noh"inl st[4][::
-1]---
-----
-True
>>>"nh"noti nl st [
4][:
:-1]----
---
--
--
-True
--
--
--
--
--
---
--
---
---
---
------
---
-----
----
---
-X--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-

7.I
dent
it
yOper
ator
s
=>ThepurposeofI
dentit
yOperator
sisthat"Tocompar
etheMemor
yAddr
essof
obj
ects"
.
=>TogetMemor yAddressofanobject/var
iabl
e,weusei
d()
.
=>I
nPy t
hon,wehavetwoI dent
it
yOperator
s.Theyar
e
1)is
2)isnot

a)i
s:
Syntax:
-v arname=obj 1isobj2
=>Thisoperatorret
urnsTruepr
ovi
dedobj
1andobj
2cont
ainsSameAddr
ess
otherwi
seitrertur
nsFalse.

b)isnot:
Syntax:
-v arname=obj 1isnotobj2
=>Thisoperatorr
etur
nsTrueprovi
dedobj
1andobj
2cont
ainsDi
ff
erentAddr
ess
otherwi
seitretur
nsFalse.

Examples:
>>>a=None
>>>b=None
>>>pri
nt(i
d(a)
)-
---
--
--
--
--
--
--
--
140716433311736
>>>pri
nt(i
d(b)
)--
--
--
--
--
--
--
--
-140716433311736-
>>>aisb---
--
--
--
True
>>>aisnotb---
--
--
-Fal
se

>>>d1={
10:
"Appl
e",
20:
"Ki
wis"
}
>>>d2={
10:
"Appl
e",
20:
"Ki
wis"
}
>>>pr
int(
id(
d1))
--
--
--
---
--
---
-2896803430144
>>>pr
int(
id(
d2))
--
--
--
---
--
---
2896803363776
>>>d1isd2--
--
--
--
--
--
-False
>>>d1isnotd2---
--
--
---
True

>>>s1={10,
20,30}
>>>s2={10,
20,30}
>>>pri
nt(i
d(s1))--
--
---
--
---
-2896803638944
>>>pri
nt(i
d(s2))--
--
---
--
---
2896803637152
>>>s1iss2----
---
--
--
-False
>>>s1isnots2- --
--
---
--
Tr ue
>>>fs1=fr
ozenset (
s1)
>>>fs2=fr
ozenset (
s2)
>>>pri
nt(i
d(fs1))-
--
---
--
-----
2896803636928
>>>pri
nt(i
d(fs2))-
--
---
--
---2896803638496
>>>fs1isfs2---
--
---
-False
>>>fs1isnotf s2--
---
--
--True

>>>l
1=[10, "
Rossum" ,
"Py t
hon"]
>>>l
2=[10, "
Rossum" ,
"Py t
hon"]
>>>pri
nt(id(l
1))-
--
--
--
--
--2896803430016
>>>pri
nt(id(l
2))-
--
--
--
--
----
--
--
--
-2896803473856
>>>l
1i sl2---
--
--
--
--
--
--
--
----
-Fal
se
>>>l
1i snotl 2-
--
--
--
--
--
--True
>>>t1=tuple(l
1)
>>>t2=tuple(l
2)
>>>pri
nt(id(t
1))-
--
--
--
--
----
2896803468800
>>>pri
nt(id(t
2))-
--
--
--
--
----
-2896803470528
>>>t1ist2---
---
--
--
--
False
>>>t1isnott 2--
--
--
--
--
Tr ue

>>>r1=range( 10,20)
>>>r2=range( 10,20)
>>>pri
nt(id(r1))-
---
--
----
-2896803585632
>>>pri
nt(id(r2))-
---
--
----
2896803585824
>>>r1isr2- -
---
---
-False
>>>r1isnotr 2--
---
--
-True
>>>b1=by tes([10,20,30,40] )
>>>b2=by tes([10,20,30,40] )
>>>pri
nt(id(b1) )
---
--
---
----2896803584624
>>>pri
nt(id(b2) )
---
--
---
---2896803585776
>>>b1isb2- -
---
--
----
---
Fal se
>>>b1isnotb2- -
---
---
Tr ue
>>>ba1=by tear r
ay (
[10,20, 30,
40]
)
>>>ba2=by tear r
ay (
[10,20, 30,
40]
)
>>>pri
nt(id(ba1) )-
--
---
--2896803726768
>>>pri
nt(id(ba2) )-
--
---
-2896803726960
>>>ba1i sba2- --
---
--False
>>>ba1i snotba2- ---
--
--True
>>>s1="I
NDI A"
>>>s2="I
NDI A"
>>>pri
nt(i
d(s1))-
--
--
--2896803726640
>>>pri
nt(i
d(s2))-
--
--
----
2896803726640
>>>s1iss2----
--
--
---
True
>>>s1isnots2- --
---
---
False
>>>s3="pyt
hon"
>>>pri
nt(i
d(s3))-
--
--
----
-2896803725360
>>>s1iss3----
--
--
-False
>>>s1isnots3- -
---
--
-True

>>>a=2+3j
>>>b=2+3j
>>>pri
nt(
id(a)
)-
---
--
--
--
2896799652016
>>>pri
nt(
id(b)
)--
--
--
--
--
2896799651888
>>>aisb---
--
--
--
False
>>>aisnotb---
--
--
---
True

>>>a=12.
3
>>>b=12.
3
>>>pri
nt(
id(a)
)-
---
--
---
---
-2896799647728
>>>pri
nt(
id(b)
)--
--
--
---
--2896799648336
>>>aisb---
--
--
--
--
--
--
Fal se
>>>aisnotb---
--
--
--True

>>>a=True
>>>b=True
>>>print
(i
d(a)
)
140716433259368
>>>print
(i
d(b)
)
140716433259368
>>>aisb
True
>>>aisnotb
False

>>>a=100
>>>b=100
>>>pri
nt(
id(a)
)
2896798616912
>>>pri
nt(
id(b)
)
2896798616912
>>>aisb---
--
--
--
--
--
- True
>>>aisnotb---
--
--
---
--
--
--
-False
>>>a=257
>>>b=257
>>>pri
nt(
id(a)
)-
---
--
--
--
--
--
--
--
--2896799652016
>>>pri
nt(
id(b)
)--
--
--
--
--
--
--
--
---
-2896799652176
>>>aisb---
--
--
--
--
--
--
---
--
--
--
--
 False
>>>ai snotb---
--
--
-----
---
--
---
Tr ue
>>>a=300
>>>b=300
>>>print
(id(a)
)-
---
----
--
---
--
--2896799652208
>>>print
(id(b)
)--
--
----
--
---
--
 2896799652016
>>>ai sb---
--
--
--
--
--
----
---
 Fal se
>>>ai snotb---
--
--
-----
---
--
-Tr ue
>>>a=256
>>>b=256
>>>print
(id(a)
)-
---
----
--
---
--
--2896798621904
>>>print
(id(b)
)--
--
----
--
---
--
--2896798621904
>>>ai sb---
--
--
--
--
--
----
---
-Tr ue
>>>ai snotb---
--
--
-----
---
-Fal se
>>>a=-4
>>>b=-4
>>>print
(id(a)
)-
---
----
--
---
-2896798613584
>>>print
(id(b)
)---
----
--
---
--
2896798613584
>>>ai sb---
--
--
--
--
--
-Tr ue
>>>ai snotb---
--
--
-----
--Fal se
>>>a=-5
>>>b=-5
>>>print
(id(a)
)---
----
--
---
--
2896798613552
>>>print
(id(b)
)---
----
--
---
--
2896798613552
>>>ai sb---
--
--
--
--
--
-Tr ue
>>>ai snotb---
--
--
-----
--Fal se
>>>a=-6
>>>b=-6
>>>print
(id(a)
)---
----
--
---
--
2896799652144
>>>print
(id(b)
)---
----
--
---
--
2896799652080
>>>ai sb---
--
--
--
--
--
----
---
-Fal se
>>>ai snotb---
--
--
-----
--Tr ue
==============================================================
>>>a,b=300,300
>>>print
(id(a)
)-
---
----
--
-2896799652080
>>>print
(id(b)
)--
--
----
--
2896799652080
>>>ai sb---
--
--
--
--
Tr ue
>>>ai snotb---
--
--
-----
-False
>>>a,b=-10,-
10--
--
----
---
---
--
>>>ai snotb---
--
--
---False
>>>ai sb---
--
--
--
-True
============================X===================================
===============================================================
FlowCont r
ol St at ement sinPy t
hon
(OR)
Cont r
ol Str
uct ur esi nPython---
8day s
================================================================
=>Thepur poseofFlowCont r
olStatement si nPy t
honi sthat" Toperform Cer
tain
Operat
ionei t
herOnceorPer formt heoper ationRepeat edlyforf i
nit
enumberof
ti
mesunt ilCondit
ionisFalse".
=>InPythonPr ogramming, Fl
owCont rol St atement sarecl assif
iedinto3types.They
are 1.Condit
ional /Selection/Br anchingSt atement s
2.Loopi
ng/I t
erati
ve/Repet i
ti
veStatement s
3.MiScFl owCont r
ol St atement s(br
eak, conti
nue,pass)
1.Condi
ti
onal
/Sel
ect
ion/Br
anchi
ngSt
atement
s
=>Thepur poseoft hi
soper at
ionist
hattoperfor
m cert
ainoper
ati
ononl
yonce
dependsoncondi tionevaluati
on.
=>Inotherwordsper form certai
nX-operat
ionwhencondit
ioni
sTRUEorperf
orm Y-
operat
ionwhencondi t
ionisFALSE.
=>inPythonwehav e4t y
pesofCondi ti
onal/Sel
ecti
on/Branchi
ngStat
ements.
Theyare:
1)si
mpl eifst
atement
2)i
f…..
elsestat
ement
3)i
f…eli
f…elsestatement
4)match…casest atement
1)
simpl
eifst
atement
:
Syntax:
I
f(
TESTCondi ti
on): (t
hat:iscal
ledIndentati
onSymbol
)
Statement1
Statement2
……………. (t
hatblockiscall
edIndentati
onBl
ock)
St
atement-n
Otherstatementinpyt
honprogram
Fl
owchar
tforsi
mpl
eifst
atement
:

ENTRY

TEST
CONDITIO
N
TRUE
FALS

Execut
eIndent
ati
onblockof
Stat
ements.

Execut
eot
herst
atementi
nthepr
ogr
am
Explanat
ion:
=>Her ei
fisakeyword.
=>IftheTESTCONDI TIONisTRUEt henPVM executesindentat
ionbl
ockof
statementsandlat
erexecutesotherstat
ementsintheprogram.
=>IftheTESTCONDI TIONisFALSEt henPVM executesotherstat
ementsi
nthe
program wit
houtexecuti
ngindentat
ionblockofst
atements.

PROGRAMS:
#mov iee.py
tkt=i
nput (
"Duhav eat i
cket(yes/no):
")
i
f (
tkt
.l
ower ()=="yes"):
print(
"Enterintotheater")
print(
"wat chmov ee")
print(
"Enjoy..
")
print
("
\ nGotoHomeandReadPYTHONNOTES" )
#posnegzer o.
py
n=int(
input("Enteranumber :
"))# n- -10
i
f (
n>0):
print(
"{}isPossiti
ve".f
ormat(n))
i
f (
n<0):
print(
"{}isNegative"
.format(n)
)
i
f (
n==0) :
print(
"{}isZero".
format(n))
print
("
Pr ogram compl eted")

#ev enoddno
n=int(i
nput("
Enteranumber :
")
)
i
f(n%2==0) :
pr i
nt("
{}i
seven."
.for
mat(n))
i
f(n%2! =0):
pr i
nt("
{}i
sodd.".
format
(n))
2.i
f….
elsest
atement
Sy
ntax:
If
(TESTCONDI TION):
Statement-1
Statement-2
-
---
---
--
--
--
--
-
Statement-ns
else:
Statement-11
Statement-22
-
---
---
--
--
--
--
-
Statement-nn
Otherstatementsi nt
hepr
ogr
am

ENTRY

TEST
FALSE CONDITIO TRUE

Execut
eIndentat
ionbl
ockof‘
i
f’ Execut
eIndentat
ionbl
ockof‘
el
se’
st
atements st
atements

Execut
eot
herst
atement
sint
hepr
ogr
am

Expl
anat
ionofi
f….
.el
seSt
atement
:

=>Her e‘
if’
and‘el
se’arethekeywords.
=>IftheTESTCONDI TIONi sTRUEt henPVM execut esIndentati
onbl ockof‘i
f’
Statementandlaterexecuteotherstatementsintheprogram( Wit
houtexecut ing
i
ndent at
ionbl
ockof‘ el
se’stat
ement )
.
=>IftheTESTCONDI TIONi sFALSEt henPVM execut esIndentat
ionbl ockof‘else’
Statementandlaterexecuteotherstatementsintheprogram( Wit
houtexecut ing
i
ndent at
ionbl
ockof‘ i
f’st
atement).
Henceanypoi ntofti
mePVM execut eeitherI
ndentati
onblockof‘ i
f’statementor
I
ndent at
ionbl
ockof‘ el
se’stat
ementandl at
erexecutesotherstatement sinthe
program.
EXAMPLE1:
#WPPwhi chwillacceptanumeri
cal
numberanddeci
dewhet
heri
tisev
enorodd.
#ev enoddex1.py
n=int(i
nput("Ent
eranumber :
")
)
i
f(n%2==0) :
pr i
nt(
"{}isEven."
.for
mat(n))
el
se:
pr i
nt(
"{}isOdd.".
format(
n))
OUTPUT:
Enteranumber :975
975i sOdd.

EXAMPLE- 2:
#wr i
teapy thonprogram whichwi l
lacceptanynumer
ical
int
egerv
alueanddeci
de
whet heritispositi
ve,negati
veorzero.
#posnegzer oex1.
py
n=int(i
nput("Enteranumber :
"))
i
f(n==0) :
print(
"{}i
sZer o."
.f
ormat (
n))
el
se:
if
(n>0):
print("
{}isPositi
ve."
.f
ormat(n))
else:
print("
{}isnegati
ve.".
for
mat (
n))
OUTPUT:
Enteranumber
:2122
2122isPosi
ti
ve.

EXAMPLE- 3_ _
______
____________
______
____
______
_____
____
______
____
__
#WPPwhi chwi l
lacceptanal phabetfr
om keyboardanddecidewhetheri
tisv
owel
or
consonant.
#vowelcon1.py
a=input(
"Enteranalphabet:")
i
f(a.l
ower()in["
a",
"e",
"i
",
"o",
"u"]
):
pri
nt("
{}isVowel.".
format(a))
el
se:
pri
nt("
{}isConsonant .
".
format(a))
______
_________
________
__________
______
____
______
_____
____
______
_
OUTPUT:
Enteranalphabet:R
RisConsonant .
EXAMPLE-
3

#WPPwhi chwi ll acceptt heempl oyeeno., employeenameandempl


oyeesal
aryand
calculat et henetsal ar y.
#emppay slip.py
eno=int (input ("
Ent erempl oyeenumber :
"))
ename=i nput (
"Ent erempl oyeename: ")
basicsal =f loat (i
nput ("enterbasi csal aryofempl oyee:
")
)
i
f(basi csal >=10000) :
da=( 20/ 100) * basi csal
ta=( 15/ 100) *basi csal
hra=( 12/ 100) * basi csal
cca=( 2/ 100) *basi csal
ma=( 2/ 100) *basi csal
gpf =(2/ 100) *basi csal#deduct ion
li
c=( 1/ 100) *basi csal #deduct ion
el
se:
da=( 25/ 100) * basi csal
ta=( 20/ 100) *basi csal
hra=( 16/ 100) * basi csal
cca=( 3/ 100) *basi csal
ma=( 2/ 100) *basi csal
gpf =(2/ 100) *basi csal#deduct ion
li
c=( 1/ 100) *basi csal #deduct ion
netsal=( basi csal +da+t a+hra+cca+ma) -(gpf+li
c)
#di splayt hepaysl ip
pri
nt (
"-"* 60)
pri
nt (
"\ tEmpl oy eepaysl ipfort hemont hoff eb-2022"
)
pri
nt (
"-"* 60)
pri
nt (
"\ tEmpl oy eenumber :{
}".f
ormat (eno))
pri
nt (
"\ nEmpl oyeename: {}"
.format (ename) )
pri
nt (
"\ tEmpl oy eebasi csalary:{}"
.format (
basicsal)
)
pri
nt (
"\ tEmpl oy eeda: {
}".
format (da))
pri
nt (
"\ tEmpl oy eet a:{}".
format(ta))
pri
nt (
"\ tEmpl oy eehr a:
{}".
format (hra))
pri
nt (
"\ tEmpl oy eecca: {}
".f
ormat (cca) )
pri
nt (
"\ tEmpl oy eema: {}".
format (ma) )
pri
nt (
"\ tEmpl oy eegpf :
{}".
format (gpf))
pri
nt (
"\ tEmpl oy eel i
c: {
}".
format (l
ic))
pri
nt (
"-"* 60)
pri
nt (
"\ tEmpl oy eenetsal ary:{}
".f
or mat (netsal)
)
pri
nt (
"-"* 60)
OUTPUT:
Enterempl oyeenumber :
123
Enterempl oyeename:Ritesh
enterbasicsalaryofempl oyee:
35000
--
--
---
--
--
--
--
--
----
--
--
--
--
--
--
--
--
--
----
--
--
--
--
--
--
--
--
-
Empl oyeepaysli
pf orthemont hoff
eb-
2022
--
--
---
--
--
--
--
--
----
--
--
--
--
--
--
--
--
--
----
--
--
--
--
--
--
--
--
-
Empl oyeenumber:123

Employeename: Rit
esh
Empl oyeebasicsalary:
35000.0
Empl oyeeda:7000.0
Empl oyeeta:5250.0
Empl oyeehra:4200.0
Empl oyeecca:700.0
Empl oyeema: 700.0
Empl oyeegpf :
700.0
Empl oyeeli
c:350.0
-
--
--
--
--
--
---
--
--
---
--
--
--
--
--
---
---
--
--
--
--
--
--
--
--
--
--
--
-
Empl oyeenetsalary:
51800.0
-
--
--
--
--
--
---
--
--
---
--
--
--
--
--
---
---
--
--
--
--
--
--
--
--
--
--
--
-
i
f….
eli
f….
elseSt
atement
:
Sy ntax:
If
(TestCondi ti
on-1):
Execut
eBl ockofSt atement -
1
eli
f (
TestCondition-2)
:
Execut
eBl ockofSt atement -
2
eli
f (
TestCondition-3)
:
Execut
eBl ockofSt atement -
3
--
----
---
--
--
--
--
--
--
--
---
--
--
---
--
--
---
---
--
--
--
--
----
---
--
--
--
--
--
--
--
---
--
--
---
--
--
---
---
--
--
--
eli
f (
TestCondition-n)
:
ExecuteBlockofSt atement -
n
else:
Execute‘
else’BlockofSt atement.

FLOW CHART:

TEST
Execut
esBl
ockofSt
atement
s-1
COND-
1

TEST Execut
eselseBl
ockof
COND-
St
atement
s-2

--
--
--
--
--
-
-
--
--
--
--
--
--

TEST
COND-N
Execut
eselseBl
ockof
St
atement
s-n

ExecuteselseBl
ockof Execut
esot
herSt
atement
sint
he
Stat
ements pr
ogr
am
Explanat i
onf orif…elif….el
sest atement:
=>Her eifthet estcondi ti
on- 1istruePVM executeblockofstatements-1andalso
executesot herst atement sint heprogram.
=>Ifthet estcondi t
ion- 1isfalset heneval
uatetestcondit
ion-2andifiti
struethe
PVM execut esblockofst atement- 2andalsoexecuteotherstatement
sinpr ogr
am.
Thispr ocesswi llperformedunt il
allt
estcondi
ti
onar eevaluat
ed.
=>Ifalltestcondi t
ionar efalset henexecuteel
seblockofst at
ementswhi chare
writi
ngundert heel seblock.
=>Wr i
tingelsebl ocki sopt i
onal .

EXAMPLE:
#WPPwhi chwi llaccept sthreeintegerval
ueandf
indbi
ggestamongt
hem.
#bigex1.py
a=int(i
nput("
Ent erfirstnumber :"
))
b=int(i
nput("
Ent ersecondv alue:
"))
c=int(i
nput("
ent erthirdvalue:")
)
i
f(a>b)and(a>c):
print(
"max( {
},
{ }
,{
}):{}
".
format (
a,b,c,
a))
el
if(b>a)and(b>c):
print(
"max( {
},
{ }
,{
}):{}
".
format (
a,b,c,
b))
el
if(c>a)and(c>b):
print(
"max( {
},
{ }
,{
}):{}
".
format (
a,b,c,
a))
el
if(a==b)and(b==c) and( a==c):
print(
"Allv
aluesar eequal .
")
OUTPUT:
Enterfir
stnumber :67
Entersecondv alue:89
enterthirdvalue:45
max( 67,89,
45) :
89
4.mat
chcasest
atement
=>match….
caseisoneoft
henewf eaturei
nPyt
hon3.10onwards
=>matchcasestat
ementisalwaysrecommendedt
odealwithpre-
def
ined/
desi
gneddecisi
ons/Operat
ions.

=>Sy
ntax:
-

mat
ch(ChoiceExpression):
caseLable1:
ExecuteBlockofstatements-1
caseLabel-2:
ExecuteBlockofstatement
s-2
caseLabel-3:
ExecuteBlockofstatements-3
--
--
--
---
--
--
--
--
--
--
---
---
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
---
---
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
caseLabel-n:
ExecuteBlockofstatement
s-n
case_:
executedefaul
tcaseblock
Expl
anat
ion:

=>Her e'match''case' ar
ekey words.
=>"Choi ceExpression"canbeei t
herInteger,Char, Stri
ng,bool .
=>Label 1,
Label2..
..
label-
ncanbeI nt
eger, Char, St r
ing,bool.
=>Ifthev al
ueofChoi ceExpressi
onismat chingwi t
hLabel -
1t henPVM execut es
correspondingBl ockofSt at
ement -
1.
=>Ifthev al
ueofChoi ceExpressi
onisnotmat chingwi thLabel -
1anditismat chi
ng
withLabel -
2thenPVM execut escorrespondi ngBl ockofSt atement-2andHence
Thiscompar i
sonpr ocesswi l
lbecont i
nuedwi thal l
CaseLabel sandtheymat ches
PVM execut esCor respondingBlockofst atement s.
=>Ifthev al
ueofChoi ceexpressi
onisnotmat chingwi thanycasel abel
st henPVM
executesdef aultcaseblockst at
ement swhi char ewr it
tenundercase_ :
=>Wr i
tingthedef aultcaseblockwi t
hcase_ :i sopt i
onal

EXAMPLE- 1:
#Writ
eapy thonprogram whi
chcal
cul
atear
eaofdi
ff
erentf
igur
es.
#matcharea.py
pri
nt(
"-
"*50)
pri
nt(
"\t
Areaofdiff
erentfi
gur
e")
pri
nt(
"-
"*50)
pri
nt(
"\t
1.Cir
cle"
)
print("\t2.Rect angl
e")
print("\t3.Squar e")
print("\t4.Triangle"
)
print("\t5.Exit"
)
print("-
"* 50)
ch=int (i
nput (
"EnterYourchoi ce:"
))
print("-
"* 50)
mat ch( ch) :
case1:
r=float (
input("
Ent erradiusofci rcl
e:"))
print (
"Areaofci rcle:
{}"
.format ((
22/ 7)*r*
r )
)
case2:
l
,b=f loat(i
nput("EnterLengt hofr ect angle:"
)),
fl
oat
(input
("Enterbr
eadt
hof
rectangl e:"))
print (
"AreaofRect angle:{}"
.f
or mat(l*b))
case3:
s=f l
oat (i
nput (
"Entersideofasquar e:"))
print (
"AreaofSquar e:{
}".format (
s*s) )
case4:
b,h=f loat(
input("EnterbaseofaTr i
angl e:"
)),
fl
oat(
input(
"Enterhei
ghtofa
Triangl e:"))
print (
"AreaofTr i
angle:{}".
format (
0.5* b*h))
case5:
print (
"\nThanksf orusingpr ogram! ")
exit()
case_ :
print (
"Yourchoi cei swrong! " )
print("-
"* 50)
OUTPUT:
-
--
--
--
--
--
--
---
--
--
---
--
--
--
--
---
--
--
--
--
--
--
--
--
Areaofdi f
ferentfi
gure
-
--
--
--
--
--
--
---
--
--
---
--
--
--
--
---
--
--
--
--
--
--
--
--
1.Cir
cle
2.Rectangl
e
3.Square
4.Tri
angle
5.Exi
t
-
--
--
--
--
--
--
---
--
--
---
--
--
--
--
---
--
--
--
--
--
--
--
--

EnterYourchoi
ce:3
-
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
-
Entersi
deofasquar e:
9
AreaofSquare:
81.0
-
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
-
=============================================================
2.Loopi
ng(or)It
erat
ive(or)Repet
it
iveStatements
=============================================================
=>Thepur poseofLoopi
ngstatementsisthat"ToPerf
orm certai
nOper at
ion
repeat
edlyforfi
nit
enumberoft i
mesunt i
lTestcondi
ti
onbecomesFal se"
.
=>InPythonProgramming,wehav e2typesofLoopingstatements.Theyare

a)whi
leloop (or
)whi
le.
..
.el
seLoop
2)f
orloop ( or
)for
..
..
elseLoop
=>Atti
meofdeal
i
ngwi
thl
oopofPython,
wemustensurethatt
her
emustexi
sts3
poi
nts.

1)
Ini
ti
ali
zati
onPart
2)
Conditi
onalPart
3)
UpdationPart(
IncrementorDecrement)
=================================X==============================

Expl
anat
ionf
orwhi
l
eloop:
=>Her
e‘whi
l
e’and‘
el
se’
arekeywor
ds.
=>iftheTestcondit
ionistruet
henexecut
eblockofst
atementsandonceagain
evaluateTestcondi
tionandifiti
sTRUEthenagai
nexecuteblockofst
atementsand
thi
spr ocesswil
lber epeat
edforfi
nit
enumberofti
mesuntil
Testcondit
ionbecomes
FALSE.
=>I
fTestcondi
ti
onbecomesFALSEt henexecut
esel
sebl
ockofst
atement
s(I
fwe
wri
te)
andalsoexecut
eotherst
atementsi
ntheprogr
am.
=>Wr
it
ingel
sebl
ocki
sopt
ional
.
EXAMPLE- 1
#Wr iteapy t
honpr ogr am whi chwilldisplay1tonnumber
swher
eni
sposi
ti
ve.
#display no1.py
n=int(i
nput ("Enterhowmanynumbery ouwanttodi
spl
ay:
")
)
i
f(n<=0) :
print("isinv al
idinput.".
format(n))
el
se:
i=1
print("Rangeofv aluewi thi
n:{}"
.f
ormat (n)
)
whi l
e( i
<=n) :
pr i
nt (
"valueofi :
{}".
format (
i)
)
i=i+1
else:
pr i
nt (
"Iam f r
om el separtofwhi lel oop.
")
pri
nt("Iam ot herpartofpr ogram.")

EXAMPLE-
2

#Wr iteapy t
honprogram whichwil
lacceptanynumer
ical
int
egerv
alueanddispl
ay
evennumberwi thini
t
#whi l
eev en.py
n=int(i
nput ("
Enteranynumbert opr
intevenno:"
))
i
f(n<0) :
print("
Invali
dInput.
")
el
se:
i=2
print("
*"*50)
print("
Ev ennumber sare"
)
print("
*"*50)
whi l
e(i<=n):
pr i
nt("\t
{}"
.f
ormat(i
))
i=i+2
else:
pr i
nt("*"
*50)
================================================================
EXAMPLE- 3

#Wri
teapythonpr
ogram whi
chwi
l
lacceptanynumer
ical
int
egerv
alueanddi
spl
ay
oddnumberwithi
nit
#whi
leodd.
py

n=int
(input(
"Enteranynumbert
opr
intoddno:
")
)
i
f(n<0):
pri
nt("I
nvali
dInput.
")
el
se:
i=1
pr
int
("*"
*50)
pr
int
("Evennumbersare"
)
pr
int
("*"
*50)
whil
e(i
<=n):
print(
"\t
{}"
.f
ormat
(i
))
i=i
+2
el
se:
print(
"*"
*50)

EXAMPLE:
-4

#Wr iteapy t honpr ogram whichwi l


lgener at
emul t
ipl
icat
iontabl
eforgi
venposi
ti
ve
i
ntegerv alue.
#whi l
emul .py
n=int(i
nput ("Enteranumbert ogener atetable:
")
)
i
f(n<0) :
print("I
nv al idInput")
el
se:
print("-
"*50)
print("Tabl eof :{}
".
format(n))
print("-
"*50)
i=1
whi l
e(i<=10) :
pr i
nt ("
\ t{}x{}
={}"
.format(
n,i
,n*
i))
i=i+1
else:
pr i
nt ("
-"* 50)
EXAMPLE: -5
#WPPwhi chwi llacceptanumberandf i
ndsum oft hedigi
tsofthegi
vennumber.
#sumdi git.py
n=int(i
nput ("Enteranumber :"
))
i
f(n<0) :
print("{}isi nvalidinput"
.f
ormat(n))
el
se:
print("Giv ennumberi s:{
}".
format(n))
s=0
whi l
e(n>0) :
d=n%10
s=s+d
n=n/ /10
else:
pr i
nt ("
sum ofdi gits:{
}".
format(
s) )

EXAMPLE:-6
#WPPwhi chwi
l
lacceptast
ri
ngandpr
inti
tsr
ever
sor
der
.
#rev
ers.
py
str=i
nput (
"enteranywor d:"
)
s=str[
::-
1]
pri
nt(s)
EXAMPLE- 7
#WPPwhi chwi l
lacceptast r
ingandpr i
nti
tispal
i
ndr
omeornot
.
#pali
ndr om. py
str=i
nput (
"enteranywor d:"
)
s=str[
::-
1]
pri
nt("Reversofinputstringis:"
,s)
i
f(s==str):
pri
nt (
"{}ispali
ndrome.".f
ormat (
str
))
el
se:
pri
nt (
"{}isnotpali
ndrome. ".
format(
str
))

EXAMPLE-
8:
#wwpt oprintreverseofinputst
ri
ng
#r
ev erseex1.py
st
r=input("
Ent eranystri
ng:"
)
l
=len(str)
pr
int("
Lengthofst r
ing:"
,l
)
i
=l-1
whil
e(i>=0):
pri
nt(str
[i
])
i
=i-1

EXAMPLE- 9:
#whilereverse.py
st
r=input (
"Enteranyword:")
l
=len(str)
pri
nt("Reversofinputstri
ng:"
)
i
=l-1
whil
e(i>=0):
pri
nt (
str[
i],
end=""
)
i
=i-1
el
se:
pri
nt (
"\n")
pri
nt (
"="*50)
i
f(str==str[
::
-1]
):
print(
"{}ispal
indr
ome" .for
mat(st
r))
el
se:
print(
"{}isnotpal
indrome" .
for
mat(str
))
f
orl
oop (
or)f
or.
..
.el
seLoop
=>Thepur poseoff orloopi sthattor
etr
iev
ethedat
aorext
ractt
hedat
afr
om any
It
erabl eobject.
=>Sy ntax1:
forv arnamei nIterable_Object:
----
--
---
--
--
--
---
--
--
---
--
---
--
--
----
-
--
---
--
--
--
---
--
--
---
---
--
---
--
--
--
--
Bl
ockofSt atement s
-
--
---
--
--
--
---
--
--
---
---
--
---
--
--
--
--
-
--
---
--
--
--
---
--
--
---
---
--
---
--
--
--
--
--
---
--
----
--
---
--
--
--
--
---
--
--
---
--
---
--
---
-
OtherSt atement sinProgr am
--
---
--
----
--
---
--
--
--
--
---
--
--
---
--
---
--
---
-
(OR)
--
---
--
----
--
---
--
--
=>Sy ntax2:
--
---
--
----
--
---
--
--
forv arnamei nIterable_Object:
----
--
---
--
--
--
---
--
--
---
--
---
--
--
----
-
--
---
--
--
--
---
--
--
---
---
--
---
--
--
--
--
Bl
ockofSt atement s
-
--
---
--
--
--
---
--
--
---
---
--
---
--
--
--
--
-
--
---
--
--
--
---
--
--
---
---
--
---
--
--
--
--
else:
--
---
--
---
--
--
---
--
--
--
---
--
---
--
----
-
elseblockofst atement s
--
---
--
---
--
--
---
--
--
--
---
--
---
--
----
-

--
---
---
--
-----
---
--
---
---
---
---
--
--
--
--
---
--
OtherSt atement si nProgram
--
---
---
--
-----
---
--
---
---
---
---
--
--
--
--
---
--
Explanat ion:
=>Her e' for','
in','el
se'arethekey words
=>Var namer epr esentsPr ogrammerchoi ce
=>Iterabl eobjectr epresentsanyobj ectcont
ainsmulti
plevalueslikesequence,l
ist
,
setanddi dcttypes.
=>Theexecut ionpr ocessoff orloopisthat"EachEl
ementofI terableObjectsel
ect
ed,
placedi nVar nameandexecut esBlockofstatements".Thi
sPr ocesswi l
lberepeat
ed
forfinitenumberoft imes
(len(iterable_obj ect))uni t
lallelementsarecompletedinIt
erable_object.

=>AfterallelementsofIterable_
Objectofforl
oopcomplet
edandi tindi
cat
es
condtionoff orl
oopi sfalseandlaterexecut
eselsebl
ockofstat
ement swhichar
e
writ
teni nelseblock.Afterexecuti
ngblockPVM execut
esOtherstatement
si n
Program
=>Wr i
tingelseblockisopt i
onal.
Note1:-ForI ter
bale_obj
ectsrepetati
on,Iti
srecommendedforusi ng"forLoop"
Note2:
-ForNon-
It
erbal
e_obj
ect
srepet
ati
on,
Iti
srecommendedf
orusi
ng"whi
l
e
Loop"

Exampl
e:1

#Thi spr ogram extr actsorretri


evet
hef
rom gi
venst
ri
ng
#forloopex 1.py
s="PYTHON"
pri
nt("Byusi ngwhi lel oop")
i
=0
whi l
e(i
<len(s) )
:
pr i
nt(s[i
])
i=i+1
pri
nt("="*50)
pri
nt("Byusi ngf orloop" )
forval i
ns:
pr i
nt(val)
pri
nt("="*50)
pri
nt("Byusi ngwhi lel oop")
l
st=[10,"Rossum" ,
34. 56,"
Python"]
i
=0
whi l
e(i
<len(lst))
:
pr i
nt(l
st[i
])
i=i+1
pri
nt("="*50)
pri
nt("Byusi ngf orloop" )
forval i
nl st:
pr i
nt(val)
pri
nt("="*50)
pri
nt("Byusi ngwhi lel oop")
r=range(100, 106)
j
=0
whi l
e(j
<len(r)):
pr i
nt(r[
j]
)
j=j+1
pri
nt("="*50)
pri
nt("Byusi ngf orloop" )
forval i
nr :
pr i
nt(val,
end="" )

EXAMPLE:
2

#WPPwhi chwi l
lgenerat
e1tonnumber
.wher
eni
sposi
ti
ve(
usef
orl
oop)
#fornumgenex1. py
n=int(
input("
Enteranumber:
")
)
i
f(n<=0):
pri
nt("i
nvali
dInput"
)
el
se:
pri
nt("-
"*50)
print
("Number swithi
n:",
n)
print
("-
"*50)
foriinrange(1,n+1):
pri
nt("{}
".
format(i
),
end=""
)
else:
pri
nt("\n"
)
pri
nt("-
"*50)

EXAMPLE: 3
#WPPwhi chwi llacceptanyi nt
egerval
ueandgener
ateev
enno.andoddno.
separ ately.
#forev enodd. py
n=int(input (
"Enteranumber :
"))
i
f(n<=0) :
print("inval
idI nput"
)
el
se:
print("-"*
50)
print("Evennumber swithin:",
n)
print("-"*
50)
forev eninr ange(2,n+1,
2) :
pr int("
{}"
.format (
even),end="" )
else:
pr int("
\n")
pr int("
-"*
50)
pr int("
Oddnumber swi thin:
",
n)
pr int("
-"*
50)
foroddi nr ange(1,n+1,2) :
pr i
nt("
{}".
format (
odd) ,end="")
el se:
pr i
nt("
\n")
pr i
nt("
-"*50)
================================================================

EXAMPLE: 4
#WPPwhi chwi l
l acceptanynumerical
int
egerv
alueanddi
spl
aymul
ti
pli
cat
ion
table,wher eni sposi t
ive.
#formul t
abl e.
py
n=int(input ("
Ent eranumber :")
)
i
f(n<=0) :
print("Invali
di nput .
")
else:
print("-"*50)
print("Mul ti
plicatintabl
eof :
",
n)
print("-"*50)
fori inr ange( 1,11):
print("\t
{}x{}={}"
.f
ormat(n,
i,
n*i
))
else:
print(
"_"*50)
EXAMPLE: 5
#WPPwhi chwi l
lf i
ndsum offirstnnaturalnumber,sum ofit
ssquar
esandsum ofi
ts
cubes.
#forsumsqcube. py
n=int(input("Enteranumber :")
)
i
f(n<=0) :
print("i
nv ali
dinput .
")
el
se:
s,ss,sc=0, 0,
0
fori inrange( 1,n+1):
s=s+i
ss=ss+i **2
sc=sc+i **3
i
=i+1
else:
print(
"Sum ofnumberf rom 1to{ }
:{
}".
format(n,
s))
print(
"Sum ofsquar eofnumberf r
om 1t o{}:
{}"
.for
mat (
n,ss)
)
print(
"Sum ofcubeofnumberf rom 1to{ }
:{
}".
format(n,
sc))

Exampl
eoff
orl
oop

EXAMPLE: 1
#sqcube. py
n=int(input ("
Ent er1stnnat ur
alno.t ocalcul
atei
tssum ofno.
,
sq,
cube.
")
)
i
f(n<=0) :
print("InvalidInput."
)
el
se:
s,ss,sc=0, 0,0
print("-"*50)
print("\tno.\tsquare\tcube"
)
print("-"*50)
fori inr ange( 1,
n+1):
s=s+i
ss=ss+i **2
sc=sc+i **3
print("\t
{}\t{}
\t{
}".
format(
i,
i**2,i
**3)
)
else:
print("-
"*50)
print("\t
{}\t{}
\t{
}".
format(
s,ss,sc))
print("-
"*50)

EXAMPLE:
2

#cal
cul
atesum ofanumberusi
ngl
i
st.
#li
stsum. py
n=int(i
nput ("
Ent erhowmanyel ementyouwantt
oadd:")
)
i
f(n<=0) :
print
("i
nv alidinput."
)
el
se:
lst=l
ist()
foriinr ange( 1,
n+1):
print("Enter{}element:
".
format
(i
))
#m=fl
oat(
input
("
Enter{
}el
ement
:"
.f
ormat
(i
))
)
m=f loat(input())
lst.
append( m)
else:
print("Youent ered:
",
l
st)
s=0
forv al i
nlst:
print (
"\t{
}".
format(v
al))
s=s+v al
else:
print (
"sum=" ,
s)
print (
"Avg=",s/l
en(l
st)
)

EXAMPLE: 3
#sumav g1.py
n=int(input ("Howmanyel ementyouwantt
oadd:"
))
i
f(n<=0) :
print("Inv al
idInput."
)
el
se:
i=1
s=0
whi le(i<=n) :
v al=f l
oat (i
nput("
Enter{
}val
ue:".
for
mat
(i)
))
s=s+v al
i=i+1
else:
pr int("Sum=" ,s)
pr int("Av g=",
s/n)

EXAMPLE- 4:
#wppwhi chwi l
lacceptli
stofnumerical
val
uesandsortthem i
nascendi
ndand
desendi ngor der.
#sortno.py
n=int(
input ("
Enterhowmanyel ementyouwantt
osort:
"))
i
f(n<=0) :
pri
nt("Invali
dInput .
")
el
se:
lst
=list()
foriinr ange(1,n+1):
val=i
nt( i
nput ())
lst.
append( val)
el
se:
print
("Youent ered:",
l
st)
print
("Valuesi nascendingorder
:"
)
lst.
sort()
forval inlst:
print(val,
end="" )
else:
print()
print("val
uesi ndescendi
ngorder:
")
lst.
sor t
( r
ev erse=True)
forv alinlst :
print(val,end="" )

EXAMPLE: -5
#wppwhi chwi l
lacceptl i
stofvaluesandsortthem i
nascendi
ndanddesendi
ng
order.
#sor twor d.py
n=int(input ("Enterhowmanyel ementy ouwanttosort
:"
))
i
f(n<=0) :
print("Inv ali
dI nput .
")
el
se:
lst=list()
fori inr ange( 1,n+1) :
v al=input ()
lst .
append( val)
else:
pr int("Youent ered:",
l
st)
pr int("Valuesi nascendingorder:"
)
lst .
sor t()
forv al inlst:
print (val,
end="" )
el se:
print ()
print ("val
uesi ndescendi
ngor der:
")
lst.sor t
( r
ev erse=True)
forv alinlst :
print(val,end="" )

EXAMPLE- 6
#wr i
teapy t
honpr ogram whi
chwil
lobt
ainr
ever
seofgi
vennumber
.
#reverseno.py
n=int(
input(
"Enteranyint
egernumber
:"
))
i
f(n<=0):
pri
nt("I
nvali
dinput"
)
el
se:
i
=1
rvs=0
d=0
while(n>0):
d=n%10
rvs=rvs*10+d
n=n/ /10
else:
print(
"Reversedofanumber:"
,r
vs)
OUTPUT: -
Enteranyi nt
egernumber :
12345
Reversedofanumber :54321

#Thisprogr
am accept i
ngageofCiti
zenanddeci
deel
i
gibl
etov
oteornot
.
#VoterEx1.
py
age=int
(i
nput(
"EntertheageofCit
izen:
")
)
i
f(age>=18)
:
pri
nt(
"Cit
izenisel
igi
blet
oVot e:
")
el
se:
pri
nt(
"Cit
izenisnotel
igi
bletoVote:
")

#Thi
spr ogram accepti
ngageofCi t
izenanddecideeli
gibl
etov
oteornot
.
#VoterEx2.py
whil
e(True):
age=int(
input(
"Ent
ertheCorrectageofCit
izen:
"))
if(
age>=18)and( age<=100):
break

pr
int
("{}yearsoldCi ti
zeniseli
gibl
etoVot e:
".
for
mat (
age))
#Thi
spr ogram acceptingageofCi t
izenanddecideeligi
blet
ovot
eornot
.
#VoterEx3.py
ct
r=0
whil
e(ctr
<3) :
age=int(i
nput("Ent
ertheCorrectageofCit
izen:"
))
if(
age>=18)and( age<=100):
break
ctr=ctr
+1

i
f(
ctr
==3):
pri
nt(
"Ulosturchanceregi
ster
ingasvot
eranduareblocked"
)
el
se:
pri
nt(
"{}y
earsoldCiti
zeniseli
gibl
etoVote:
".
for
mat(
age))
#StudentMar ksReport.
py
stno=int
(input(
"EnterStudentNumber:
")
)
sname=i nput("
EnterStudentName:"
)
#validat
ionofCmar ks
while(Tr
ue) :
cm=int(i
nput("
EnterMarksi
nC:"))
i
f(cm>=0)and( cm<=100):
break

#v ali
dationofCPPmar ks
whi l
e(True) :
cppm=i nt(i
nput("
Ent erMarksinCPP:")
)
i
f(cppm>=0)and( cppm<=100) :
break
#v ali
dationofPYTHONmar ks
whi l
e(True) :
pym=i nt(input(
"EnterMar ksinPYTHON: "
))
i
f(py m>=0)and( pym<=100) :
break
#cal cul
at etotalandper cent ageofmarks
totmar ks=cm+cppm+py m
per marks=( totmar ks/300)*100
#deci dest hegr ades
i
f(cm<40)or( cppm<40)or( pym<40):
grade=" FAIL"
else:
i
f(totmar ks<=300)and( t
otmarks>=250):
grade="DISTINCTION"
i
f(totmar ks<=249)and( t
otmarks>=200):
grade="FI
RST"
i
f(totmar ks<=199)and( t
otmarks>=150):
grade="SECOND"
i
f(totmar ks<=149)and( t
otmarks>=120):
gr ade=" THI RD"
#Displayt heMar ksMemo
pri
nt("="*70)
pri
nt("\tStudentM arksReport ")
pri
nt("="*70)
pri
nt("\tStudentNumber :{
}".format (st no) )
pri
nt("\tStudentName: {}
".
for mat (sname) )
pri
nt("\tStudentMar ksi nC:{ }
".f
or mat ( cm) )
pri
nt("\tStudentMar ksi nCPP: {
}".format (cppm) )
pri
nt("\tStudentMar ksi nPYTHON: {}".
f ormat (pym) )
pri
nt("-"*70)
pri
nt("\tStudentTot al Mar ks:{}"
.format ( totmar ks))
pri
nt("\tStudentPer cent ageofMar ks:{ }".
f or
mat (permarks)
)
pri
nt("-"*70)
pri
nt("\tStudentGr ade: {}
".
for mat (grade) )
pri
nt("="*70)
#WPPwhi chwi llacceptempl oyeeno., empl oyeenameandbasi
csal
aryand
calculatenet salaryandshowpay slip.
#empsal ex2. py
empno=i nt (
input (
"Ent eraempl oy eenumber :
")
)
empname=( i
nput ("Ent ernameofempl oy ee:"
))
while(True) :
basicsal =int(input ("Enterbasi csal ar yofempl oyee:
")
)
if(
basi csal>=1000) and(basi csal <=10000) :
br eak
pri
nt("basi csal ary:",
basi csal )
i
f(basicsal >=1000) and( basi csal<=5000) :
hra=( 15* basicsal )/100
da=( 20* basicsal )/100
ta=(14* basi csal)/100
ma=( 4*basi csal)/100
gpf=( 2*basi csal)/100
li
c=( 2*basi csal)/100
el
se:
hra=( 15* basicsal )/100
da=( 20* basicsal )/100
ta=(14* basi csal)/100
ma=( 2*basi csal)/100
gpf=( 2*basi csal)/100
li
c=( 2*basi csal)/100
netsal=basi csal +(hra+da+t a+ma) -(gpf +l i
c)
pri
nt("-"*60)
pri
nt("\t\templ oy eepaysl i
p" )
pri
nt("-"*60)
pri
nt("\tEmpl oyeenumber :{
}".f
ormat (empno) )
pri
nt("\tEmpl oyeename: {}".
format (empname) )
pri
nt("\tEmpl oyeebasi csalar y
:{}"
.for mat (basicsal))
pr
int
("
\tEmploy
eeda:{
}".
format(da))
pr
int
("
\tEmploy
eeta:
{}"
.f
or mat(
ta))
pr
int
("
\tEmploy
eehra:
{}"
.format(hra)
)
pr
int
("
\tEmploy
eema:{}"
.format(ma))
pr
int
("
\tEmploy
eegpf:
{}"
.format(gpf)
)
pr
int
("
\tEmploy
eel
ic:{
}".
format(
lic))
pr
int
("
-"
* 60)
pr
int
("
\tEmploy
eenetsalary:
{}
".
format (
net
sal
))
pr
int
("
-"
* 60)

OUTPUT:

Enteraempl oy eenumber :123


Enternameofempl oy ee:Pooja
Enterbasicsal aryofempl oyee:
7000
basicsalary:7000
--
--
--
--
--
---
---
--
----
----
--
---
----
--
---
---
--
--
--
--
--
--
--
--
-
empl oy eepaysl ip
--
--
--
--
--
---
---
--
----
----
--
---
----
--
---
---
--
--
--
--
--
--
--
--
-
Empl oy eenumber :
123
Empl oy eename: Pooj a
Empl oy eebasi csal ary:
7000
Empl oy eeda: 1400. 0
Empl oy eeta:980. 0
Empl oy eehr a:1050. 0
Empl oy eema: 140.0
Empl oy eegpf :140.0
Empl oy eelic:140.0
--
--
--
--
--
---
---
--
----
----
--
---
----
--
---
---
--
--
--
--
--
--
--
--
-
Empl oy eenetsal ary:
10290.0
--
--
--
--
--
---
---
--
----
----
--
---
----
--
---
---
--
--
--
--
--
--
--
--
-

br
eak
=>breakst
atementisusedforter
mi nati
ngtheexecuti
onprocessofLoopi
ng
prov
idedcertai
ncondit
ionsat
isfi
ed.
=>breakst
atementalwaysusedinsideofloopstatement
s.
=>whenweusebr eakstatementinsideoftheLoop,PVM contr
olcomesoutofl
oop
andexecut esot herst atement sint heprogram butnotcor
respondi
ngel
sebl
ockof
l
oop.
=>Syntax1:-
--
--
--
--
--
---
--
-
forvarnamei nIterable_Object:
-
---
---
--
---
---
--
----
--
---
--
--
--
--
-
if
(TestCond) :
break
else:
el
sebl ockofst atement s
--
---
--
--
---
--
----
---
---
--
---
---
--
----
--
---
-
Otherstat ement sinPr ogram
-
---
---
--
--
---
--
----
---
---
--
---
---
--
----
--
---
--

--
---
--
---
---
---
--
=>Sy ntax2: -
--
---
--
---
---
---
--
whi l
e(TestCond)
--
----
---
--
--
--
--
---
--
--
--
---
--
---
-
i
f(TestCond) :
br eak
else:
elsebl ockofst atement s
---
---
--
---
---
----
---
--
--
--
---
--
--
--
---
--
---
Ot herstat ement sinProgram
--
---
---
---
--
---
----
---
--
--
---
--
--
--
--
---
--
---
-
============================================X=======================
==
#breakex1. py
s="PYTHON"
forvi ns:
i
f(v==" O"):
break
else:
print("
\t{
}".
format(v))
else:
print("
iam f r
om elseoff orloop")

pr
int
("
Otherst
atement
sinpr
ogr
am"
)

#breakex2.py
l
st=[10,
"Rossum",
34.56,
True,2+3j
]
forvali
nlst:
if
(val
==True):
break
else:
pri
nt("
\t{
}".
format
(val
))
#breakex3. py
d={10:"Python",20:"
DataSci enece",30:
"Dj
ango",
40:"
Java"
}
fork,vind.items( ):
if(k==30) :
break
else:
pri
nt("
\t{
}-
-->{}
".f
or mat(
k,v)
)
#Thispr ogram acceptanumberanddeci dewether
eiti
spr
imeornot
#primeex1. py
n=int(
input("EnteraNumber :
")
)
i
f(n<=1) :
print(
"{}isinvali
dinput:".
format(n))
else:
result=True
fori i
nr ange(2,n)
:
i
f(n%i==0):
result=False
break

if
(result):
pr
int
("{
}isPr i
me:".
for
mat (
n))
else:
pr
int
("{
}isnotPr i
me:".
for
mat(n)
)
#Thispr ogram acceptanumberanddeci dewether
eiti
spr
imeornot
#primeex2. py
n=int(
input("EnteraNumber :"
))
i
f(n<=1):
print(
"{}isinv
ali
di nput:
".
format
(n))
el
se:
result="Pri
me"
fori i
nr ange(
2,n):
i
f(
n%i==0) :
result
="NotPri
me"
break

i
f(
resul
t=="
Prime"
):
pr
int
("
{}i
sPri
me:"
.f
ormat(
n))
el
se:
pr
int
("
{}i
snotPr
ime:"
.f
ormat
(n)
)

#Thispr ogram acceptanumberanddecidewet


her
eiti
spr
imeornot
#primeex3. py
n=int(
input("EnteraNumber:"
))
i
f(n<=1):
print(
"{}i
sinv
ali
dinput:
".
for
mat
(n))
el
se:
result=0
foriinrange(2,n)
:
i
f(
n%i ==0):
resul
t=1
break
#otherstatement s
i
f(resul
t==0):
pr
int
("{}isPri
me:"
.f
ormat(
n))
else:
pr
int
("{}isnotPr
ime:"
.f
ormat
(n)
)

Cont
inuest
atement
=>conti
nueisoneofthekeyword
=>Thepurposeofconti
nuestatementisthatt
omakecontr
oltot
opofthel
oopf
or
thatcur
renti
terat
ionwi
thoutexecut
ingthefol
lowi
ngst
atementwri
tt
enaft
er
conti
nuestatement

Syntax1:
-
-
--
---
---
--
--
-
whi
le(
Testcond1) :
-
--
---
---
--
--
--
--
--
-
-
--
---
---
--
--
--
--
--
-
i
f(Testcond2):
-
--
--
--
--
---
--
-
conti
nue
--
--
--
--
--
--
--
-
statementswr i
tt
en-aftercont
inuest
atement
-
--
--
--
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
-
--
--
--
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-

Syntax2:
-
-
--
---
---
--
--
-
f
orvarnamei niterable-
object
-
--
---
---
--
--
--
--
--
-
-
--
---
---
--
--
--
--
--
-
i
f(Testcond):
-
--
--
--
--
---
--
-
conti
nue
--
--
--
--
---
---
-
statementswr i
tt
en-af t
erconti
nuest
atement
-
--
--
--
--
---
--
--
---
--
--
--
---
---
--
---
--
--
--
--
--
--
--
--
--
--
-
--
--
--
--
---
--
--
---
--
--
--
---
---
--
---
--
--
--
--
--
--
--
--
--
--
#conti
nueex1.py
s="PYTHON"
#wantt odispl
ay PYTON
forvins:
if
(v=="H"
):
cont
inue
el
se:
pr
int
("
\t{
}".
for
mat
(v)
)
el
se:
print("el
separ toff orloop")
print("
-"*60)
#wantt odi splay PYTN
forvi ns:
if
(v==" H")or (v=="O" )
:
cont inue
else:
pr i
nt (
"\t{
}".
format (v
))
#cont inueex1. py
s=" PYTHON"
#wantt odi splay PYTON
i
=0
whi le(
i<l
en( s)):
if
(s[ i
]=="H" ):
i=i+1
cont inue
else:
pr i
nt (
s[i]
)
i=i+1
print("
-"*60)
#wantt odi splay PYTN
i
=0
whi le(
i<l
en( s)):
if
(s[ i
]=="H" )or(s[i]
==" O"):
i=i+1
cont inue
else:
pr i
nt (
s[i]
)
i=i+1
#Thi sPr ogram f indsum of+v enumber sand-v
enumber
ssepar
atel
y.
#cont inueex3. py
l
st =[10,-
20,30, 40,-
34, -45,89,
-3,23,6]
ps=0
forv alinlst:
if
(val<0) :
cont inue
else:
pr i
nt (
"\t\
t{}"
.format(val
))
ps=ps+v al
else:
print("Possi t
iveSum={ }
".f
ormat(ps)
)
print("="*60)
ns=0
forv al i
nl st:
if(val>0):
cont i
nue
el
se:
pri
nt(
"\t
\t{
}".
for
mat
(val
))
ns=ns+val
el
se:
pr
int
("
Negat
iveSum={
}".
for
mat
(ns)
)
pr
int
("
="*
60)

#ThisProgram acceptalineoftextanddisplaytheVowels
#conti
nueex4py
l
ine=i
nput("Ent
eralineoftext:
")#Py thonisanoopl ang
forvinl
ine:
ifvnotin['
a',
'
e',
'i
'
,'
o'
,'
u'
,'
A',
'
E',
'
I'
,'
O',
'
U']
:
continue
else:
print
("\t
{}andwhosei ndex={}
".
format(
v,l
i
ne.
index(
v))
)

Nest
ed(
or)I
nnerLoops
=>ThePr ocesswr i
ting/Def iningonel oopi nsideofanot herloopiscal
ledNested/
I
nnerLoop.
=>Theexecut i
onPr ocessofnest ed/i nnerloopi st hat"
ForEv eryVal
ueofOuter
Loopinnerloopr epeatedf orfini
tenumberoft imes.
--
--
--
--
--
---
--
--
--
---
--
--
---
---
--
---
--
--
---
---
---
--
--
--
---
---
---
--
--
---
---
-
=>Syntax1:(forl oopi nf orloop)
--
--
--
--
--
---
--
--
--
---
--
--
---
---
--
---
--
--
---
---
---
--
--
--
---
---
---
--
--
---
---
-
forv arnam1i nIterable_object: #out erforLoop
--
---
--
---
--
---
--
--
---
--
---
---
---
--
---
-
forv arnam2i nIterable_object: #I nnerf
orLoop
---
--
--
---
--
---
---
--
---
--
---
--
---
---
--
-
else:
---
---
--
--
---
--
--
---
---
---
--
---
--
---
--
else:
-
--
---
--
---
--
---
--
---
--
--
---
---
---
--
---
--
--

Exampl es:
--
--
---
--
--
---
---
---
-
#innerl
oopsex1. py
print
("-
"*40)
foriinrange( 1,
6):
print(
"Valofi-
Outerloop={
}".
format(i
))
print(
"-
"*40)
forjinrange(1,
4):
pri
nt(
"\t
Valofj-I
nnerloop={}
".f
ormat
(j
))
else:
pri
nt(
"-"
*40)
pri
nt(
"iam outofinnerloop"
)
pr
int
("
-"
*40)

el
se:
pr
int
("
Iam outofout
erf
orl
oop"
)
pr
int
("
-"
*40)

--
--
--
--
--
---
--
--
--
--
--
--
--
--
---
--
---
--
---
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
=>Syntax2:(whil
el oopi nwhileloop)
--
--
--
--
--
---
--
--
--
--
--
--
--
--
---
--
---
--
---
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
----
--
--
---
---
--
--
--
--
--
whi l
e( t
estcond1) :#Out erwhil
eloop
--
---
--
---
--
--
--
---
--
-
while(Testcond2) :#innerwhil
eloop
-
---
--
---
--
--
--
---
--
--
-
--
--
---
--
--
---
--
--
--
-
else:
-
---
--
---
--
--
--
---
--
-
else:
-
---
--
---
--
--
--
---
--
--
--

Exampl es:
--
--
---
--
--
---
---
-
#innerl
oopsex2. py
print
("-
"*40)
i
=1
whi l
e(i
<6):
print
("Val ofi-
-outerwhil
el oop=",i
)
print
("-
"*40)
j=1
whi l
e(j
<4):
pr i
nt(
"\tValofj-
innerwhi l
eloop=",
j
)
j=j+1
else:
pr i
nt(
"-"
*40)
pr i
nt(
"\tiam out-ofinnerwhil
eloop")
i=i+1
pr i
nt(
"-"
*40)
el
se:
print
("iam out -
ofouterwhi leloop"
)

--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
---
--
--
---
---
----
--
--
--
---
--
=>Syntax3:(whil
eloopinf orloop)
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
---
--
--
---
---
----
--
--
--
---
--
forvarnam1i nIterable_object: #outerf
orLoop
---
--
--
--
---
--
---
--
--
---
---
--
---
---
--
--
whi l
e(Testcond2) :#i nnerwhi
lel
oop
-
---
--
---
--
---
--
---
--
-
-
---
--
---
--
---
--
---
--
-
el
se:
--
---
--
---
--
---
---
--
-
el
se:
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-

Exampl e:
--
---
--
---
---
---
#innerloopsex3. py
print
("-
"* 40)
foriinr ange( 1,
6):#out erloop
print(
"Val ofi-Outerforloop={ }"
.format (
i)
)
print(
"-"
*40)
j=3
whi l
e(j
>0):#I nnerloop
pr i
nt("\t
Val ofj-
innerwhi l
el oop=",
j
)
j=j-
1
else:
pr i
nt("-
"*40)
pr i
nt("\t
iam out -ofinnerwhi l
eloop")
pr i
nt("-
"*40)
else:
print(
"Iam outofout erforl oop")
print(
"-"
*40)
--
---
--
---
---
----
---
--
--
---
--
---
----
--
---
--
---
--
--
---
---
---
--
--
----
---
--
--
--
=>Sy nt
ax4:f orloopi nwhi l
eloop
--
---
--
---
---
----
---
--
--
---
--
---
----
--
---
--
---
--
--
---
---
---
--
--
----
---
--
--
--
----
--
---
---
--
--
---
---
--
--
whi le(testcond1) :#Out erwhilel
oop
---
---
--
---
--
---
--
--
--
forv arnam2i nIterable_object
: #Innerf
orLoop
---
--
--
----
--
---
--
--
---
---
---
--
--
--
--
--
else:
---
--
---
--
--
---
---
---
--
--
----
---
--
--
--

el
se:
--
--
--
--
--
--
--
--
--
--
--
--

Exampl es:
--
--
---
--
--
---
---
#innerl
oopsex4. py
print
("-
"*40)
i
=1
whi l
e(i
<6):
print
("Val ofi-
-outerwhileloop=",i
)
print
("-
"*40)
forjinrange( 1,4):
pr i
nt(
"\tValofj-
Innerforloop={}
".
for
mat
(j
))
else:
i=i+1
pr i
nt(
"-"*40)
pr i
nt(
"i am outofinnerforloop"
)
pr i
nt(
"-"*40)
el
se:
pri
nt(
"iam out
-ofouterwhi
leloop"
)
=============================X==================================

Nest
ed(
or)I
nnerLoops
=>ThePr ocesswr i
ting/Def iningonel oopi nsideofanot herloopiscal
ledNested/
I
nnerLoop.
=>Theexecut i
onPr ocessofnest ed/i nnerloopi st hat"
ForEv eryVal
ueofOuter
Loopinnerloopr epeatedf orfini
tenumberoft imes.
--
--
--
--
--
---
--
--
--
---
--
--
---
---
--
---
--
--
---
---
---
--
--
--
---
---
---
--
--
---
---
-
=>Syntax1:(forl oopi nf orloop)
--
--
--
--
--
---
--
--
--
---
--
--
---
---
--
---
--
--
---
---
---
--
--
--
---
---
---
--
--
---
---
-
forv arnam1i nIterable_object: #out erforLoop
--
---
--
---
--
---
--
--
---
--
---
---
---
--
---
-
forv arnam2i nIterable_object: #I nnerf
orLoop
---
--
--
---
--
---
---
--
---
--
---
--
---
---
--
-
else:
---
---
--
--
---
--
--
---
---
---
--
---
--
---
--
else:
-
--
---
--
---
--
---
--
---
--
--
---
---
---
--
---
--
--

Exampl es:
--
--
---
--
--
---
---
---
-
#innerl
oopsex1. py
print
("-
"*40)
foriinrange( 1,
6):
print(
"Valofi-
Outerloop={
}".
format(i
))
print(
"-
"*40)
forjinrange(1,
4):
pri
nt(
"\t
Valofj-I
nnerloop={}
".f
ormat
(j
))
else:
pri
nt(
"-"
*40)
pri
nt(
"iam outofinnerloop"
)
pri
nt(
"-"
*40)

el
se:
pr
int
("
Iam outofout
erf
orl
oop"
)
pr
int
("
-"
*40)

--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
---
---
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
=>Syntax2:(whil
eloopi nwhi l
eloop)
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
---
---
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
---
--
--
--
---
--
-
while(testcond1):#Out erwhil
eloop
-
--
--
--
----
--
--
--
--
--
-
whil
e(Testcond2):#i nnerwhil
eloop
--
---
--
--
--
---
--
--
--
--
-
--
--
--
--
--
--
--
--
--
--
-
el
se:
--
--
--
--
--
--
--
--
--
--
-
el
se:
--
--
--
--
--
--
--
--
--
--
--
--

Exampl es:
--
--
---
--
--
---
---
-
#innerl
oopsex2. py
print
("-
"*40)
i
=1
whi l
e(i
<6):
print
("Val ofi-
-outerwhil
el oop=",i
)
print
("-
"*40)
j=1
whi l
e(j
<4):
pr i
nt(
"\tValofj-
innerwhi l
eloop=",
j
)
j=j+1
else:
pr i
nt(
"-"
*40)
pr i
nt(
"\tiam out-ofinnerwhil
eloop")
i=i+1
pr i
nt(
"-"
*40)
el
se:
print
("iam out -
ofouterwhi leloop"
)

--
--
--
--
--
---
--
--
--
--
--
--
--
--
---
--
---
--
--
--
---
--
---
--
--
---
---
----
--
--
--
---
--
=>Syntax3:(whil
el oopinf orloop)
--
--
--
--
--
---
--
--
--
--
--
--
--
--
---
--
---
--
--
--
---
--
---
--
--
---
---
----
--
--
--
---
--
forv arnam1i nIterable_object: #outerf
orLoop
---
--
--
--
---
--
---
--
--
---
---
--
---
---
--
--
whi l
e(Testcond2) :#i nnerwhi
lel
oop
-
---
--
---
--
---
--
---
--
-
-
---
--
---
--
---
--
---
--
-
el
se:
--
---
--
---
--
---
---
--
-
else:
-
---
--
--
--
---
--
---
--
--
---
---
--
---
---
--
---
--

Exampl e:
--
--
---
--
--
---
--
#innerl
oopsex3.py
print
("-
"*40)
foriinrange(1,
6):#out erloop
pri
nt(
"Val ofi-
Out erforl
oop={}
".
for
mat (
i)
)
pri
nt(
"-
"*40)
j=3
whil
e(j
>0):#I nnerl oop
pr i
nt(
"\tValofj-
innerwhil
eloop=",
j
)
j=j-
1
el
se:
pr
int
("
-"
*40)
pr
int
("
\ti
am out
-ofi
nnerwhi
l
eloop"
)
pr
int
("
-"
*40)
el
se:
pri
nt(
"Iam outofout erforloop")
pri
nt(
"-"
*40)
--
--
--
--
--
---
---
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
---
--
--
--
---
--
--
--
--
--
=>Syntax4:forloopinwhi leloop
--
--
--
--
--
---
---
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
---
--
--
--
---
--
--
--
--
--
--
--
--
---
---
--
--
---
--
--
---
while(testcond1):#Out erwhilel
oop
-
--
---
--
---
--
---
--
--
--
forv arnam2i nIterabl
e_object
: #Innerf
orLoop
--
--
---
--
--
--
--
---
--
--
--
--
--
--
--
---
--
--
else:
---
--
---
--
--
--
--
---
--
--
--
---
--
--
--
--
--

el
se:
--
--
--
--
--
--
--
--
--
--
--
--

Exampl es:
--
--
---
--
--
---
---
#innerl
oopsex4. py
print
("-
"*40)
i
=1
whi l
e(i
<6):
print
("Val ofi-
-outerwhileloop=",i
)
print
("-
"*40)
forjinrange( 1,4):
pr i
nt(
"\tValofj-
Innerforloop={}
".
for
mat
(j
))
else:
i=i+1
pr i
nt(
"-"*40)
pr i
nt(
"i am outofinnerforloop"
)
pr i
nt(
"-"*40)
el
se:
print
("iam out -
ofout erwhilel
oop" )

=============================X==================================
#innerl
oopsex1. py
print
("-
"*40)
foriinrange(1,6):
print
("Valofi-
Outerloop={
}".
format(i
))
print
("-
"*40)
forjinrange(1,
4):
pri
nt(
"\t
Valofj-I
nnerloop={}
".f
ormat
(j
))
else:
pri
nt(
"-"
*40)
pri
nt(
"iam outofinnerloop"
)
pri
nt(
"-"
*40)

el
se:
pr
int
("
Iam outofout
erf
orl
oop"
)
pr
int
("
-"
*40)

""
"
E:\
KVR-PYTHON- 9AM\ I
NNERLOOPS>pyi
nner
loopsex1.
py
-
---
--
--
--
--
--
--
--
---
--
---
--
---
--
--
--
--
-
Valofi-
Outerloop=1
-
---
--
--
--
--
--
--
--
---
--
---
--
---
--
--
--
--
-
Valofj
-Innerloop=1
Valofj
-Innerloop=2
Valofj
-Innerloop=3
-
---
--
--
--
--
--
--
--
---
--
---
--
---
--
--
--
--
-
iam outofinnerloop
-
---
--
--
--
--
--
--
--
---
--
---
--
---
--
--
--
--
-
Valofi-
Outerloop=2
-
---
--
--
--
--
--
--
--
---
--
---
--
---
--
--
--
--
-
Valofj
-Innerloop=1
Valofj
-Innerloop=2
Valofj
-Innerloop=3
-
---
--
--
--
--
--
--
--
---
--
---
--
---
--
--
--
--
-
iam outofinnerloop
-
---
--
--
--
--
--
--
--
---
--
---
--
---
--
--
--
--
-
Valofi-
Outerloop=3
-
---
--
--
--
--
--
--
--
---
--
---
--
---
--
--
--
--
-
Valofj
-Innerloop=1
Valofj
-Innerloop=2
Valofj
-Innerloop=3
-
---
--
--
--
--
--
--
--
---
--
---
--
---
--
--
--
--
-
iam outofinnerloop
-
---
--
--
--
--
--
--
--
---
--
---
--
---
--
--
--
--
-
Valofi-
Outerloop=4
-
---
--
--
--
--
--
--
--
---
--
---
--
---
--
--
--
--
-
Valofj -Innerloop=1
Valofj -Innerloop=2
Valofj -Innerloop=3
--
---
---
--
---
----
-----
--
---
--
----
--
--
--
-
iam outofi nnerloop
--
---
---
--
---
----
-----
--
---
--
----
--
--
--
-
Val ofi-Out erloop=5
--
---
---
--
---
----
-----
--
---
--
----
--
--
--
-
Valofj -Innerloop=1
Valofj -Innerloop=2
Valofj -Innerloop=3
--
---
---
--
---
----
-----
--
---
--
----
--
--
--
-
iam outofi nnerloop
--
---
---
--
---
----
-----
--
---
--
----
--
--
--
-
Iam outofout erforloop
--
---
---
--
---
----
-----
--
---
--
----
--
--
--
-
""
"
#innerloopsex2. py
print("
-"*40)
i
=1
whi l
e(i<6):
print("Val ofi-
-outerwhil
el oop=",i
)
print("-"
*40)
j=1
whi le(j
<4):
pr i
nt("
\tValofj-
innerwhi l
eloop=",
j
)
j=j+1
else:
pr i
nt("
-"
*40)
pr i
nt("
\tiam out-ofinnerwhil
eloop")
i=i+1
pr i
nt("
-"
*40)
else:
print("iam out -
ofouterwhi leloop"
)

""
"
E:
\KVR- PYTHON- 9AM\INNERLOOPS>pyi
nner
loopsex2.
py
-
---
--
--
---
--
--
--
--
---
--
--
--
--
--
--
--
---
-
Valofi--
outerwhileloop=1
-
---
--
--
---
--
--
--
--
---
--
--
--
--
--
--
--
---
-
Valofj-i
nnerwhi l
eloop=1
Valofj-i
nnerwhi l
eloop=2
Valofj-i
nnerwhi l
eloop=3
-
---
--
--
---
--
--
--
--
---
--
--
--
--
--
--
--
---
-
iam out-ofi
nnerwhi l
eloop
-
---
--
--
---
--
--
--
--
---
--
--
--
--
--
--
--
---
-
Valofi--
outerwhileloop=2
-
---
--
--
---
--
--
--
--
---
--
--
--
--
--
--
--
---
-
Valofj-i
nnerwhi l
eloop=1
Valofj-i
nnerwhi l
eloop=2
Valofj-i
nnerwhi l
eloop=3
-
---
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
---
-
iam out-ofi
nnerwhi l
eloop
-
---
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
---
-
Valofi--
outerwhil
el oop=3
-
---
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
---
-
Valofj-i
nnerwhi l
eloop=1
Valofj-i
nnerwhi l
eloop=2
Valofj-i
nnerwhi l
eloop=3
-
---
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
---
-
iam out-ofi
nnerwhi l
eloop
-
---
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
---
-
Valofi--
outerwhil
el oop=4
-
---
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
---
-
Valofj-i
nnerwhi l
eloop=1
Valofj-i
nnerwhi l
eloop=2
Valofj-i
nnerwhi l
eloop=3
-
---
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
---
-
iam out-ofi
nnerwhi l
eloop
-
---
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
---
-
Valofi--
outerwhil
el oop=5
-
---
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
---
-
Valofj-i
nnerwhi l
eloop=1
Valofj-i
nnerwhi l
eloop=2
Valofj-i
nnerwhi l
eloop=3
-
---
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
---
-
iam out-ofi
nnerwhi l
eloop
-
---
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
---
-
iam out-ofouterwhil
eloop""
"

#innerl
oopsex3. py
print
("-
"*40)
foriinrange( 1,
6):#out erloop
print
("Val ofi-
Out erforl
oop={ }"
.f
ormat(
i)
)
print
("-"
*40)
j=3
whi l
e(j
>0):#I nnerl oop
pr i
nt(
"\tValofj-
innerwhi lel
oop=",
j
)
j=j-
1
else:
pr i
nt(
"-"*
40)
pr i
nt(
"\tiam out-ofinnerwhil
eloop")
pr i
nt(
"-"*
40)
else:
print
("Iam outofout erf
orl oop")
print
("-"
*40)

""
"
E:
\KVR-
PYTHON-
9AM\
INNERLOOPS>pyi
nner
loopsex3.
py
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--
Valofi-Outerforloop=1
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--
Valofj-i
nnerwhi leloop=3
Valofj-i
nnerwhi leloop=2
Valofj-i
nnerwhi leloop=1
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--
iam out-ofinnerwhi l
eloop
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--
Valofi-Outerforloop=2
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--
Valofj-i
nnerwhi leloop=3
Valofj-i
nnerwhi leloop=2
Valofj-i
nnerwhi leloop=1
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--
iam out-ofinnerwhi l
eloop
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--
Valofi-Outerforloop=3
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--
Valofj-i
nnerwhi leloop=3
Valofj-i
nnerwhi leloop=2
Valofj-i
nnerwhi leloop=1
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--
iam out-ofinnerwhi l
eloop
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--
Valofi-Outerforloop=4
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--
Valofj-i
nnerwhi leloop=3
Valofj-i
nnerwhi leloop=2
Valofj-i
nnerwhi leloop=1
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--
iam out-ofinnerwhi l
eloop
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--
Valofi-Outerforloop=5
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--
Valofj-i
nnerwhi leloop=3
Valofj-i
nnerwhi leloop=2
Valofj-i
nnerwhi leloop=1
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--
iam out-ofinnerwhi l
eloop
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--
Iam outofout erforloop
--
--
--
--
---
--
--
--
---
--
---
--
---
--
--
--
--
--"
""
#i
nnerl
oopsex4. py
pr
int
("-
"*40)
i
=1
whil
e(i
<6):
print
("Val ofi-
-outerwhileloop=",i
)
print
("-
"*40)
forjinrange( 1,4):
pr i
nt(
"\tValofj-
Innerforloop={}
".
for
mat
(j
))
else:
i=i+1
pr i
nt(
"-"*40)
pr i
nt(
"i am outofinnerforloop"
)
pr i
nt(
"-"*40)
el
se:
print
("iam out -
ofout erwhilel
oop" )

""
"
E:\
KVR-PYTHON- 9AM\ I
NNERLOOPS>pyi
nner
loopsex4.
py
-
---
--
--
--
--
--
--
--
---
--
---
--
--
--
--
---
--
-
Valofi-
-out
erwhi leloop=1
-
---
--
--
--
--
--
--
--
---
--
---
--
--
--
--
---
--
-
Valofj
-Innerforloop=1
Valofj
-Innerforloop=2
Valofj
-Innerforloop=3
-
---
--
--
--
--
--
--
--
---
--
---
--
--
--
--
---
--
-
iam outofinnerforloop
-
---
--
--
--
--
--
--
--
---
--
---
--
--
--
--
---
--
-
Valofi-
-out
erwhi leloop=2
-
---
--
--
--
--
--
--
--
---
--
---
--
--
--
--
---
--
-
Valofj
-Innerforloop=1
Valofj
-Innerforloop=2
Valofj
-Innerforloop=3
-
---
--
--
--
--
--
--
--
---
--
---
--
--
--
--
---
--
-
iam outofinnerforloop
-
---
--
--
--
--
--
--
--
---
--
---
--
--
--
--
---
--
-
Valofi-
-out
erwhi leloop=3
-
---
--
--
--
--
--
--
--
---
--
---
--
--
--
--
---
--
-
Valofj
-Innerforloop=1
Valofj
-Innerforloop=2
Valofj
-Innerforloop=3
-
---
--
--
--
--
--
--
--
---
--
---
--
--
--
--
---
--
-
iam outofinnerforloop
-
---
--
--
--
--
--
--
--
---
--
---
--
--
--
--
---
--
-
Valofi-
-out
erwhi leloop=4
-
---
--
--
--
--
--
--
--
---
--
---
--
--
--
--
---
--
-
Valofj
-Innerforloop=1
Valofj
-Innerforloop=2
Valofj
-Innerforloop=3
-
---
--
--
--
--
--
--
--
---
--
---
--
--
--
--
---
--
-
iam outofinnerforloop
-
---
--
--
--
--
--
--
--
---
--
---
--
--
--
--
---
--
-
Valofi-
-out
erwhi l
el oop=5
-
---
--
--
--
--
--
--
--
---
--
---
--
--
--
--
---
--
-
Valofj
-Innerforloop=1
Valofj
-Innerforloop=2
Valofj
-Innerforloop=3
-
---
--
--
--
--
--
--
--
---
--
---
--
--
--
--
---
--
-
iam outofinnerforloop
-
---
--
--
--
--
--
--
--
---
--
---
--
--
--
--
---
--
-
iam out-
ofout erwhil
eloop""
"

#i
nnerloopsex5.py
#writeapy t
honpr ogr
am whi
chwil
lacceptl
i
stofnumer
ical
val
uesanddi
spl
ayt
he
mult
ipli
cati
ont abl
eforev
eryval
ueofli
st.

l
st=[
-3,6,
-12,
-19,
-
4,0]
f
orni nlst:
if(
n<=0):
print
("{
}isinvali
di nputandNoMul Tabl
e:".
for
mat
(n)
)
else:
print
("-
"*40)
print
("Mul Tablefor{}"
.f
ormat(n)
)
print
("-
"*40)
foriinrange(1,11):
print
("
\t{}x{}={}
".
for
mat(n,
i
,n*
i))
else:
print
("
-"*40)

#i
nnerloopsex6. py
#wr i
teapy thonpr ogram whi chwi ll
acceptl i
stofnumericalval
uesanddi
spl
ayt
he
multi
pli
cationtabl ef orev eryvalueoflist.
l
st=l
ist(
)
nt
=int(
input("HowManymul t
ablesuwant :
"))
i
f(
nt<=0):
print("
{}isI nvalidInput".f
ormat (
nt))
el
se:
fori i
nr ange( 1,nt+1):
val=int(i
nput ("
Enter{}number :
".
format(
i))
)
l
st .append( val
)
else:
print("
-"*40)
print("
Gi venListofelement s={
}".
format
( l
st)
)
print("
-"*40)
forni nl st:#Out erforloop
if(
n<=0):
pr
int
("
{}i
sinv
ali
dinputandNoMul
Tabl
e:"
.f
ormat
(n)
)
el
se:
print
("-
"*40)
print
("Mul Tablefor{}
".
format(n))
print
("-
"*40)
foriinrange(1,11):#innerforloop
print
("
\t{}x{}
={}"
.f
ormat (
n,i
,
n*i
))
else:
print
("
-"*40)

#i
nnerloopsex7. py
#wr i
teapy thonpr ogram whi chwillacceptl i
stofnumer icalv al
uesanddi spl
aythe
pr
imenumber s
l
st=l
ist(
)
nt
=int(
input("HowManyNumber suHav e:")
)
i
f(nt
<=0):
print("
{}isI nvalidI nput".f
ormat (nt))
el
se:
fori i
nr ange( 1,nt+1) :
val=int(i
nput ("
Enter{}number :"
.format (
i)))
l
st .append( val)
else:
print("
-"*40)
print("
Gi venLi stofel ement s={}"
.format (l
st))#[12,21,3,7,14,46]
print("
-"*40)
primel i
st =list(
)
nonpr imel ist=[]
forni nl st:#out erforloop- -
whichwi l
lsuppl ythevaluesofli
stone
byone
if(n<=0) :
pass
el se:
result=True
fori i
nr ange(2,n):
i
f(n%i==0) :
result=False
break
if(
result):
pri
mel i
st.append( n)
else:
nonprimel i
st(
n)
else:
pr int(
"GivenList={ }
".f
ormat (l
st))
pr int(
"Pri
meNumber sList={}".
format (
primeli
st)
)
pr int(
"Non-Pr i
meNumber sList={}"
.for
mat (
nonpr i
meli
st))
#i
nnerloopsex8. py
#wr i
teapy thonpr ogram whi chwillacceptl i
stofnumer icalv al
uesanddi spl
aythe
pr
imenumber s
l
st=l
ist(
)
nt
=int(
input("HowManyNumber suHav e:")
)
i
f(nt
<=0):
print("
{}isI nvalidI nput".f
ormat (nt))
el
se:
fori i
nr ange( 1,nt+1) :
val=int(i
nput ("
Enter{}number :"
.format (
i)))
l
st .append( val)
else:
print("
-"*40)
print("
Gi venLi stofel ement s={}"
.format (l
st))#[12,21,3,7,14,46]
print("
-"*40)
primel i
st =list(
)
nonpr imel ist=[]
forni nl st:#out erforloop- -
whichwi l
lsuppl ythevaluesofli
stone
byone
if(n<=0) :
pass
el se:
result=True
fori i
nr ange(2,n):
i
f(n%i==0) :
result=False
break
if(
result):
pri
mel i
st.append( n)
else:
nonprimel i
st.
append( n)
else:
pr int(
"GivenList={ }
".f
ormat (l
st))
pr int(
"Pri
meNumber sList={}".
format (
primeli
st)
)
pr int(
"Non-Pr i
meNumber sList={}"
.for
mat (
nonpr i
meli
st))
#i
nnerloopsex7. py
#wr i
teapy thonpr ogram whi chwillacceptl i
stofnumer icalv al
uesanddi spl
aythe
pr
imenumber s
l
st=l
ist(
)
nt
=int(
input("HowManyNumber suHav e:")
)
i
f(nt
<=0):
print("
{}isI nvalidI nput".f
ormat (nt))
el
se:
fori i
nr ange( 1,nt+1) :
val=int(i
nput ("
Enter{}number :"
.format (
i)))
l
st .append( val)
else:
print("
-"*40)
print("
Gi venLi stofel ement s={}"
.format (l
st))#[12,21,3,7,14,46]
print("
-"*40)
primel i
st =list(
)
nonpr imel ist=[]
forni nl st:#out erforloop- -
whichwi l
lsuppl ythevaluesofli
stone
byone
if(n<=0) :
pass
el se:
result=True
fori i
nr ange(2,n):
i
f(n%i==0) :
result=False
break
if(
result):
pri
mel i
st.append( n)
else:
nonprimel i
st(
n)
else:
pr int(
"GivenList={ }
".f
ormat (l
st))
pr int(
"Pri
meNumber sList={}".
format (
primeli
st)
)
pr int(
"Non-Pr i
meNumber sList={}"
.for
mat (
nonpr i
meli
st))
Funct
ionsi
nPy
thon
=>Thepur poseofFuncti
onsisthat"Toperfor
m cer
tai
nOper
ati
onandpr
ovi
desRe-
usabi
lit
y".
=>Def.ofFuncti
on:
=>APar tofmainprogram iscal
ledFuncti
on
(
or)
=>SubPr ogram ofmainprogram i
scall
edFuncti
on.

=>Adv antagesofFunct i
ons:
--
--
---
--
---
--
---
---
---
--
--
---
--
--
--
--
---
--
--
=>Ifwedev el
opanypr oblem orpr
ogram byusingFuncti
onconcept,weget
fol
lowingadv antages.
=>Appli
cati
onDevelopmenttimeisLess
=>Appli
cati
onMemor ySpacei sLess
=>Appli
cati
onExecutionti
mei sLess
=>Appli
cati
onPerformanceisEnhanced(Improved)
=>Redundency(Dupli
cati
on)ofCodeisMinimized

=>PartsofFuncti
ons:
=>Whenwedeal wit
hFunct
ionalPr
ogrammi ng,wemustensur
ethattheremustexi
st
2parts.Theyare
1)Functi
onDef i
nit
ion
2)Functi
onCalls
=>Apar t
icul
arFunct
ionDef
ini
ti
onexistonlyonceandwecanhav eoneormore
Functi
onCal l
s.
=>ForEveryFuncti
oncal
l,t
heremustexistsaFuncti
onDefi
nit
ionother
wiseweget
NameEr ror.

Phasesi
nFuncti
ons:
=>I
nFuncti
ons,
theremustexi
sts3phases.
a)Ever
yFunct
ionMustTake I
NPUT
b)Ever
yFunct
ionMustPROCESSthei
nput
c)Ev
eryFunct
ionmustgiv
eOUTPUT/RESULT
================================================================

================================================================
Ty
pesofPr
ogr
ammi
ngLanguages

=>Inindustrywehav etwot y pesofpr ogramminglanguages.Theyare


1.Un-Struct uredProgrammingLanguages.
2.Str
uct uredPr ogr
ammi ngLanguages.
--
--
--
----
--
--
--
--
---
---
--
--
--
--
---
---
--
---
-----
---
--
--
--
--
--
--
---
1.Un- St
ructuredProgrammi ngLanguages.
--
--
--
----
--
--
--
--
---
---
--
--
--
--
---
---
--
---
-----
---
--
--
--
--
--
--
---
=>Un- St
ructuredProgrammi ngLanguagesdoesnotcont aintheconceptof
Funct i
ons.
=>SinceFunct ionsconceptnotpr esenti
nUn-Struct
uredProgrammingLanguages,
it
hast hefoll
owi ngLimitati
ons.

=>Applicati
onDev el
opmentt imei sMore
=>Applicati
onMemor ySpacei sMor e
=>Applicati
onExecut iont i
mei sMor e
=>Applicati
onPer formancei sDegr aded
=>Redundency( Duplicati
on)ofCodei sMore
=>Exampl e:GW- BASIC
2.Str
ucturedProgrammi ngLanguages.
--
---
--
--
--
--
--
---
--
--
--
---
--
---
--
--
--
--
---
--
--
---
--
---
---
--
---
--
-
=>Struct
uredPr ogrammi ngLanguagescont aintheconceptofFunct
ions.
=>SinceFunctionsconceptpr esentinSt ruct
uredPr ogr
ammingLanguages,i
thas
thefoll
owingAdv antages.

=>Appli
cati
onDevelopmenttimeisless.
=>Appli
cati
onMemor ySpacei sl
ess.
=>Appli
cati
onExecutionti
meisless.
=>Appli
cati
onPerf
or manceisEnhancedorImproved.
=>Redundency(
Dupl i
cati
on)ofCodeismi ni
mized
=>Exampl
e:C,
CPP,JAVA,PYTHON
================================================================
Numbersofappr oachesi
nfuncti
ons-MOSTI MP
=======================================================
Progr am- 1
#Thi spr ogr am di splaythev aluesofl ist,
tuple,
set,
dict
#iterabl edisp. py
defdi sp(k):
print ("t
ypeofk=" ,type(k))
print ("-
"*40)
forv alink:
print
("
\t{}".
format (val)
)
else:
print
("
-"*40)
defdi spdi ct (
k):
print ("t
ypeofk=" ,type(k))
print ("-
"*40)
forcno, cnamei nk. it
ems( )
:
print
("
\t{}--
>{}"
.format (cno,
cname) )
else:
print
("
-"*40)
#mai npr ogr am
l
st =[10,20, 30, 40,50]
disp( l
st )#f unct ioncall
tpl=("Py thon" ,
"Django","
Dat aSci ence","
ML" ,"
DL")
disp( tpl)#f unct ioncall
s={ 10,"Rossum" ,
34.56,"
Py thon",
Tr ue}
disp( s)#f unct i
oncal l
d={ 1:"Py thon" ,2:
"Dat aScience" ,
3:"Django",4:
"Java"
,5:
".
Net
"}
dispdi ct(d)#f unctioncall
Progr am- 2

#Thi
spr
ogr
am acceptl
i
stofv
aluesandsor
tthem
#li
stsort
.py
defdisp(k) :
pr int("
-"*
40)
f orv ali
nk:
pri
nt(
"\t{}".
for
mat (
val
))
el se:
pri
nt(
"-"*40)
defsor t
el ement s(l
st):
pr int("
OriginalElement s"
)
di sp(lst)
lst .
sor t
()
pr int("
Sor t
edEl ement sinAscendi
ngOrder")
di sp(lst)
lst [
::
-1]# orl st.rever
se() orl st
.sor
t(r
everse=Tr
ue)
pr int("
Sor t
edEl ement sinDecendi
ngOrder")
di sp(lst)

#mainprogram
l
st=[
10,2,
222,50,
10,4,
55,
-
3,0,
22]
sort
element
s( l
st)

#Thi spr ogr am di splaythev aluesofl ist,


tuple,
set,
dict
#iterabl edisp. py
defdi sp(k):
print ("t
ypeofk=" ,type(k))
print ("-
"*40)
forv alink:
print
("
\t{}".
format (val)
)
else:
print
("
-"*40)
defdi spdi ct (
k):
print ("t
ypeofk=" ,type(k))
print ("-
"*40)
forcno, cnamei nk. it
ems( )
:
print
("
\t{}--
>{}"
.format (cno,
cname) )
else:
print
("
-"*40)
#mai npr ogr am
l
st =[10,20, 30, 40,50]
disp( l
st )#f unct ioncall
tpl=("Py thon" ,
"Django","
Dat aSci ence","
ML" ,"
DL")
disp( tpl)#f unct ioncall
s={ 10,"Rossum" ,
34.56,"
Py thon",
Tr ue}
disp( s)#f unct i
oncal l
d={ 1:"Py thon" ,2:
"Dat aScience" ,
3:"Django",4:
"Java"
,5:
".
Net
"}
dispdi ct(d)#f unctioncall
#Thi spr ogr am acceptl istofv aluesandsor tthem
#listsor t.py
defdi sp(k):
print("
-"*40)
forv ali
nk:
print(
"\t{}".
for
mat (
val
))
else:
print(
"-"*40)
defsortelement s(lst):
print("
Or i
ginal Element s"
)
disp(lst)
lst.
sor t
()
print("
Sor t
edEl ement sinAscendi
ngOrder")
disp(lst)
lst[
::-
1]# orl st.rever
se() orl st
.sor
t(r
everse=Tr
ue)
print("
Sor t
edEl ement sinDecendi
ngOrder")
disp(lst)
#mainpr ogram
l
st=[
10,2,222,50,10,4,55,-3,0,
22]
sort
element s(l
st)

Li
stcompr
ehensi
on
=>ThepurposeofLi stcompr ehensionisthattoreadthev al
uesdy namicall
yf r
om
keyboardseparatedbyadel i
met er(space,comma, colon..
etc)
=>Li
stcompr ehensi
oni sthemostef f
ecti
vewayf orreadingthedat af
orlistinstead
tr
adit
ionalreadi
ngthedat a.
=>Syntax:
- l i
stobj=[expressi
on f orv arnamei nIterabl
e_object]
=>hereexpressi
onrepr esentseit
hertypecast i
ngormat hemat i
calexpression

Exampl es:
--
--
--
--
--
----
---
--
--
-
pri
nt(
"Ent erListofval
uesseparatedbyspace:
")#[
10,
2,
222,
50,
10,
4,
55,
-
3,0,
22]
l
st=[ f
loat (
val)forvalininput
().
spl
it
()]
pri
nt(
"cont entoflst
",l
st)

Exampl es:
--
--
--
---
--
---
--
--
l
st=[4,
3,7,-
2,6,
3]
newlst=[val*2forvalinl
st]
pri
nt("
newl ist
=",
newlst
)#[8, 6,
14,
-
4,12,
6]

#li
stcompre.py
pri
nt("
EnterListofv al
uesseparatedbyspace:
")#[10,
2,222,
50,
10,
4,
55,
-
3,0,
22]
l
st=[ fl
oat(
val)f orvalininput
().
spl
it
()]
pri
nt("
contentofl st
",l
st)
pri
nt("
============OR================" )
l
s=[]
n=int(
input
("Enterhowmanyv al
uesuwantt obel
ist:
")
)
i
f(n<=0):
pr
int
("
{}i
sinv
ali
dinput
:"
.f
ormat
(n)
)
el
se:
print
("Enter{}values:"
.f
ormat
(n))
foriinrange( 1,
n+1):
val=i
nt(input(
))
l
s.append( val
)
else:
print
("contentofl
st"
,l
s)

#list
compr e1.py
print
("EnterListofv aluessepar atedbyspace:"
)#[ 10,
2,222,
50,
10,
4,
55,
-
3,0,
22]
l
st =[float(val
)f orvali ninput (
).
spli
t(
)]
print
("contentofl st"
,lst
)#[ 3.0,5.0,
2.0,7.
0,3.
0,9.0,6.
0]
print
("-"
*40)
newlst=[]
forval i
nlst :
newl st.append(val*2)
else:
print("newlist=",
newl st
)
print
("-"
*40)
print
("==============OR=================" )
newlst=[v al*2f orvali nlst
]
print
("newl ist
=" ,
newlst)

#Thisprogr am acceptli
stofvaluesdynami
cal
l
ybyusi
ngl
i
stcompr
ehensi
onand
sortthem
#li
stsort
compr e.
py
defdisp(k):
pr int
("
-"*40)
f orvalink:
pri
nt(
"\t
{}"
.f
ormat(v
al))
el se:
pri
nt(
"-
"*40)

defsor
telements(l
st)
:
print
("
Origi
nalEl
ement
s")
disp(l
st)
lst.
sort
()
pr
int(
"SortedEl
ementsinAscendingOrder
")
di
sp(l
st)
l
st.
reverse()# orlst.
sort
(rev
erse=Tr
ue)
pr
int(
"SortedEl
ementsinDecendingOrder
")
di
sp(l
st)

#mainpr ogr
am
pri
nt(
"EnterLi
stofval
uesseparat
edbyspace:
")#[
10,
2,
222,
50,
10,
4,
55,
-
3,0,
22]
l
st=[i nt
(val
)forvali
ninput(
).
spli
t(
)]
sort
elements(l
st)

#Thisprogr am acceptli
stofnamesdynami
cal
l
ybyusi
ngl
i
stcompr
ehensi
onand
sortthem
#li
stsort
compr e1.py
defdisp(k):
pr int
("
-"*40)
f orvalink:
pri
nt(
"\t
{}"
.f
ormat
(val
))
el se:
pri
nt(
"-
"*40)

defsor
telements( l
st)
:
print(
"Origi
nalElements"
)
disp(l
st)
lst.
sort(
)
print(
"SortedElementsinAscendingOrder
")
disp(l
st)
lst.
reverse()# orl st.
sort
(rev
erse=Tr
ue)
print(
"SortedElementsinDecendingOrder
")
disp(l
st)

#mainprogram
pri
nt(
"EnterLi
stofNamesseparat
edbycomma:
")
l
st=[st r
(val
)forvali
ninput
().
spl
it
("
,"
)]
sort
elements(l
st)
Par
amet
ersandAr
gument
s

=>Par
amet
ersar
ecl
assi
fi
edint
otwotypes.Theyare
a)FormalParameter
s
b)LocalPar
ameters(or
)Vari
abl
es

=>For
mal parameter
sarethose,whi
chareusedinFunct
ionHeadi
ngandt
heyar
e
usedforstor
ingthei
nputswhicharecomingfr
om Funct
ioncal
ls.

=>LocalParamet
ers(or)Var
iabl
esar
ethosewhi
char
eusedi
nFunct
ionBodyand
theyareusedforstor
ingTemporar
yresul
ts.

=>HencebothFormalPar
ametersandLocal
Par
amet
ers(
or)Var
iabl
esar
eav
ail
abl
e
i
nthecontextFunct
ionDef
ini
ti
on.

Examples:
def comput e(a,
b,
c):# her
e'a'
,'
b'
,'c'
arecall
edfor
malParameter
s
d=a+b*c #Her e'd'i
scall
edLocal Parmet
ers/Vari
abl
e
--
--
--
--
---
--
--
--
--
--
-
--
--
--
--
---
--
--
--
--
--

=>Argumentsarethosewhi
char
eusedi
nFunct
ionCal
landt
heymaybei
nthef
orm
var
iablesorval
ues.

Exampl
e:
#mainpr
ogr
am
x=10
y=20
z=30
comput
e(x,
y,
z)`#her
e'x'
,
'y'
,
'z'ar
ecall
edArgument
s
comput
e(100,
200,
300)#her e100,
200and300arecal
l
ed
Argumentval
ues.
=>Therel
ati
onbetweenargument
sandfor
mal par
amet
ersi
sthat"
all
val
uesof
Argumentsarepassi
ngtoFormalpar
amet
ers"
.

Ty
pesofPar
amet
ersandAr
gument
s

=>Basedonpassi
ngar
gument
sval
uest
oPar
amet
ers,
thear
gument
sar
ecl
assi
fi
ed
i
nto5t y
pes.

1)Posit
ionalArguments/Parameter
s
2)DefaultAr
guments/Paramet er
s
3)Keywor dArguments/Parameters
4)Vari
ableLengthArguments/Parameter
s
5)KeyWor dVar i
abl
eLengthArguments/Par
amet
ers

1)Posi
ti
onal
Argument
s(or
)Par
amet
ers

=>TheConceptofPosi t
ionalPar ameters(or)argumentssaysthat"
TheNumberof
Argument s(Actualargument s)mustbeequal tothenumberofformalparameter
s".
=>ThisPar amet ermechani sm alsorecommendsOr derofParameter
sf orHi
gher
accuracy.
=>PythonPr ogrammi ngEnv i
ronmentf oll
owsbydef aultPosi
ti
onalArguments(or
)
Parameter s.
--
--
--
---
--
--
---
---
--
--
---
---
--
--
--
--
---
--
---
--
SyntaxforFunct ionDefini
tion:
--
--
--
---
--
--
---
---
--
--
---
---
--
--
--
--
---
--
---
--
def f uncti
onname( parm1, param2..
..
.param-n):
--
--
--
--
--
---
--
---
---
--
---
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
---
--
---
---
--
---
--
--
--
--
---
--
--
--
--
--
--

--
--
---
--
--
--
--
--
--
---
--
--
---
--
--
--
--
--
--
---
--
-
SyntaxforFunctionCall:
--
--
---
--
--
--
--
--
--
---
--
--
---
--
--
--
--
--
--
---
--
-
funct
ionname(arg1,
arg2.
..
.ar
g-n)
=>Herethev al
uesofar g1,ar
g2..
.ar
g-narepassi
ngtopar
am-
1,par
am-
2..
par
am-
n
respecti
vel
y.

2)Def
aul
tPar
amet
ers(
or)ar
gument
s

=>Whenther
ei saCommonVal uef
orfamil
yofFuncti
onCall
sthenSucht
ypeof
CommonVal ue(s)mustbetakenasdefaultpar
ameterwi
thcommonv al
ue(Butnot
recommendedt opassbyusingPosi
ti
onalParamet
ers)
Syntax:forFunctionDef i
niti
onwi t
hDef aul
tParamet ers
--
--
--
---
--
--
---
---
--
--
--
--
---
--
---
--
--
---
--
--
--
---
--
--
--
--
--
---
--
--
--
--
--
---
--
--
---
--
--
deff unctionname( param1,param2,..
..
param-n-1=Val1,Par
am-
n=Val
2):
--
--
---
---
--
--
--
--
---
--
--
---
--
--
---
--
--
--
---
--
--
--
--
---
--
--
--
--
--
-
-
---
--
--
--
--
---
---
--
---
--
--
--
---
--
--
--
--
--
--
---
--
--
--
--
--
--
---
--
--

Herepar
am-n-
1andparam-nar
ecal
led"
defaul
tParamet
ers"
andparam1,
par
am-2.
..ar
ecal
led"
Posi
ti
onalpar
ameter
s"

Rule-
:Whenweusedefaultparamet
ersinthefuncti
ondefi
nit
ion,
Theymustbeused
aslastPar
ameter(
s)ot
herwisewegetError(Synt
axErr
or:
non-defaul
tar
gument
(Posi
ti
onal)f
oll
owsdefaul
targument)
.

#pospar
amex1.
py

def dispstudinfo(stno,
sname,marks)
:
pr i
nt("
\t{
}\t{
}\t{
}".
for
mat(
stno,
sname,
mar
ks)
)
#mainpr ogram
pri
nt(
"="*50)
pri
nt(
"\t
St no\tName\ tMarks"
)
pri
nt(
"="*50)
di
spstudinfo(10,"
RS",33.33)
di
spstudinfo(20,"
DR",33.33)
di
spstudinfo(30,"
RR",43.33)
di
spstudinfo(40,"
SR",23.33)
pri
nt(
"="*50)
#posparamex2. py

def di
spst
udinfo(
stno,
sname,marks,
crs)
:
pri
nt(
"\t
{}\
t{}
\t{
}\t
{}"
.f
ormat(
stno,
sname,
mar
ks,
crs)
)

#mainprogram
pr
int
("
="*50)
pr
int
("
\ t
Stno\tName\tMar ks\t
Course"
)
pr
int
("
="*50)
di
spstudi
nfo(10,"
RS"
,33.33,"PYTHON")
di
spstudi
nfo(20,"
DR"
,33.33,"PYTHON")
di
spstudi
nfo(30,"
RR"
,43.33,"PYTHON")
di
spstudi
nfo(40,"
KV"
,63.33,"PYTHON")
di
spstudi
nfo(50,"
WR",93.93,"
PYTHON" )
di
spstudi
nfo(60,"
PR"
,83.33,"PYTHON")
pr
int
("
="*50)

#def
aul
tpar
amex1.
py

def di
spst
udinfo(
stno,
sname,marks,
crs="
PYTHON"
):
pri
nt(
"\t
{}\
t{}
\t{
}\t
{}"
.f
ormat(
stno,
sname,
mar
ks,
crs)
)
#mainprogram
pr
int
("
="*50)
pr
int
("
\ t
Stno\tName\tMar ks\t
Cour
se"
)
pr
int
("
="*50)
di
spstudi
nfo(10,"
RS"
,33.33)
di
spstudi
nfo(20,"
DR"
,33.33)
di
spstudi
nfo(30,"
RR"
,43.33)
di
spstudi
nfo(40,"
KV"
,63.33)
di
spstudi
nfo(50,"
WR",93.93)
di
spstudi
nfo(60,"
PR"
,83.33)
di
spstudi
nfo(70,"
SN"
,93.33,"JAVA"
)
di
spstudi
nfo(60,"
AJ"
,73.33)
pr
int
("
="*50)

#def
aul
tpar
amex2.
py

def di
spst
udinfo(
stno,
sname,marks,
crs="PYTHON",
ci
ty="
HYD"):
pri
nt(
"\t
{}\
t{}
\t{
}\t
{}\
t{}
".
for
mat(stno,
sname,
marks,
crs,
ci
ty)
)

#mainpr ogr am
pri
nt("
="*50)
pri
nt("
\tStno\ tName\ tMar ks\t
Cour se\City
")
pri
nt("
="*50)
di
spstudi nfo(10,"RS"
,33.33)
di
spstudi nfo(20,"DR",
33.33)
di
spstudi nfo(30,"RR",
43.33)
di
spstudi nfo(40,"KV",
63.33)
di
spstudi nfo(50,"WR",93.93)
di
spstudi nfo(60,"PR",
83.33)
di
spstudi nfo(70,"SN",
93.33,"JAVA" )
di
spstudi nfo(80,"AJ"
,73.33)
di
spstudi nfo(90,"RR",
33.33,"JAVA" )
di
spstudi nfo(35,"KB",
33.33,"DJ",
"Bang")
pri
nt("
="*50)
#defaultparamex3. py
defdi sp( a=10,b=20,c=30) :
pr i
nt("
{}+{}
+{}={}
" .
format(a,b,
c,a+b+c)
)

#mai
nprogram
di
sp(
)
di
sp(
100)
di
sp(
1,2)
di
sp(
1,2,
3)
3)Key
wor
dPar
amet
ers(
or)ar
gument
s

=>I
nsomeoft hecircumst
ances,weknowt hefunctionnameandf ormal parameter
namesandwedon' tknowtheorderoffor
mal Paramet ernamesandt opasst hedata
/valuesaccurat
elywemustuset heconceptofKey wor dPar
ameters(or)arguments.
=>Theimpl ementat
ionofKeywordParameter
s( or)argumentssaysthatallthe
for
mal parameternamesusedasar gumentsinFunct i
oncall
(s)askeys.

Synt
axforfuncti
ondefini
tion:-
def functi
onname(param1, param2.
..
par
am-
n):
-
---
--
--
--
--
--
--
--
--
--
--
--
--
---
--
---
---
--
---
-
-
---
--
--
--
--
--
--
--
--
--
--
--
--
---
--
---
---
--
---
-

Sy
ntaxf
orfunct
ioncal
l
:-
f
uncti
onname(par
am-
n=v
al-
n,par
am1=v
al1,
par
am-
n-1=v
al-
n-1,
.
..
..
.)

Herepar
am-n=v
al-
n,par
am1=v
al1,
par
am-
n-1=v
al-
n-1,
.
..
..
.ar
ecal
l
edKey
wor
ds
ar
guments

#kwdpar
amex1. py
defdi
sp(
a,b,c)
:
print(
"\t
{}\
t{}
\t{
}"
.f
ormat
(a,
b,
c))

#mai nprogram
pr
int("="
*50)
pr
int("\t
a\t
b\ t
c")
pr
int("="
*50)
di
sp( 10,
20,30)
di
sp( c=30,
b=20,a=10)
di
sp( b=20,
a=10,c=30)
di
sp( 10,
c=30,b=20)
di
sp( 10,
20,c=30)
#disp(c=30,10,
20)-
--
--
err
or-
--
Synt
axEr
ror
:posi
ti
onal
argumentf
oll
owskey
wor
d
ar
gument
pr
int("="
*50)

#kwdpar
amex2. py
defdi
sp(
a,b,c,
crs="
PYTHON" ):
print(
"\t
{}\
t{}
\t{
}\t
{}"
.f
ormat
(a,
b,
c,
crs)
)

#mainprogram
pr
int
("="
*50)
pr
int
("\t
a\t
b\tc\
tcrs"
)
pr
int
("="
*50)
di
sp(10,
20,30)
di
sp(c=30,
b=20,a=10)
disp( b=20, a=10, c=30)
disp( 10,c=30, b=20)
disp( 10,20, c=30)
#di sp(c=30, 10,20)--
---
error-
--
Sy ntaxError
: posi
ti
onalargumentfoll
owskeywor
d
argument
disp( c=30, a=10, b=20)
disp( crs=" Java" ,
c=30,a=10,b=20)
#di sp(10, 20,crs=" DSC",30)--
--
-error--
-SyntaxEr
ror:
posi t
ionalar
gumentf
oll
ows
key wor dar gument
disp( 10,20, 30,crs="JAVA" )
disp( 10,20, 30,"Django")
print("="*50)
#kwdpar amex3. py
defst udi nfo(sno, sname, marks,crs="Python")
:
print("\t
{}\t{
}\t
{}\t{
}".
format (
sno,sname,mar ks,
crs))

#mai npr ogr am


print("
="*50)
print("
\tst no\tName\ t
Marks\ tCrs"
)
print("
="*50)
studinfo( 10,"RS",77.77)
studinfo( 20,mar ks=22.22,sname=" DR" )
studinfo( mar ks=42. 22,
sno=30, sname=" DR"
)
studinfo( crs="Django" ,
mar ks=11.11,sname="TR",
sno=40)
#st udi
nf o( cr
s="Dj ango",
50,"MC" ,
44.44)SyntaxEr
ror:posi
ti
onal
argumentf
oll
ows
key wordar gument
print("
="*50)

4)Var
iabl
esLengt
hPar
amet
ers(
or)ar
gument
s

=>Whenwehav ef amilyofmul ti
plefunctioncallswi thVariablenumberofv alues/
argument st henwi thnormal pythonpr ogrammi ng, wemustdef inemul t
iplefunction
defi
nat i
ons.Thi spr ocessleadst omor edev elopmentt i
me.Toov er
comet his
process, wemustuset heconceptofVar iablelengthPar amet ers.
=>ToI mpl ement ,Var i
ablelengthPar amet ersconcept ,wemustdef i
nesi ngle
Funct i
onDef init
ionandt akesaf ormal Par amet erprecededwi t hasy mbol called
astri
sk(*par am)andt heformal paramet erwi t
hast risksymbol iscal
ledVar iabl
e
l
engt hPar amet ersandwhosepur posei st ohold/st oreanynumberofv alues
comi ngf r
om si milarfuncti
oncal l
sandwhoset y peis<class, '
tuple'
>.
--
--
--
----
--
---
---
--
--
---
---
---
--
--
---
--
--
--
--
---
--
---
--
--
---
--
--
----
--
---
---
--
--
---
---
--
--
--
--
---
----
Syntaxf orfunctiondef i
niti
onwi thVar i
ablesLengt hPar amet ers:
--
--
--
----
--
---
---
--
--
---
---
---
--
--
---
--
--
--
--
---
--
---
--
--
---
--
--
----
--
---
---
--
--
---
---
--
--
--
--
---
----
def f unctionname( l
istofformal params,* param):
-
---
--
--
----
--
--
--
---
--
--
---
--
--
---
--
---
--
--
----
--
-
---
--
---
--
--
--
---
--
--
--
---
--
---
--
---
---
---
--
--
---

=>Here*param i
scall
edVari
abl
eLengthparameteranditcanhol
danynumberof
argumentvalues(or
)var
iabl
enumberofargumentvaluesand*par
am t
ypei
s
<cl
ass,
'
tupl
e'
>

=>Rule:-The* param mustal way swrit


tenatlastpar tofFunctionHeadingandit
mustbeonl yone( butnotmul ti
ple)
=>Rule:-WhenweuseVar i
ablelengthanddef aultparamet ersinfuncti
onHeading,
weusedef aul tparamet eraslastandbef oreweusev ariablel
engthparameterandin
functi
oncal ls,weshoul dnotusedef aultparamet erasKeywor dargumentbcoz
Variablenumberofv aluesaretreatedasPosi ti
onal ArgumentVal ue(s)
#nonv arl
enar gex1.py--
--
#Thispr ogr am wi llnotexecuteasi ti
sshownbel ow, becausePVM r emembers
l
atestf unctiondef i
niti
ononly.
defdi spv alues( a):
print ("{
}".
format (
a))

defdi
spval
ues(a,
b):
pri
nt(
"{}
\t{
}".
for
mat
(a,
b))

defdi
spval
ues(a,
b,c)
:
pri
nt(
"{}
\t{
}\t
{}"
.f
ormat
(a,
b,
c))

defdi
spval
ues(a,
b,c,
d):
pri
nt(
"{}
\t{
}\t
{}\
t{}
".
for
mat
(a,
b,
c,
d))

#mai
npr ogram
di
spv
alues(10)#Funct
ioncal
l-
1
di
spv
alues(10,
20)#Functi
oncall
-2
di
spv
alues(10,
20,
30)#Functi
oncall-
3
di
spv
alues(10,
20,
30,
40)#Functioncall
-4

#nonv
arlenargex2.py
defdispvalues(a)
: #Funct
ionDef
-1
pri
nt("
{}"
.f
ormat(a)
)

di
spv
alues(
10)#Funct
ioncal
l
-1

defdi
spval
ues(a,
b):#Funct
ionDef
-2
pri
nt(
"{}
\t{
}".
for
mat(
a,b)
)

di
spv
alues(
10,
20)#Funct
ioncal
l
-2

defdi
spval
ues(a,
b,c)
:#Functi
onDef-
3
pri
nt(
"{}
\t{
}\t
{}"
.f
ormat
(a,
b,
c))

di
spv
alues(
10,
20,
30)#Funct
ioncal
l
-3

defdi
spval
ues(a,
b,c,
d):#Functi
onDef -
4
pri
nt(
"{}
\t{
}\t
{}\
t{}
".
for
mat (
a,b,
c,
d))

di
spv
alues(
10,
20,
30,
40)#Funct
ioncal
l
-4
defdi
spval
ues(a,
b,c,
d,
e):#FunctionDef-
5
pri
nt(
"{}
\t{
}\t
{}\
t{}
\t{
}".
for
mat(a,
b,
c,d,
e))

di
spvalues("RS",
"DR" ,
"MC",
"TR",
"SS")#Funct i
oncal
l-
5
#var
lenargex1.py
defdispv alues(*
a) :#here* ai
scal l
edv ari
abl
eargumentandwhoset
ypei
stupl
e
print("
="*50)
print("
\ntypeofa:{}andlength={}"
.f
ormat(
type(
a),
len(
a))
)
forv ali
na:
print(
"\t
{}"
.f
ormat(val)
)
else:
print(
"="
*50)

#mai
npr ogram
di
spv
alues(10)#Functioncall
-1
di
spv
alues(10,20)#Functi
oncal l
-2
di
spv
alues(10,20,
30)#Functioncall-
3
di
spv
alues(10,20,
30,
40)#Funct ioncall
-4
di
spv
alues("RS",
"DR"
,"
MC" ,
"TR",
"SS")#Funct
ioncal
l
-5

#var
lenargex2.
py
defdispv al
ues(
*a)
:
forvali
na:
pr
int
("
{}"
.f
ormat
(val
),
end=""
)
else:
pr
int
()

#mai npr ogram


print
("="*50)
dispvalues(10)#Funct ioncal l
-1
dispvalues(10,20)#Funct ioncal l
-2
dispvalues(10,20,30)#Funct ioncall-3
dispvalues(10,20,30, 40)#Funct ioncall-
4
dispvalues("RS" ,
"DR" ,
"MC" ,
"TR" ,
"SS")#Functi
oncal
l-
5
print
("="*50)
#Wr it
eapy thonpr ogram whi chwi llcomput
esum ofvar
iabl
enumberofnumer
ical
values
#v ar
lenargex3. py
deff i
ndsum( sname, *nums) :
print("="*50)
print("MyNamei s{}".
format (
sname))
s=0
forv al i
nnums:
pr i
nt("
\ t
{}".
format(val))
s=s+v al
else:
pr
int
("
sum={
}".
for
mat
(s)
)
pr
int
("
="*
50)

#mainprogr am
fi
ndsum("Mahdev ",10, 20, 30,40,50,60)
fi
ndsum("pooj a",10,20)
fi
ndsum("supr iya",10, 20, 30)
fi
ndsum("priyanka" ,
12. 3,34. 5,
5.6,
-5.7)
fi
ndsum("venkat esh" ,1.2, 13)
fi
ndsum("pav an" ,
23, 45, 67, -56,78,
12, -
34,56)
fi
ndsum("nani ")
#Writ
eapy thonpr ogr am whi chwi llcomput esum ofvari
abl
enumberofnumer
ical
val
ues
#varl
enargex4. py
deff i
ndsum( sname,* nums, cr
s=" PYTHON" ,ci
ty="
hyd")
:
print("="*50)
print("MyNamei s'{}
'doing' {
}'cour
seANDLI VI
NG
I
N:{}
".
format (sname, crs, city))
s=0
forv al i
nnums:
print ("\t{}".
format (v
al))
s=s+v al
else:
print ("sum={ }"
.f
or mat(s))
print ("="*50)

#mainprogr am
fi
ndsum("Mahdev ",10, 20,30,40,50,
60)
fi
ndsum("pooj a",
10, 20)
fi
ndsum("supr iy
a",10, 20,30)
fi
ndsum("priyanka" ,
12. 3,
34. 5,
5.6,
-5.7)
fi
ndsum("venkat esh" ,1.2,13)
fi
ndsum("pav an",
23, 45, 67,-56,78,
12,-34,56)
fi
ndsum("nani "
)
#fi
ndsum( crs="Dajngo" ,
sname=" KVR" ,
5,6,7)-
--
SyntaxErr
or:posi
ti
onalargument
fol
lowskey wor dar gument
#fi
ndsum( "KVR" ,
5,6,7, ,
"Django" )TypeEr ror
:unsupportedoperandtype(
s)for+:
'i
nt'
and'st
r'
fi
ndsum("KVR" ,
5,
6,7, crs=" Django")
fi
ndsum("Pr anav",
15, 16, 17,crs="DataSci ence",
ci
ty="AP")
fi
ndsum("Ajay -
Anki t",15,16,city="
Delhi-BANG" )

5)KeyWor
dVar
iabl
esLengt
hPar
amet
ers(
or)ar
gument
s
=>Whenwehav ef ami li
yofmul ti
plef unct i
oncal lswi t
hKeyWor dVari
ablenumberof
values/ar gument st henwi thnor mal py thonpr ogrammi ng, wemustdef inemut i
ple
funct i
ondef intions.Thi spr ocessl eadst omor edev el
opmentt i
me.Toov ercomet hi
s
process, wemustuset heconceptofKey wordVar iablelengt hPar ameters.
=>ToI mplement ,Key wor dVar i
ablel engt hPar amet ersconcept ,wemustdef ine
singleFunct i
onDef init
ionandt akesaf ormal Par amet erpr ecededwi t
hasy mbol
calleddoubl east r
isk(* *par am)andt hef ormal par amet erwi thdoubl
east risk
symbol i
scal ledKey wor dVar i
abl elengt hPar amet er sandwhosepur posei st ohold
/st oreanynumberof( Key,Value)comi ngf r
om si mi l
arfunct ioncall
sandwhose
typei s<class, '
dict'>.
--
----
---
--
--
---
---
---
----
--
---
----
--
--
---
---
--
---
---
---
---
---
----
--
--
---
---
---
---
--
--
--
----
----
---
--
-
Sy ntaxforf unct i
ondef i
niti
onwi t
hKey wor dVar iablesLengt hPar ameters:
--
----
---
--
--
---
---
---
----
--
---
----
--
--
---
---
--
---
---
---
---
---
----
--
--
---
---
---
---
--
--
--
----
----
---
--
-
def f unctionname( l
istoff ormal params,* *param):
----
--
---
-----
--
--
---
---
--
--
---
----
--
---
----
---
--
-
-
----
---
---
--
--
---
--
----
--
---
----
--
----
--
--
----
---

=>Her
e**param i
scal
ledKeywordVar i
ableLengt
hparameterandi
tcanhol
dany
numberofKeywordargumentvalues(or)Keywordv
ariabl
enumberofar
gument
val
uesand**par
am ty
peis<class,
'di
ct'
>

=>Rul
e:-The*
*par
am mustalwayswri
tt
enatl
astpar
tofFunct
ionHeadi
ngandi
t
mustbeonlyone(butnotmul
ti
ple)

#kwdv arlenpar amex1. py


defdispinfo(* *a):#her e* *aiscal ledkey wor dvari
ablelengthargrument/
Paramet er--
-dict
print(
"-"*50)
print(
"typeofa=" ,
type(a) )
print(
"No.of( Key,Value)={ }".f
ormat (l
en(a)))
fork,vi na.items():
print(
"\t
{}--
->{}".
format (k,v)
)
else:
print(
"-"
*50)
#mainpr ogram
di
spinfo(sno=10, sname=" RS" ,
mar ks=33. 33,cname=" PSF")
di
spinfo(eno=111, ename=" DR" ,sal=4.5)
di
spinfo(crs1=" Py t
hon1" ,
crs2=" Django" )
di
spinfo(aut hor="Ritche")
di
spinfo()
#Thispr ogram comput estotal mar tksdi ff
erentstudentstudyi
ngi ndi
ffer
entcl
asses
whosecur edindi f
ferentsubj ects.
#kwdv arlenpar amex2. py
deff indtotalmar ks(sname, cls,**submar ks):
print(
"* "
*50)
print(
"\ t
StudentM arksReport :
")
print(
"* "
*50)
print(
"\ t
StudentName: {}\t
Cl assName: {}".
format(sname,cl
s))
print(
"-"*50)
tm=0
print(
"\t
SubjectName\ t
Mar ks")
print(
"-
"*50)
forsub,marksinsubmar ks.it
ems( ):
pri
nt("
\t{}
\t\t{
}".
format (sub,mar ks)
)
tm=tm+mar ks
else:
pri
nt("
-"
*50)
pri
nt("
\tTotalMar ks={}".f
or mat(tm))
pri
nt("
-"
*50)
print(
"*"
*50)
#mainprogram
fi
ndt
otal
mar ks("
Santosh",
"X",Sci
=70,Soc=77, Maths=88,Hindi=55)
fi
ndt
otal
mar ks("
Umesh" ,
"XII
",Maths=75, Phy =56,Che=55)
fi
ndt
otal
mar ks("
Venkatesh",
"B.Tech( Mech) ",sub1=50,sub2=88,sub3=77,
sub4=55)
fi
ndt
otal
mar ks("
Mahima" ,
"P.hD(DAA) ",Cor e=90,Rm=56)
fi
ndt
otal
mar ks("
Rossum" ,
"Resear ch")
Gl
obal
Var
iabl
esandLocal
Var
iabl
es

=>Thepur poseofGl obalvari


ablesisthat"Tost oreCommonVal uesf orDiff
erent
Functi
onCal ls"
=>GlobalVariablesarethose,whishar edefinedbef oreallthefunct i
oncal l
s.
=>LocalVariablesarethose,whichar eusedf orst oringTempor ar yr
esultsinthe
Functi
onBody .
=>LocalVariablesarethose,whishar edefinedwi thint heFunct i
onBody
=>Syntax:
-
--
--
--
--
--
---
--
---
Fil
eName. py
--
--
---
--
--
--
--
---
var1=val
1
var2=val
2 #her ev ar1,
v ar2...
arecalledglobal vari
ables
deff uncti
onname1( li
stoff ormalpar amsi fany )
:
-
--
--
--
--
---
---
--
--
---
--
---
---
var5=val#her ev ar5iscalledLocal Vari
able
--
--
---
--
--
--
----
---
--
---
----
-
deff uncti
onname2( li
stoff ormalpar amsi fany )
:
-
--
--
--
--
---
---
--
--
---
--
---
---
var6=val#her ev ar6iscalledLocal Vari
able
--
--
---
--
--
--
----
---
--
---
----
-
deff uncti
onname- n(li
stoff ormal par amsi fany):
-
--
--
--
--
---
---
--
--
---
--
---
---
var7=val#her ev ar7iscalledLocal Vari
able

#globalvar
ex1.py
l
ang=" PYTHON"#her e'l
ang'i
scalledGlobal
Var i
able
defl earnDataSci
():
cr
s1="DataScience"#crs1iscall
edlocalvari
abl
e
pri
nt(
"Todocodi ngin'
{}',
weneed' {
}'l
anguage:"
.for
mat(
crs1,
lang))
#pri
nt(cr
s2,
crs3)can'
taccesscrs2andcr s3bcoztheyar
elocalinother
functi
ons
deflearnAI (
):
crs2="AI"#crs2iscall
edlocal
variabl
e
print(
"Todocodi ngin'{
}',
weneed' {}
'language:
".
for
mat(
crs2,
lang))
#pr i
nt(
crs1,
crs3)can'
taccesscrs1andcr s3bcoztheyar
elocalinother
funct
ions

defl earnML():
crs3="ML"#cr s3iscal
ledlocalvar
iable
pr i
nt(
"Todocodi ngin'{
}',
weneed' {}'
language:
".
for
mat(
crs3,
lang))
#pr i
nt(cr
s1,
crs2)can'
taccesscrs1andcr s2bcoztheyar
elocalinother
functi
ons
#mai nprogram
l
earnDataSci()
l
earnAI()
l
earnML( )
#globalv
arex2.py
defl earnDataSci
():
crs1="DataScience"#crs1iscall
edlocalvari
abl
e
pr i
nt(
"Todocodi ngin'{
}',
weneed' {}'
language:
".
for
mat(
crs1,
lang))
#pr i
nt(cr
s2,
crs3)can'
taccesscrs2andcr s3bcoztheyar
elocalinother
functi
ons
defl earnAI(
):
crs2="AI"#crs2iscall
edlocalvari
able
pr i
nt(
"Todocodi ngin'{
}',
weneed' {}'
language:
".
for
mat(
crs2,
lang))
#pr i
nt(cr
s1,
crs3)can'
taccesscrs1andcr s3bcoztheyar
elocalinother
functi
ons

defl earnML( ):
crs3="ML"#cr s3iscal
ledlocalvar
iable
print(
"Todocodi ngin'{
}',
weneed' {}'
language:
".
for
mat(
crs3,
lang))
#pr i
nt(cr
s1,
crs2)can'
taccesscrs1andcr s2bcoztheyar
elocalinother
functi
ons
#mai nprogr am
l
ang=" PYTHON"#her e'l
ang'i
scalledGlobalVari
able
l
earnDat aSci()
l
earnAI (
)
#globalvarex3.py
defl earnDat aSci
():
crs1="DataScience"#crs1iscall
edlocalvari
abl
e
print(
"Todocodi ngin'{
}',
weneed' {}'
language:
".
for
mat(
crs1,
lang))
#pr i
nt(cr
s2,
crs3)can'
taccesscrs2andcr s3bcoztheyar
elocalinother
functi
ons
l
ang=" PYTHON"#her e'l
ang'i
scalledGlobalVari
able
defl earnAI (
):
crs2="AI"#crs2iscall
edlocalvari
able
print(
"Todocodi ngin'{
}',
weneed' {}'
language:
".
for
mat(
crs2,
lang))
#pr i
nt(cr
s1,
crs3)can'
taccesscrs1andcr s3bcoztheyar
elocalinother
functi
ons

defl
ear
nML(
):
crs3="ML"#cr s3iscal
ledlocal
v ar
iable
print(
"Todocodi ngin'
{}'
,weneed' {}'
language:
".
for
mat(
crs3,
lang))
#pr i
nt(
crs1,
crs2)can'
taccesscrs1andcr s2bcoztheyar
elocalinother
funct
ions
#mainpr ogram
l
earnDataSci()
l
earnAI()
l
earnML()

#globalv
arex4.py
defl earnDataSci
():
crs1="DataScience"#crs1iscall
edlocalvari
abl
e
pr i
nt(
"Todocodi ngin'{
}',
weneed' {}
'language:
".
for
mat(
crs1,
lang))
#pr i
nt(cr
s2,
crs3)can'
taccesscrs2andcr s3bcoztheyar
elocalinother
functi
ons
defl earnAI(
):
crs2="AI"#crs2iscall
edlocalvar
iabl
e
pr i
nt(
"Todocodi ngin'{
}',
weneed' {}
'language:
".
for
mat(
crs2,
lang))
#pr i
nt(cr
s1,
crs3)can'
taccesscrs1andcr s3bcoztheyar
elocalinother
functi
ons

deflearnML( ):
crs3="ML"#cr s3iscal
ledlocal
v ar
iable
print(
"Todocodi ngin'
{}'
,weneed' {}'
language:
".
for
mat(
crs3,
lang))
#pr i
nt(
crs1,
crs2)can'
taccesscrs1andcr s2bcoztheyar
elocalinother
funct
ions
#mainprogr am
#lear
nDataSci()
#lear
nAI()
l
earnML()
l
ang="PYTHON"#her e'l
ang'i
scall
edGlobal Vari
able

gl
obal
keywor
d
=>WhenwewantMODI FYt heGLOBALVARIABLEvaluesi
nsideoff uncti
on
defi
nati
onthengl
obal
v ar
iablenamesmustbeprecededwit
h'global'key
word
otherwi
seweget"
UnboundLocalErr
or:
local
var
iabl
enamesr ef
erencedbef or
e
assignment
"

Syntax:
-
--
---
---
--
var1=val
1
var2=val
2
var-
n=val-
n #v
ar1,
var
2..
.v
ar-
nar
ecal
l
edgl
obal
var
iabl
enames.
--
--
---
--
--
--
--
--
-
def fun1()
:
--
---
---
---
--
---
---
---
--
global var1,var2...
var-
n
#Modi fyv ar1,
v ar2.
..
.var
-n
-
--
---
--
--
--
---
---
--
---
---
def fun2()
:
---
--
--
--
--
--
----
---
---
-
gl
obal var1,var2..
.var-n
#Modi fyv ar1,var2..
..
v ar-
n
-
--
---
--
--
--
---
---
--
---
---

#globalkwdex1.py
a=10 #Gl obal Var
iabl
e
deff un1()
:
pr
int
("Valofainf
un1(
)="
,a)#Accessi
ngGl
obal
Vari
ableVal
ue
deff un2()
:
pr
int
("Valofainf
un2(
)="
,a)#Accessi
ngGl
obalVar
iabl
eVal
ue
deff un3()
:
pr
int
("Valofainf
un3(
)="
,a)#Accessi
ngGl
obalVar
iabl
eVal
ue

#mainpr
ogr
am
fun1(
)
fun2(
)
fun3(
)

#global
kwdex2.py
a=10
defincrement()
:
globala
a=a+1
print
("
valofai
nfun1(
)="
,a)#11

defmul t
iply
v al
():
global a
a=a* 2
pr i
nt("valofainmul t
ipl
yval()
=",a)#22
#mai nprogram
pri
nt("
Val ofai nmai nprogram beforeincrement()=" ,
a)#10
i
ncrement ()
pri
nt("
Val ofai nmai nprogram aft
erincr ement(
)=",a)#11
multi
plyval(
)
pri
nt("
Val ofai nmai nprogram aft
ermul ti
ply
val
()=",a)#22
#global
kwdex3. py
a=10
b=20 #her e'a'and'b'arecall
edGl obal Vari
abl
es
defoper ation():
global a,b
a=a+1
b=b+1
defupdat
ev al
ues():
globala,b
c=a* b
print(
"Valofci
nupdat
eval
ues(
)="
,c)
a=a+2
b=b+2

#mai nprogram
pri
nt("
Val ofabefor
eoperat ion()=",a)#10
pri
nt("
Val ofbbefor
eoper ation()=",b)#20
operati
on()
pri
nt("
Val ofaaft
eroperation()=",a)#11
pri
nt("
Val ofbaft
eroperation()=",b)#21
updatevalues(
)
pri
nt("
Val ofaaft
erupdatev alues( )
=",a)#13
pri
nt("
Val ofbaft
erupdatev alues( )
=",b)#23

Anony
mousorLambdaFunct
ions

=>Anony mousFunct i
onsar ethosewhi chdoesnotcont ainanynameexplicitl
y.
=>Thepur poseofAnony mousFunct ionsisthat"ToPef ormInst
antOperations".
InstantOperationsarethosewhi char enolongerinterest
edtocarr
yinfur t
her
programs.
=>Anony mousFunct i
onscont ainssingleexecutablestatement
=>Anony mousFunct i
onsaut omat i
callyorimpli
citl
yreturnstheval
ue(NoNeedt o
user et
urnstatementtor eturnthev alue).
=>Todef ineAnony mousFunct i
ons, weuseakeywor d"lambda"andhence
Anony mousFunct ionsar ecalledLambdaFunct i
ons.

=>Sy
ntax:
v
arname=l
ambdapar
ams-
li
st:
Expr
essi
on

Explanati
on:
=>varnamei sanobj ectoft
ypeof<class'
functi
on'
>andvarnamei si
tselfi
ndi
rect
ly
actsfuncti
onname.
=>l
ambdai sakey wordusedfordefini
ngAnonymousFunctions
=>Params-listr
epresentsli
stofvari
abl
enamesusedf orst
or i
ngtheinputval
ues
comi ngfunctioncalls.
=>Expressionrepresentssi
ngleexecut
abl
est at
ementandpr ovi
dessoluti
onfor
I
nstantOper ati
on.

#anony
mousf unex1.
py
defaddop(
a,b):#Nor mal
Funct
ionDef
ini
ti
on
c=a+b
ret
urnc
sumop=l
ambdaa,
b:a+b#anony
mousFunct
iondef
ini
ti
on

#mai npr ogr am


res=addop( 10,20)
print("
typeofaddop=" ,
type(addop))#typeofaddop=<class'
functi
on'
>
print("
sum=" ,r
es)
print("
========================" )
print("
typeofsumop=" ,
type(sumop))#t ypeofsumop=<class'funct
ion'
>
x1=f l
oat(input (
"EnterFi rstvalue:
"))
x2=f l
oat(input (
"EnterSecondv al
ue:")
)
res1=sumop( x1,x2)
print("
sum=" ,r
es1)
#Wr iteapy t honpr ogr am whi chwill
calcul
ateal
lty
pesofacademi coperat
ions(
Use
menudr ivenappl i
cat i
onal ongwi thanonymousfunct
ion).
#aopmenuop1. py
#anony mousf unct iondef inions
i
mpor tsys
addop=l ambdaa, b:a+b
subop=l ambdaa, b:a-b
mul op=lambdaa, b:a*b
divop=lambdaa, b:a/ b
fl
oor div
op=l ambdak, v:k//v
modop=l ambdak, v:k%v
expop=l ambdak, v:
k* *v

defaopmenu(
):#Nor mal Funct i
onDef
ini
ti
on
pr
int
("
="*50)
pr
int
("
\tAri thm eti cOperati ons:
")
pr
int
("
="*50)
pr
int
("
\t1.
Addi t
ion:")
pr
int
("
\t2.
Subst raction" )
pr
int
("
\t3.
Mul ti
plication" )
pr
int
("
\t4.
Divisi
on" )
pr
int
("
\t5.
FloorDi vision" )
pr
int
("
\t6.
Modul oDi vision")
pr
int
("
\t7.
Exponent iation")
pr
int
("
\t8.
Exit")
pr
int
("
="*50)

#mainprogram
aopmenu()
ch=i
nt(
input(
"Ent
erUrChoice:"
))
match(ch):
case1:
x1=float(
input("
EnterFir
stValuef orAddi
ti
on:")
)
x2=float(
input("
EnterSecondVal ueforAddit
ion:"
))
res=addop( x1,
x2)
print
("Sum({ }
,{
})={
}".
for
mat(x1,x2,
res))
case2:
x1=float(
input("
EnterFi
rstVal
ueforSubst
ract
ion:
")
)
x2=float(
input("
EnterSecondVal
ueforSubstr
acti
on:"
))
res=subop(x1,x2)
print
("Sub({}
,{
})={
}".
for
mat (
x1,
x2,
res)
)
case3:
x1=float
(i
nput("EnterFi
rstVal
ueforMul
ti
pli
cati
on:
")
)
x2=float
(i
nput("EnterSecondVal
ueforMult
ipl
i
cati
on:"
))
res=mulop(x1,
x2)
print
("Mul(
{},
{}
)={}"
.for
mat (
x1,
x2,
res)
)
case4:
x1=float(
input(
"EnterFi
rstValueforDiv
isi
on:")
)
x2=float(
input(
"EnterSecondValueforDivi
sion:"
))
res=divop(x1,
x2)
print
("Div
({},
{}
)={}
".
format(x1,
x2,
res))
case5:
x1=float(i
nput(
"Ent erFi
rstVal
uef orFl
oorDi
vi
sion:")
)
x2=float(i
nput(
"Ent erSecondValueforFl
oorDi
v i
sion:"
))
res=floordi
vop(x1,x2)
print
("Floor
Div(
{ }
,{
})={}"
.f
ormat(
x1,x2,r
es)
)
case6:
x1=float
(i
nput(
"EnterFi
rstValueforModul
oDivi
sion:")
)
x2=float
(i
nput(
"EnterSecondValueforModul
oDiv i
sion:"
))
res=modop(x1,
x2)
print
("Mod({
},
{}
)={}
".f
ormat(x1,
x2,
res)
)
case7:
x1=float(
input
( "
EnterBase:
")
x2=float(
input
( "
EnterPower:
")
res=expop(x1,x2)
print
("expop({
},{
})={
}".
for
mat(x1,
x2,
res)
)
case8:
pr
int
("Thanksf
ort
hispr
ogr
am"
)
sy
s.exit
()
case_
:
pr
int
("
UrSel
ect
ionofOper
ati
oni
swr
ong!
--
tr
yagai
n")

#Wr i
teapy thonprogr am whichwill
calcul
ateal
lty
pesofacademi
coper
ati
ons(
Use
menudr ivenappli
cat i
onal ongwithanonymousfunct
ion)
.
#aopmenuop1. py
#anony mousf unctiondef i
nions
i
mpor tsys
addop=lambdaa, b:a+b
subop=lambdaa, b:a-b
mulop=lambdaa, b:a*b
div
op=lambdaa, b:a/ b
fl
oordiv
op=lambdak, v:k/
/v
modop=l ambdak, v:k%v
expop=lambdak, v:
k* *v
defaopmenu(
):#Nor mal Funct i
onDef
ini
ti
on
pr
int
("
="*50)
pr
int
("
\tAri thm eti cOperati ons:
")
pr
int
("
="*50)
pr
int
("
\t1.
Addi t
ion:")
pr
int
("
\t2.
Subst raction" )
pr
int
("
\t3.
Mul ti
plication" )
pr
int
("
\t4.
Divisi
on" )
pr
int
("
\t5.
FloorDi vision" )
pr
int
("
\t6.
Modul oDi vision")
pr
int
("
\t7.
Exponent iation")
pr
int
("
\t8.
Exit")
pr
int
("
="*50)

#mainprogram
aopmenu()
ch=i
nt(
input(
"Ent
erUrChoice:"
))
match(ch):
case1:
x1=float(i
nput ("EnterFirstVal uef orAddi t
ion: "))
x2=float(i
nput ("EnterSecondVal uef orAddi tion: ")
)
res=addop( x1,x2)
print
("Sum( {},
{})={}
".format (x1,x2,res)
)
case2:
x1=float(i
nput ("EnterFirstVal uef orSubst ract ion:"))
x2=float(i
nput ("EnterSecondVal uef orSubst ract i
on:")
)
res=subop( x1,x2)
print
("Sub({},{
})={}"
.format (x1,x2,res))
case3:
x1=float(i
nput ("EnterFirstVal uef orMul ti
plicat ion:"))
x2=float(i
nput ("EnterSecondVal uef orMul tiplication:"
))
res=mul op(x1,x2)
print
("Mul (
{},
{})={}"
.format (x1,x2,res))
case4:
x1=float(i
nput ("EnterFirstVal uef orDivisi
on: "))
x2=float(i
nput ("EnterSecondVal uef orDivision: "))
res=divop(x1,x2)
print
("Div({
},
{ }
)={ }
".
for mat(x1,x2, r
es))
case5:
x1=float(i
nput ("EnterFirstVal uef orFloorDi v i
si on:"))
x2=float(i
nput ("EnterSecondVal uef orFloorDi v i
sion:"
))
res=floordi
v op(x1,x2)
print
("FloorDiv({},
{})
={ }
".
format (x1,x2,
res))
case6:
x1=float(i
nput ("EnterFirstVal uef orModul oDi visi
on:"))
x2=float(i
nput ("EnterSecondVal uef orModul oDi visi
on:"
))
res=modop( x1,x2)
print
("Mod( {},
{})={}
".format (x1,x2,res)
)
case7:
x1=float(
input
( "
EnterBase:
")
)
x2=float(
input
( "
EnterPower:
"))
res=expop(x1,x2)
print
("expop({
},{
})={
}".
for
mat(x1,
x2,
res)
)
case8:
pr
int
("Thanksf
ort
hispr
ogr
am"
)
sy
s.exit
()
case_
:
pr
int
("
UrSel
ect
ionofOper
ati
oni
swr
ong!
--
tr
yagai
n")

#Wr i
teapy thonprogr am whichwill
calcul
ateal
lty
pesofacademi
coper
ati
ons(
Use
menudr ivenappli
cat i
onal ongwithanonymousfunct
ion)
.
#aopmenuop2. py
#anony mousf unctiondef i
nions
i
mpor tsys
addop=lambdaa, b:a+b
subop=lambdaa, b:a-b
mulop=lambdaa, b:a*b
div
op=lambdaa, b:a/ b
fl
oordiv
op=lambdak, v:k/
/v
modop=l ambdak, v:k%v
expop=lambdak, v:
k* *v

defaopmenu(
):#Nor mal Funct i
onDef
ini
ti
on
pr
int
("
="*50)
pr
int
("
\tAri thm eti cOperati ons:
")
pr
int
("
="*50)
pr
int
("
\t1.
Addi t
ion:")
pr
int
("
\t2.
Subst raction" )
pr
int
("
\t3.
Mul ti
plication" )
pr
int
("
\t4.
Divisi
on" )
pr
int
("
\t5.
FloorDi vision" )
pr
int
("
\t6.
Modul oDi vision")
pr
int
("
\t7.
Exponent iation")
pr
int
("
\t8.
Exit")
pr
int
("
="*50)

#mainprogr
am
whi
le(
True):
aopmenu( )
ch=int(
input(
"Ent
erUrChoi
ce:
")
)
mat ch(ch):
case1:
x1=float(
input("
EnterFi
rstValuef orAddi
ti
on:")
)
x2=float(
input("
EnterSecondVal ueforAddit
ion:"
))
res=addop( x1,
x2)
print
("Sum({ }
,{
})={
}"
.f
ormat(x1,x2,
res))
case2:
x1=f
loat
(i
nput
("
Ent
erFi
rstVal
uef
or
Subst
ract
ion:
")
)
x2=f
loat
(i
nput
("
Ent
erSecondVal
uef
or
Subst
ract
ion:
")
)
res=subop(
x1,
x2)
print
("
Sub({
},
{}
)={
}"
.f
ormat
(x1,
x2,
res)
)
case3:
x1=f
loat
(i
nput
("
Ent
erFi
rstVal
uef
or
Mul
ti
pli
cat
ion:
")
)
x2=f
loat
(i
nput
("
Ent
erSecondVal
uef
or
Mul
ti
pli
cat
ion:
")
)
res=mulop(
x1,
x2)
print
("
Mul({
},
{}
)={
}"
.f
ormat
(x1,
x2,
res)
)
case4:
x1=float(
input(
"EnterFi
rstValueforDiv
isi
on:")
)
x2=float(
input(
"EnterSecondValueforDivi
sion:"
))
res=divop(x1,
x2)
print
("Div
({},
{}
)={}
".
format(x1,
x2,
res))
case5:
x1=f
loat
(i
nput
("
Ent
erFi
rstVal
uef
orFl
oor
Di
vi
si
on:
")
)
x2=f
loat
(i
nput
("
Ent
erSecondVal
uef
orFl
oor
Di
vi
si
on:
")
)
res=fl
oordi
vop(
x1,x2)
print
("
Floor
Div(
{},
{}
)={
}".
for
mat
(x1,
x2,
res)
)
case6:
x1=f
loat
(i
nput
("
Ent
erFi
rstVal
uef
orModul
o
Di
vi
si
on:
")
)
x2=f
loat
(i
nput
("
Ent
erSecondVal
uef
orModul
o
Di
vi
si
on:
")
)
res=modop(
x1,
x2)
print
("
Mod({
},
{}
)={
}"
.f
ormat
(x1,
x2,
res)
)
case7:
x1=float(
input
( "
EnterBase:
")
)
x2=float(
input
( "
EnterPower:
"))
res=expop(x1,x2)
print
("expop({
},{
})={
}".
for
mat(x1,
x2,
res)
)
case8:
pr
int
("Thanksf
ort
hispr
ogr
am"
)
sy
s.exit
()
case_
:
pr
int
("
UrSel
ect
ionofOper
ati
oni
swr
ong!
--
tr
y
agai
n")
#Wr i
teapy thonprogr am whichwill
calcul
ateal
lty
pesofacademi
coper
ati
ons(
Use
menudr ivenappli
cat i
onal ongwithanonymousfunct
ion)
.
#aopmenuop3. py
#anony mousf unctiondef i
nions
i
mpor tsys
addop=lambdaa, b:a+b
subop=lambdaa, b:a-b
mulop=lambdaa, b:a*b
div
op=lambdaa, b:a/ b
fl
oordiv
op=lambdak, v:k/
/v
modop=l ambdak, v:k%v
expop=lambdak, v:
k* *v

defr
eadvalues(op):
x1=float(
input
("
Ent
erFi
rstVal
uefor{
}:
".
format
(op)
))
x2=float(
input
("
Ent
erSecondVal
uefor{}
:"
.f
ormat(
op)
))
ret
urnx1, x2

defaopmenu(
):#Nor mal Funct i
onDef
ini
ti
on
pr
int
("
="*50)
pr
int
("
\tAri thm eti cOperati ons:
")
pr
int
("
="*50)
pr
int
("
\t1.
Addi t
ion:")
pr
int
("
\t2.
Subst raction" )
pr
int
("
\t3.
Mul ti
plication" )
pr
int
("
\t4.
Divisi
on" )
pr
int
("
\t5.
FloorDi vision" )
pr
int
("
\t6.
Modul oDi vision")
pr
int
("
\t7.
Exponent iation")
pr
int
("
\t8.
Exit")
pr
int
("
="*50)

#mainprogr
am
whi
le(
True):
aopmenu( )
ch=int(
input(
"Ent
erUrChoice:"
))
mat ch(ch):
case1:
x1,x2=readvalues("Addition" )
res=addop(x1,x2)
print
("Sum({},
{})={}
".for
mat ( x1,
x2,r
es)
)
case2:
a,b=readval
ues( "Substraction")
res=subop(a,b)
print
("Sub({
},{
})={}"
.format (a,b,
res)
)
case3:
x1,x2=readvalues("Multipli
cat i
on")
res=mul op(
x1,x2)
pr
int
("
Mul
({
},
{}
)={
}"
.f
ormat
(x1,
x2,
res)
)
case4:
x1,x2=readvalues("
Div
isi
on")
res=divop(x1,
x2)
print
("Div(
{},
{}
)={}"
.f
ormat(
x1,x2,
res)
)
case5:
x1,x2=readval
ues("Fl
oorDi
visi
on")
res=fl
oor di
vop(
x1,x2)
print
("Fl
oorDiv(
{},
{}
)={}
".
for
mat(x1,
x2,
res)
)
case6:
x1,x2=readv
alues("
ModuloDiv
isi
on")
res=modop( x1,
x2)
print
("Mod({},
{}
)={
}"
.for
mat(
x1,
x2,
res))
case7:
x1=float(
input
( "
EnterBase:
")
)
x2=float(
input
( "
EnterPower:
"))
res=expop(x1,x2)
print
("expop({
},{
})={
}".
for
mat(x1,
x2,
res)
)
case8:
pr
int
("Thanksf
ort
hispr
ogr
am"
)
sy
s.exit
()
case_
:
pr
int
("
UrSel
ect
ionofOper
ati
oni
swr
ong!
--
tr
y
agai
n")

#Pr ogr am accept i


ngt woi ntegervaluesandf i
ndbi ggestbyusinganonymous
funct i
ons
#bi gex1. py
big=lambdaa, b:aifa>bel seb#anony mousf uncti
ons
smal l=lambdaa, b:aifa<bel seb #anony mousf uncti
ons
#mai npr ogram
bv=bi g(float(
input("EnterFir
stVal ue:"
)),
fl
oat(i
nput("
EnterSecondValue:"
)))
print("Biggest={}".
format (
bv))
sv=smal l(f
loat(i
nput (
"EnterFirstValue:"
)),
fl
oat(i
nput("
EnterSecondValue:"
)))
print("smal l
est={}"
.format (
sv )
)

#Program accept
ingthreei
ntegerval
uesandfi
ndbiggestbyusi
nganony
mous
functi
ons
#bigex2.
py
big=l
ambdaa, b,
c:aif
(a>b)and(a>c)el
sebi f(
b>c)and(b>a)el
sec

#mainpr ogram
pr
int
("EnterThreevalues:"
)
bv
=big(int(
input
())
,int(
input(
)),
int
(i
nput
()))
pr
int
("Biggest="
,bv
)
#Program accept
ingthreei
ntegerv
aluesandfi
ndbiggestbyusi
nganonymous
functi
ons
#bigex3.
py
big=l
ambdaa, b,
c:"ALLVALUESEQUAL"i f(
a==b)and(b==c)el
seaif
(a>b)and(
a>c)
elsebi f(
b>c)and( b>a)el
sec

#mai npr ogram


pri
nt("EnterThr eevalues:"
)
bv=big(int(
input())
,int(
input(
)),i
nt(
input
()))
pri
nt("Biggest=",bv
)
#Progr am accept i
nglistofintegerval
uesandf
indbi
ggestandsamml
estbyusi
ng
anony mousf uncti
ons
#bigsmal l.
py

bi
g=l
ambdalst:
max(l
st)#anonymousfunct
ions
smal
l
=lambdahyd:
min(hyd)#anonymousfunct
ions

#mainpr ogr am
pr
int(
"Ent erListofVal uessepar at
edbyspace:
")
l
st=[i
nt(
v al)f orvalininput()
.spli
t(
)]
bv=bi
g(lst)
sv=small(lst)
pr
int(
"bi
ggest ({
})={}
".f
or mat(
lst,
bv))
pr
int(
"smal l
est({
})={}
".format(l
st,
sv))

================================================================
Di
ff
erencesbet
weenNor
mal
Funct
ionsandAnony
mousFunct
ions
================================================================
=>Nor mal Functionsalway susedf orper formi ngLongTer m Operati
on(nothi
ngbut
wecanr e-useinev erypar tofpr oject),wher eAnony mousFunct i
onsarethosewhich
aremeantf orper f
ormi ngInst antOper ations.
=>Nor mal Functionsdef init
ionscont ainsBl ockofst atement swhereAnony mous
Funct i
onscont ainssi ngleexecut abl est atement .
=>Nor mal FunctionDef init
ionst artswi th" def"key wordwher eAnony mous
Funct i
onsdef einit
ionst artswi t
h" lambda"
=>Tor eturnthev aluefrom nor mal funct i
on, itismandat orytouser et
urn
statement .wher easAnony mousFunct i
onsr eturnst hev al
ueautomaticall
y/
i
mpl citl
y(noneedt ouser eturnstat ement ).
=>Sy ntaxf ornormal funct i
on:
def f uncti
onname( li
stoff ormal params) :
---
--
---
---
--
--
----
---
----
---
--
-----
--
---
--
---
-
Blockofst atement s
--
---
---
---
----
----
---
--
---
---
--
---
--
---
---
---
-
=>Sy ntaxforAnony mousFunct ions:
varname=l ambdapar ams- li
st: expressi
on
===========================x====================================
Speci
alFunct
ionsi
nPy
thon

=>I
nPy
thonPr
ogr
ammi
ng,wehave3t y
pesofFunct
ions.Theyar
e
1)f
il
ter
()
2)map()
3)r
educe()

1)f
il
ter
()
=>fi
lter()isusedf orf i
lt
eringoutsomeel ementsf rom givenli
stofel ement sby
applyingt ogi venfunct ion.
=>Synt ax:-
varname=f il
ter(Funct i
onname,Iterabl
eobject )
Explanat i
on:
=>varnamei sanobj ectof<cl ass,'
fil
ter'
>andwecanconv ertintoanyi terableobject
typebyusi ngI tyer
abl etypecast ingf uncti
ons.
=>Funct ionnamecanbeei therNor mal f
uncti
onoranony mousf unction.
=>It
er ableobj ectcanbesequence, l
ist,setordicttype.
=>Theexecut i
onpr ocessoff i
lt
er()isthat"Eachel ementofI t
erableobj ectpassi
ngt o
specifiedf unction, t
hef unctiondeci desTr ueorFal sebasedoncondt ion,ift
he
functionr eturnsTr uet henthecor respondingelementwi llbef i
lt
eredandi fthe
functionr eturnsFal set henthecor respondingelementwi llbenegl ected( notfi
lt
ered)
".ThisPr ocesswi l
l becontinuedunt ilal
lelement sofit
erablecompl eted.

#Thi
spr ogram t
akesli
stofvaluesandext
ractonl
y+v
eval
ues
#Fi
lt
erEx1.py
defposi tve(
n):
ifn>0:
ret
urnTrue
else:
ret
urnFalse

defnegat
ive(
n):
i
f(
n<0):
ret
urnTrue
el
se:
ret
urnFalse

#mai npr ogr am


l
st=[10,-20,30, 0,
40,-50,-60,70,23]
obj1=fil
ter(posi tve,l
st)
pri
nt("typeofobj =",t
y pe(obj1) )#<cl
ass,
'f
il
ter'
>
psl
ist=list(
obj 1)
pri
nt("Or i
ginal Element s=" ,
lst)
pri
nt("Possi tiveElement s=",psli
st)
obj2=fil
ter(negat ive,l
st)
ngtpl=tuple(obj 2)
pri
nt("Negat iv eElement s=",ngtpl
)
#Thispr ogr am t akesl i
stofv aluesandextr
actonl
y+v
eval
ues
#Filt
erEx2. py
defposi tve( n):
i
fn>0:
returnTr ue
el
se:
returnFal se

defnegat i
v e( n):
i
f (n<0) :
r eturnTr ue
else:
r eturnFal se
#mai npr ogr am
pri
nt("Ent erl istofv aluessepar atedbyspace:")
l
st=[i
nt (
v al)f orv al i
ni nput().split
()]
obj1=fil
ter (posi tve, l
st)
pri
nt("typeofobj =",type(obj1) )#<cl ass,
'f
il
ter'
>
psl
ist=list(obj 1)
pri
nt("Or i
gi nal Element s=",
lst)
pri
nt("Possi tiveEl ement s=",pslist)
obj2=fil
ter (negat i
v e,l
st )
ngtpl=tupl e(obj 2)
pri
nt("Negat iv eEl ement s=",ngtpl)
#Thispr ogr am t akesl istofv al
uesandext r
actonl
y+v
eval
ues
#Filt
erEx3. py
positi
ve=l ambdax: x>0
negative=l ambdak: k<0
#mai npr ogr am
pri
nt("Ent erl istofv aluessepar atedbyspace:")
l
st=[i
nt (
v al)f orv al i
ni nput().split
()]
psl
ist=list(filter (posi tive,
lst))
ngl
ist=tupl e( filter(negat i
ve,lst))
pri
nt("-
----
---------
-------
----
---
--
--
------
-")
pri
nt("Or i
gi nal Element s=",
lst)
pr
int
("
Posit
iveEl
ements=",
psli
st)
pr
int
("
Negati
veElements=",
ngl
ist
)
pr
int
("
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-"
)

#Thispr ogram takeslistofv aluesandextractonl


y+v
eval
ues
#Fil
terEx4.py
pri
nt("
Ent erli
stofv al
uessepar atedbyspace:"
)
l
st=[i
nt(val)forvalininput()
.split(
) ]
psl
ist=li
st(fi
lt
er(l
ambdax: x>0,lst))
ngl
ist=tuple(fi
l
ter(
lambdak: k<0, lst)
)
pri
nt("
---
---
--
---
--
--
---
--
---
--
---
--
--
--
----
-")
pri
nt("
Or i
ginalElement s=",
l
st)
pri
nt("
Posi ti
veElement s=",
pslist)
pri
nt("
Negat iveElement s=",
nglist)
pri
nt("
---
---
--
---
--
--
---
--
---
--
---
--
--
--
----
-")

#Thi spr ogram accept slistofv aluesandext ractEv enNumber s


#FilterEx5.py
pri
nt ("Enterlistv aluessepar at edbyspace: "
)
l
st=[int (
val)forv al i
ninput ().
spl it
()]#l st=[4671263481]
evenl st=tuple(filter(
lambdan: n%2==0, l
st))
pri
nt ("Origi
nal list=",l
st)
pri
nt ("Evenlist=" ,evenlst)
#wr iteapy t
honpr ogram whi chwi l
lacceptal ineoft extandf i
lt
ervowel
sandpr int
theircount
#FilterEx6.py
s=input ("Enterl i
neoft ex t
:")
vowel s=list(
f i
lter(lambdach: chi n[ '
a'
,'
e',
'o',
'i
',
'
u','
A'
,'
E'
,'I
',
'
O',
'U'
],s))
pri
nt ("--
--
---
--
----
------
--
--
---
---
---
---
-----
---
--
--
--"
)
pri
nt ("GivenLi neofText ={}".
for mat (
s))
pri
nt ("Vowel s={ }".f
ormat (vowel s))
pri
nt ("Numberofv owel s={}".
for mat (l
en(v owels)))
pri
nt ("--
--
---
--
----
------
--
--
---
---
---
---
-----
---
--
--
--"
)
cons=l i
st(f
il
ter( l
ambdach: chnoti n['
a','
e','
o',
'
i'
,
'u',
'
A',
'
E' ,
'
I'
,'
O',
'
U']andnotch.
isspace()
andnotch. i
sdi git(),s))
pri
nt ("consonant s={ }
".format (cons) )
pri
nt ("Numberofconsonant s={ }".
format (l
en(cons) )
)
pri
nt ("--
--
---
--
----
------
--
--
---
---
---
---
-----
---
--
--
--"
)
#Thi spr ogram t akesl i
stofv aluesandext ractonly+v ev al
ues
#nonFi l
terEx.py
defposi t
ivenegat ive(l
st )
:
pslist=[]
nglist=[ ]
forv al inlst:
if(val>0):
pslist.append( val)
else:
nglist.append( val)
r
etur
npsl
i
st,
ngl
i
st

#mainpr ogr am
pri
nt("
Ent erlistofvaluessepar atedbyspace:
")
l
st=[i
nt(val)forv ali
ninput ().
spli
t(
)]
psl
,ngl=positivenegative(l
st)
pri
nt("
Or ginal El
ement s:",
l
st)
pri
nt("
Possi tiveElement s:"
,psl)
pri
nt("
Neget i
v eElement s:
",
ngl)

2)map(
)

=>Thepur poseofmap( )i
sthat"Toconver
tOldIt
erbaleobj
ectel
ement
sintonew
I
nterableobjectEl
ementsbyapplyi
ngtothefunct
ion".
=>I
not herwords,map()conver
tsoldl
istel
ementsintonewli
stel
ementsbyappl
ying
tothefuncti
on

=>Sy
ntax:
-
varname=map( Functi
onname,Iterabl
eobject )
=>varnamei sanobj ectof<class,'
map'>andwecanconv ertintoanyi t
erableobject
typebyusi ngI tyerabletypecast i
ngfuncti
ons.
=>Funct i
onnamecanbeei therNormal f
unctionoranonymousf uncti
on.
=>It
erableobj ectcanbesequence, li
st,setordicttype.
=>Theexecut ionpr ocessofmap( )i
sthat"Ev eryelementofi ter
ableobj ectsending
tothespeci fiedf uncti
on,functionwill
executebusi nessl
ogi candr eturnedtheresult
fr
om f unctionandi twill
bepl acedinanobj ectoftype<class,map>" .ThisProcess
will
becont inuedunt ilal
lelement sofit
erableobjectcomplet ed.
#Thispr ogram accept slistofelementsandget sitssquarel ist
.
#mapex1. py
defsquar e(n):
result=n* *2
returnresul t

#mai npr ogr am


print("
Ent erl istofelement ssepar atedbyspace:")
oldlst=[int(val )forv
alini nput()
.spli
t()]
mapobj =map( square,
oldlst)
print("
\ nTypeofmapobj ={}"
.for
mat (type(mapobj
))
)
sqr l
ist=li
st(mapobj )
print("
Or iginal El
ements:{}".
format (
oldlst)
)
print("
New El ement s:
{}"
.format (sqrl
ist))
#Thi spr ogr am accept sl istofelement sandgetsitssquar
eli
st.
#mapex2. py
print("
Ent erl istofelement ssepar atedbyspace:")
oldlst=[int(val )forv
alini nput()
.spli
t()]
sqr l
ist=t
upl e(map( l
ambdav al
:
val *
*2, oldl
st))
print("
Or i
gi nal El
ements:{
}".
for
mat (
oldlst)
)
print("
New El ements:
{}"
.f
ormat (sqrl
ist))
#Thi spr ogr am acceptslistofelement sandget sitssquar
eli
st.
#mapex3. py
print("
Ent erl i
stofelementssepar atedbyspace: ")
oldlst=[i
nt (val)forval
ininput(
).spli
t()]
sqr ootli
st=t uple(map(l
ambdav al :
val**
0.5, ol
dlst
))
print("
Or i
gi nal El
ements:{
}".
for
mat (
oldlst)
)
print("
New El ements:
{}"
.f
ormat (sqrootli
st)
)

#Thi
sprogr am acceptslistofel
ement
sandget
sit
ssquar
eli
st.
#mapex4. py
defdisp(lst)
:
print
("
-"*
40)
forvali
nl st
:
pri
nt(
"%0.2f"%v
al)
print
("
-"*
40)

#mapex4. py
print("
Ent erl i
stofelementsseparatedbyspace:
")
oldlst=[
int (val)forval
ininput
().
spli
t()
]
sqr ootl
ist =tuple(map(l
ambdav al
:val
**0.
5,oldl
st)
)
print("
Or iginal El
ements:"
)
di
sp( oldlst )
print("
New El ements:
")
di
sp( sqr oot l
ist)

#Thi spr ogr am accept sl i


stofel ement sandgetsitssquar
eli
st.
#mapex5. py
print("
Ent erl i
stofel ement ssepar atedbyspace:")
oldlst=[i
nt (val)forv ali
ninput()
.spl i
t()
]
sqr ootli
st=t uple(map( l
ambdav al:val*
*0.5,ol
dlst
))
print("
-"*50)
print("
Or i
gi nal Elements\tSquarer ootElements:"
)
print("
-"*50)
foron, sninzi p( oldl
st,
sqrootli
st):
print("\t{}
\t\t
{}"
.f
ormat (on,round(sn,
3))
)
print("
-"*50)

#Thi spr ogram acceptslistofelement sandgetsitssquar


eli
standsquar
eroot.
#mapex6. py
print("
Ent erli
stofelementssepar atedbyspace:")
oldlst=[
int (v
al)forval
ininput(
).spli
t()
]
sqr ootl
ist=tuple(map(l
ambdav al
:val
**0.5,ol
dlst
))
sqlist=t
upl e(map( l
ambdav al
:val*
*2, oldl
st)
)
print("
-"
* 50)
pri
nt("
Ori
ginal\
tSquareRoot\tSquar
e:"
)
pri
nt("
-"
*50)
foron,
sqrtno,
sqrnoinzip(ol
dlst,
sqr
ootli
st,
sql
ist
):
print
("
\t{
}\t
{}\t
\t{
}".
format(
on,r
ound(sqrt
no,
2),
sqr
no)
)
pri
nt("
-"
*50)

#Thi spr ogram accept sl istofOl dSal ari


esofempl oy eesandget snewsalaryl
ist
#mapex7. py
print("
Ent erlistofol dsl ariesofempl oyees:")
oldsal=[float (
v al)f orv al ini nput ()
.spl it()]
newsal =list(map( lambdasal :
sal +sal * 0.15,ol
dsal ))
print("
="* 50)
print("
OldSal ar ies\ tNewSal ari
es" )
print("
="* 50)
forold,newi nzi p(oldsal ,
newsal ):
pr i
nt("\ t{
}\t{ }
".format (old,round( new, 3)))
print("
="* 50)
#Thi spr ogram accept stwol istsofel ement sandf indt heirsum.
#mapex8. py
print("
Ent erlistofel ement sforFi rstLi st")
l
st 1=[f
loat (val)f orv alini nput ().
spl it()]
print("
Ent erlistofel ement sforSecondLi st"
)
l
st 2=[f
loat (val)f orv alini nput ().
spl it()]
suml st=list(map( lambdax, y :
x+y ,
lst 1,lst2))
print("
="* 50)
print("
\tList1\ tList2\ tList1+Li st2")
print("
="* 50)
forx,y,zinzi p( l
st 1,lst2,suml st):
pr i
nt("\ t{
}\t{ }
\t{}".format (
x ,y,z))
print("
="* 50)
#wr it
eapy thonpr ogr am whi chwi l
l acceptl istofempl oy eessalari
esbetween1000
toanysal ar
y.gi v
e15%hi ket ot hoseempl oy eeswhoi sdr awingmor ethan5000
andgi ve30%hi ket ot hoseempl oy eeswhosedr awi ngl essthan5000.
#mapex9. py
print("
Ent erLi stofSal ar i
esofEmpl oy ee:")
orginalsal =[
int( sal)f orsal ini nput ().spl i
t()
]
salless5000=l ist (
filter(lambdasal :sal <=5000, orginalsal))
hikesallesst han5000=l ist(map( l
ambdasal :
sal +sal*(30/ 100),sal
less5000))
salmor e5000=l ist(fil
ter( l
ambdasal :
sal >5000, orginalsal))
hikesalmor ethan5000=l i
st(map( lambdasal :
sal +sal* (
15/ 100) ,
salmore5000))
print("
="* 50)
print("
\tSal LessThan5000\ tHi keSal ari
es")
print("
="* 50)
forsal,hsal inzi p(sal l
ess5000, hikesal lessthan5000) :
pr i
nt("\ t\
t{}\ t
\ t
{ }
".format (sal ,
hsal )
)
pri
nt("
="*50)
pri
nt("
="*50)
pri
nt("
\tSalMoreThan5000\ tHikeSalari
es"
)
pri
nt("
="*50)
forsal
,hsalinzip(sal
mor e5000,
hikesal
morethan5000)
:
pr
int(
"\t\
t{}\
t\t
{}"
.for
mat(sal,
hsal
))
pri
nt("
="*50)

r
educe(
)

=>reduce()isusedforobtaini
ngasingleelement/r esultfrom gi
venit
erabl
eobj
ect
byapply i
ngtoaf unct
ion.
=>Syntax:-
varname=reduce(f
uncti
on- name,iter
abl
e-obj
ect)
=>herev ar
namei sanobjectofint,f
loat
,bool
,complex,st
ronl y
=>Ther educe()bel
ongstoapr e-def
inedmodul ecal
led"f unctool
s".

I
nter
nal
Flowofr
educe(
)

step-
1:-reduce( )selectstwoFirstvaluesofI terableobjectandpl acethem Fi
rstvar a
step-
2:-Thef unction-nameutil
i
zest heval uesofFi rstvarand
Secondv arappl i
edtothespeci f
iedl ogicandobt ainstheresul
t.
Step-
3:-r educe( )placestheresultoffunct i
on-namei nFirstvari
able andreduce()
sel ectsthesucceedingelementofI terableobjectandpl acesinsecond
vari
able.
Step-
4: repeatSt ep-2andStep-3unt i
lal
l element scompl etedin
I
terableobj ectandreturnstheresul tofFirstVariabl e

#Thisprogr am accept sli


stofv aluesandfi
ndthei
rsum byusi
ngr
educe(
)
#redceex 1.py
i
mpor tfunct ools
print
("
Ent erListofv al
uessepar atedbyspace:
")
l
st=[i
nt(val)forval i
ninput (
).spl
it
()]
resul
t=funct ool
s.reduce(lambdaa, b:
a+b,
lst
)
print
("
\nLi stofelement s=",
lst)
pri
nt("
Sum=" ,r
esult)
#Thispr ogr am accept slistofv aluesandf indmaxandmi nf
rom l
i
stofel
ement
s.
#reduceex2. py
i
mpor tf unct ools
pri
nt("
Ent erLi stofv aluessepar atedbyspace: "
)
l
st=[i
nt (val)f orval i
ni nput ().
split(
) ]
bi
g=funct ool s.r
educe( lambdax, y:xi fx>yelsey ,l
st)
small=funct ools.reduce( lambdax, y:xifx<yelsey ,l
st)
pri
nt("
\ nLi stofel ement s={ }
".
for mat (lst
))
pri
nt("
Bi ggestEl ement ={}".f
ormat ( big))
pri
nt("
Smal lestElement ={ }
".f
or mat (smal l
))
#Thispr ogr am accept slistofv aluesandf indmaxandmi nf
rom l
i
stofel
ement
s.
#reduceex3. py
fr
om f unct oolsimpor tr educe
pri
nt("
Ent erLi stofv aluessepar atedbyspace: "
)
l
st=[i
nt (val)f orval i
ni nput ().
split(
) ]
bi
g=reduce( lambdax, y:xi fx>yel sey ,l
st)
small=reduce( l
ambdax, y:xifx<yel sey ,l
st)
pri
nt("
\ nLi stofel ement s={ }
".
for mat (lst
))
pri
nt("
Bi ggestEl ement ={}".f
ormat ( big))
pri
nt("
Smal lestElement ={ }
".f
or mat (smal l
))
#Thispr ogr am accept slistofSr i
ngssepar atedbycommaandobt ai
nsi
ngl
eli
ne.
#reduceex4. py
i
mpor tf unct ools
pri
nt("
Ent erLi stofv aluessepar atedbycomma: ")
l
st=[str(v al)f orv alininput ().spli
t(",
")]
pri
nt("
cont entofl ist=",l
st )
si
ngleline=f unctools.reduce( lambdax, y:
x+""+y,
lst)
pri
nt("
Resul t={}
".
format (singleli
ne) )
I
ter
ator
sinpy
thon
=>It
erat
orisakindofobj ectwhichisacol lect
ionofotherelements.
=>Forexample:
-l i
standt upl
earei t
erables.
=>I
nPy t
hon,i
ter()convertsIt
erableobjects(li
st,t
uple,set,fr
ozenset
….et
c)int
oit
erat
or
Obj
ectanditt
akesl essmemor yspaceandpr ovi
desv al
uewhenwer equest.
=>Ani
ter
atori
sanobj
ectt
hatcont
ainscountabl
enumberofv
alues.
=>Ani
ter
atori
sanobj
ectt
hatcanbeiter
atedwit
hall
val
ues.

Exampl
e: lst
=[“apple”
,“mango”
,“ki
wi”
,“guav
a”]
f
orfrtinlst:
print(
frt)

=>Her
elsti
sbydefaul
tit
erable.
=>Pr
ogrammat
ical
l
y, t
oconv er
tanobj
ectwhi
chcont
ainsmul
ti
plesv
aluesasi
ter
ator
obj
ect,
weuseit
er(
).

=>Sy
ntax: i
tr
obj
=it
er(
obj
ectwi
thmul
ti
plev
alues)

=>Toretri
vethev al
uesf
rom i
ter
atorobj
ect,weusenext (
)andi
tgener
atesan
except
ionStopI
ter
ati
onwhennoval
uepresenti
nit
erat
orobj
ect.

Exampl e-1:
#it
eratorex1. py
l
st=["
appl e" ,"
mango" ,
"ki
wi","
guava"]
forfr
tinl st:
pri
nt(frt)
pri
nt("
=================OR==================="
)
i
trl
st=i
ter (l
st)
pri
nt("
wear eini t
erati
onpart"
)
pri
nt("
typeofi telst"
,t
ype(i
tr
lst
))
pri
nt("
cont entofl i
stit
erat
or:"
,i
tr
lst
)
pri
nt("
-"*50)
whil
e(Tr ue) :
tr
y:
pri
nt (next(itr
lst
))
exceptSt opIterat
ion:
break
OUTPUT:
apple
mango
ki
wi
guav a
=================OR===================
wear einiterat
ionpar t
typeofitel
st<class' l
i
st _
iter
ator'
>
contentoflistit
erator:<l
ist_i
ter
atorobj
ectat0x0000020B02DB5660>
--
---
--
--
--
--
---
--
---
--
--
--
---
--
---
---
--
---
--
--
--
-
apple
mango
ki
wi
guav a

Decor
ator
s
=>ADecoratorisafuncti
onthat’
sprovi
desadditi
onalFuncti
onal
i
t ytotheexisti
ng
Funct
ional
it
yofnor malfunct
ion.
=>Adecoratortakestheresul
tofnormalfunct
ion,Modifi
estheresultandretur
ns
modif
iedresult
.
=>Adecorator
salwaystakesnormal f
unct
ionnameasanar gument .
EXAMPLE- 1:
Program forgener at
ingsquareofnowi t
houtusi
ngdecor
ator
:
#program f orgett
ingsquareofgivennumber
#non_ decorex1.py
defget val
ues():#nor malfunct
ion
ret
ur n(f
loat(
input(
"Ent
eranumber :"
)))

defsquare()
:#prov
idessquar
eforanumberr
etur
nbyget
val
ues(
)
x=get
values(
)
ret
urnx,x*
*2

#mai nprogram
n,
result
=square()
pri
nt("
square({
})={
}".
for
mat
(n,
resul
t)
)
OUTPUT:
Enteranumber :6
square(6.
0)=36.0

EXAMPLE-2:
#decor
ex1.
py--
--
--
--
--
--
WAYONE

defget
val
ues(
):#nor
mal
funct
ion
r
etur
n(f
loat
(i
nput
("
Ent
eranumber:
")
))

defsquar e(get v
):
defcal ()
:#innerfunct
ionname
val=get v()
x=v al*
*2
returnx
ret
ur ncal
#mai npr ogram
squ=squar e( getv
alues)
s=squ( )
pri
nt("Squar e=",
s)
OUTPUT:
Enteranumber: 5
Square=25. 0
#decorex2.py--
--
--
--
--
WAY2
defsquare(getv): #heresquarei
scall
eddecor
ator
defcalculat
ion()
:#i nnerfunct
ionname
val
=getv (
)
s=val*
*2
ret
urns
ret
urncalculati
on

defsquareroot(
getv)
:#her esquarer
ooti
scal
l
eddecor
ator
defcalcul
ati
on():#innerfunct
ionname
val
=getv()
s=val*
*0.5
ret
urns
ret
urncalcul
ation

@square#Programmerdefineddecorat
or
defget
val
ue()
:#Nor malfuncti
on
r
etur
n(f
loat
(i
nput(
"Ent
eranumberf orsquar
e:"
)))

@squarer
oot
defget
number()
:#Normalfunct
ion
r
etur
n(f
loat
(i
nput
("
Enteranumberforsquar
eroot
:"
)))

#mai nprogram
resul
t=getvalue()
print
("
Squar e:"
,r
esult
)
print
("
-"
*50)
resul
t=getnumber ()
print
("
Squar e:"
,r
esult
)

OUTPUT:
Enteranumberf orsquar
e:12
Square:144.0
-
--
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
Enteranumberf orsquar
eroot:
400
Square:20.0

Modul
esi
nPy
thon

=>Weknowt hatFuncti
onsconceptmakesusunder
standHowtoperform
operationsandwecanr e-
usewithi
nthesameprogr
am butnotabl
etore-uset
he
functi
onsacr osst
heprograms.
=>Tor eusethefunct
ionsacrossthepr
ograms,wemustusetheconceptof
Modules.

=>Defi
nit
ionofModules:
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
=>AModul eisacoll
ecti
onofv
ari
abl
es(
global
var
iabl
es),
Funct
ionsandCl
asses.

=>TypesofModules:
=>I
nPy t
honProgramming,wehavetwotypesofModules.Theyar
e
1)Pre-
defi
ned(or
)Buil
t-
inModules
2)Progr
ammeroruserorcustom-def
inedmodules.

1)Pre-defi
ned(or)Buil
t-
inModul es:
--
--
--
---
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
-
=>Thesemodul esaredev el
opedbyPy t
honLanguageDevel
opersandtheyare
avi
alableinPythonAPIsandt heyareusedpy
thonprogr
ammer sfordeal
ingwit
h
UniversalRequi
rements.

Exampl
es: mat
h cmat hfunct
ool
ssy scal
endaros
rethreadi
ng pi
ckl
e random.
..
..
..
etc

=>Outofmanypre-
def
inedmodul
es,i
npyt
honprogrammingonei
mpl
i
citpr
e-def
ined
moduleimpor
tedtoev
erypyt
honprogr
am cal
l
ed"buil
ti
ns".

2)Programmeroruserorcust om-def
inedmodul es:
--
--
--
--
---
--
--
---
--
--
--
---
--
--
--
---
--
--
---
---
---
--
--
--
--
--
--
---
---
--
--
---
---
--
--
---
--
-
=>Thesemodul esaredev elopedbyPy thonPr ogrammer sandt
heyar
eavi
alabl
ein
PythonProjectandt heyar eusedbyot herpy thonpr ogrammerswhoarei
nproj
ect
developmentt odeal wi
thcommonr equirement s.
=>Exampl es:
- aop mat hsinfo. .
..
..
etc

Dev
elopmentofPr
ogrammer-
Defi
nedModul
e
=>Todev
elopmentPr
ogr
ammer-Def
inedModul
es,wemustuset
hefol
l
owi
ngst
eps

St
ep-
1:Def
ineVar
iabl
es(
Global
var
iabl
es)
Step-2: Def i
nedFunct i
ons
Step-3: Def i
neCl asses
=>Afterdev elopingst ep- 1, step-2andst ep- 3,wemustsav eonsomef il
enamewi
th
anext ension. py(FileName. py )anditist reatedasmodul ename.
=>Whenaf i
lenamet reatedasamodul ename, i
nternall
yPythonexecuti
on
envi
ronmentcr eatesaf olderaut omat icallyonthenameof_ _py
cache__andi
t
containsmodul enameont henamef ilename. cpython-310.
pyc.
Exampl es:
--
--
--
---
---
--
---
-
__pycache_ _
--
---
--
---
--------
---
--
---
--
--
---
----
---
---
aop.cpat hon- 310.pyc <- -
--
--
--
--
--
---
--
--ModuleName
mat hsinf o. cpython-310. pyc<--
--
--
---
--
--
-ModuleName
-
--
---
--
---
------
-----
--
---
--
--
---
----
---
--
--
PROGRAM:
#Thispr ogram cal sum subandmul oft wonumber s
#aop.py -
-Fil
eName- -andt reat edas modul ename
defaddop( a,
b) :
c=a+b
print("sum( {}
,{}
)={ }".format(a,b,c))
defsubop( a,
b) :
c=a- b
print("sub({},
{})
={ }".format (
a,b,c))
defmul op( a,
b) :
c=a* b
print("mul({},
{})
={ }".format (
a,b,c))

#Thi
sprogr am acceptthreenumber sandf i
lebi
ggestamontt
hem byusi
ngmodul
es
#bi
g.py-
--f
il
enameandt reat
edasmodul ename
defbig(
):
a=int
(i
nput("EnterFirstv alue:")
)
b=int
(i
nput("EnterSecondv al
ue:")
)
c=int
(i
nput("EnterThirdv alue:
"))
i
f(a==b)and( b==c):
pr
int(
"ALLVALUESAREEQUAL: ")
el
se:
i
f(
a>b)and( a>c) :
pr
int("Biggest =",
a)
el
if
(b>c)and( b>a) :
pr
int("Biggest =",
b)
el
se:
pr
int("Biggest =",
c)

#Progr am fordispl
ayi
ngt
hecal
endarf
ory
earandmont
h
#calendarex1.py
i
mpor tcalendarasc
pri
nt(c.
mont h(2022,
4))
#Progr am fordispl
ayi
ngt
hecal
endarf
ory
ear
#calendarex2.
py
i
mpor tcalendar
print
(cal
endar.calendar
(2022))
#mat hsi
nfo.py--
-fi
lename--
treat
edasmodulename
pi=3.
14
e=2.71
k=272#her epi,e,andxarecall
edgl
obalv
ariabl
es

#SE1.
py--
Fil
eName---
someotherpr
ogr
ammer
i
mportaop
aop.
mulop(10,
20)#Funct
ioncal
l
aop.
addop(10,
20)#Funct
ioncal
l
aop.
subop(23,
45)#Funct
ioncal
l

#SE2.py--
-f
il
ename
fr
om mat hsi
nfoimpor t*
pri
nt("
valofpi="
,pi)
pri
nt("
valofe=",
e)
pri
nt("
valofk=",
k)
#stud1.py
i
mpor tbig
bi
g.big(
)#f unctioncall

Numberofappr
oachest
ore-
useModul
es

=>Weknowt hatAModul eisacollecti


onofv ari
ables,Funct
ionsandClasses.
=>Tor e-uset hefeatures(Vari
ableNames, Functi
onNamesandCl assNames)of
modul e,wehav eappr oaches.Theyar e
1)Byusi ngi mpor tstatement
2)Byusi ngf rom..
..impor tst
atement .
1)Byusi ngi mpor tstatement :
--
--
--
---
---
---
---
--
---
--
--
--
--
---
---
--
---
--
--
--
---
--
--
---
--
----
---
--
--
--
--
--
---
--
--
--
-
=>'i
mpor t'isakey word
=>Thepur poseofi mpor tstat
ementi st hat"Toreferoraccessthevari
ablenames,
functi
onnamesandcl assnamesi ncur rentprogram"
=>wecani mpor tstatementi n4way s.
=>Syntax-1: importmodul ename
--
--
--
---
---
---
---
-
=>Thissy ntaximpor tssinglemodul e
--
--
--
---
---
---
-
Exampl e: impor tbig
impor taop
i
mpor tmathsinfo
=>Syntax-2: importmodul ename1, modulename2. .
..
Modulename-n
=>Thissy ntaximpor tsmul ti
plemodul es
Exampl
e: i
mpor
tbi
g,aop,
mat
hsi
nfo

=>Syntax-3: i
mportmodul enameasal i
asname
=>Thissy nt
aximportssi
nglemodul eandal iasedwi thanothername
--
--
---
--
--
---
--
Exampl e: importbi gasb
i
mportaopasa
i
mpor tmat hsinfoasm
=>Syntax-4:
impor tmodul ename1asal i
asname, modul ename2asal i
asname. ..
..
.modul
e
=>Thissy nt
aximportsmult
iplemodul esandal iasedwithanothernames
--
--
---
--
--
---
--
Exampl e: importbi gasb, aopasa, mat hsi
nfoasm
Henceaf teri
mporti
ngallt
hev ari
ablenames, Funct i
onnamesandcl assnamesby
using"i
mpor tst
atement",wemustaccessv ariablenames, Funct
ionnamesand
cl
assnamesw. r.
tModuleNamesoral iasnames.
Modul eName. Var i
ableName
Modul eName. Funct i
onName
Modul eName. ClassName
(
OR)
AliasName. VariableName
AliasName. FunctionName
AliasName. ClassName

2)Byusi
ngf
rom.
..
.impor
tst
atement
.

=>Here" form"" i
mpor t"aret
hekeywor ds
=>Thepur poseoff rom...
.impor tst
atementi st hat"Toreferoraccessthev
ari
abl
e
names, funct i
onnamesandcl assnamesi ncur rentprogr
am"
=>wecanf rom. .
..i
mpor tst
atementin3way s.
--
--
--
---
---
--
----
-
Syntax-1: f
rom modulenamei mpor tVar i
ableNames, Funct
ionNames,
Cl assNames
=>Thissy ntaxi mportstheVariableNames, Funct i
onNames, ClassNamesofa
modul e.
Exampl e: f rom calendarimpor tmonth
from aopi mportaddop,subop,mul op
from mathinfoimpor tpi ,
e

Synt
ax-2: f r
om modulenamei mportVariabl
eNamesasal i
asname,Funct
ion
Namesasal i
asname, Cl
assNamesasal iasnames.
=>Thi
ssyntaximport
stheVariabl
eNames, Funct
ionNames,ClassNamesofa
modulewit
haliasNames
Example: from cal
endarimportmont hasm
fr
om aopimportaddopasa,subopass, mulopasm
f
rom mathinf
oi mportpiasp,eask

Syntax-3: f
rom modul
enamei
mpor
t*
-
--
---
---
--
---
-
=>Thi
ssy nt
aximport
sALLVar i
ableNames,Funct
ionNames,ClassNamesofa
module.
=>Thi
ssy nt
axisnotr
ecommendedt ousebecausei ti
mport
srequir
edFeat
uresof
Moduleandalsoimportun-
int
erest
edfeat
uresalsoimpor
tedandleadsmoremain
memor yspace.

Exampl
e: f
rom cal
endarimport*
f
rom aopimpor
t*
fr
om mathsi
nfoi
mpor
t*

=>Henceafteri
mport
ingallt
hevar
iablenames,
Functi
onnamesandclassnamesby
usi
ng" f
rom .
..
.i
mpor
tstatement
",wemustaccessv ar
iabl
enames,
Functi
onnames
andclassnamesDir
ectly
wit
houtusing Modul
eNamesoral iasnames.

VariableName
FunctionName
ClassName

=>Hencewith"i
mportstat
ement "wecangiveali
asnameformodulenamesonlybut
notforVari
abl
esNames, Functi
onNamesandCl assNames.Whereaswith"
from .
..
i
mpor tst
atement"wecanaliasnamesforVari
ablesNames,
Funct
ionNamesand
ClassNamesbutnotforModul eName.

#Progr am fordispl
ayi
ngthecal
endarf
ory
earandmont
h
#calendarex1.py
i
mpor tcalendarasc,aopasa
pri
nt(c.
mont h(2022,
4))
pri
nt(c.
mont h(2022,
5))
pri
nt(c.
mont h(2022,
6))

a.
addop( 100,200)
#Progr am f ordisplay
ingthecal
endarf
ory
ear
#calendar ex2.py
i
mpor tcal endar
pri
nt(calendar .
calendar(
2022))

#Progr am f ordispl
ayi
ngthecal
endarf
ory
earandmont
h
#calendar ex3.py
fr
om cal endari mportmonthasm
fr
om aopi mpor t*
fr
om mat hsinfoimportpiasp
pri
nt(m( 2022,4))
pri
nt(m( 2022,5))
pri
nt(m( 2022,6))
addop(10, 15)
subop(100, 200)
mulop(20, 30)
pr
int
("
val
ofpi
=",
p)

#cit
y1.py--
-fi
l
enameandt reat
edasmodul ename
defhello(s):
pri
nt(
"Hi {
},GoodMorning:
".
format(
s))
#cit
y2.py--
fi
lrname- -
actsasmodulename
defhello(s):
pri
nt(
"Hello{}
,GoodEvening".
for
mat(s)
)
#cit
ydemo. py--
mai nprogr
am
fr
om city2impor thell
oase
fr
om city1impor thell
oasm
m("Rossum" )
e("
Rit
che" )

#writ
epy thonprogr am whi chwi llgeneratemulti
pli
cati
ontabl
eforagi
vennumber
byusingmodul esconcept
#mul t
able.py-
--
--f
ilenameandmodul ename
deftable()
:
n=int
(i
nput ("Enteranumber :
")
)
i
f(n<=0):
print(
"{}isinvali
di nput"
.format
(n))
el
se:
print(
"="*50)
print(
"Mul Tablef or{}"
.format(
n))
print(
"="*50)
fori i
nr ange(1,11):
pri
nt("
\t{}x{}={}"
.f
ormat(n,
i
,n*i
))
else:
pri
nt("
="*50)
#mul t
abledemo. py -
--mainpr ogram
from multableimpor tt
abl e
tabl
e()

r
eloadi
ngamodul
esi
nPy
thon

=>Torel
oadamodul
einpy
thon,weuseapre-defi
nedfunct
ioncal
l
edrel
oad()
,whi
ch
i
spresenti
nimpmodul
eanditwasdepr
ecat
edi nfav
ourofimport
li
bmodule.
=>Sy
ntax:
-imp.
rel
oad(
modul
ename)
(OR)
importl
ib.
reload(
modul ename)--
--
-r
ecommended
--
--
---
--
--
--
--
--
--
---
--
---
---
--
--
=>Purpose/Si tuati
on:
--
--
---
--
--
--
--
--
--
---
--
---
---
--
--
-
=>rel
oad()reloadsapr evi
ouslyimportedmodule.i
fwehaveedit
edt hemodul
e
sourcefil
ebyusi nganexternaledi
torandwewantt ousethechangedval
ues/new
versi
onofpr eviouslyl
oadedmodul ethenweuser el
oad()
.

#shares.
py--
-f
il
eandtr
eatedasmodulename
defsharesi
nfo(
):
d={"
Tech":
19,
"Phar
ma":
11,
"Auto"
:1,
"Fi
nance"
:100}
ret
urnd

#mainpr ogr am
#sharesdemo. py
i
mpor tshar es
i
mpor ttime
i
mpor timpor t
li
b
defdisp(d):
print("
-"*50)
print("
\ t
ShareName\ tValue"
)
print("
-"*50)
forsn, svind.i
tems():
pri
nt(
"\t
{}\t
\t:
{}"
.f
ormat(
sn,sv))
else:
pri
nt(
"-"
*50)
#mainpr ogr am
d=shares.shar esinfo(
)#pr evi
ouslyimport
edmodul e
di
sp(d)
ti
me.sleep( 15)
i
mpor tl
ib.reload(shares)#r eloadi
ngprevi
ouslyimport
edmodul
e
d=shares.shar esinfo(
)#obt ai
ningchanged/ newval
uesofpr
evi
ousl
yimpor
t
modul e
di
sp(d)
EXAMPLE:
#shar
es.py -
--f
il
enameandact sasmodul ename
defshar esinfo():
d={ "
IT":
4,"Phamacy":2,
"Auto":
3,"
Mr kt"
:2}
returnd
#shar
esdemo. py
i
mportshar es,ti
me, i
mportl
ib
defdisp( d):
pr i
nt("
="*50)
pr i
nt("
\tShareName\ t
ShareValue:")
pr i
nt("
="*50)
forsn,svi nd.i
tems():
pri
nt(
"\t
{}\
t\t{
}".
format(sn,sv
))
pri
nt("="*50)
#mainpr ogram
d=shares.sharesi nfo(
)
di
sp(d)
pri
nt(
"iam goi ngt osl
eep")
ti
me.sl
eep( 20)
pri
nt(
"iam comi ngoutofsl eep:
")
i
mpor t
lib.r
eload( shares)
d=shares.sharesi nfo(
)
di
sp(d)

Packagei
nPy
thon
=>TheFunct i
onconcepti susedf orPer f
ormi ngsomeoper ationandpr ovidescodere
-usabi l
i
tywi thinthesamepr ogram andunabl et oprov i
decoder e-
usabilit
yacr oss
progr ams.
=>TheModul esconcepti sacol l
ectionofVar iables,Funct i
onsandcl assesandwe
canr e-uset hecodeacr ossthePr ogr amspr ov i
dedModul enameandmai nprogram
presenti nsamef olderbutunabl et oprovidecoder e-usabil
ityacrossthef olders/
drives/env ironment s.
=>ThePackageConcepti sacol l
ectionofModul es.
=>Thepur poseofPackagesi sthatt oprov i
decoder e-usabili
tyacrosst hefolders/
drives/env ironment s.
=>Todeal wi ththepackage, weneedt othelear nthef oll
owing.
a)createapackage
b)re-uset hepackage
---
--
---
---
---
--
--
----
--
--
---
---
--
---
--
--
--
--
--
---
---
---
---
--
--
--
---
--
---
---
---
--
--
---
---
--
--
---
--
a)cr eateapackage:
--
----
---
--
---
--
----
--
--
---
-
=>Tocr eateapackage, weuset hef oll
owingst eps.
i)createaFolder
ii
)place/wr it
eanempt ypy thonf i
lecalled_ _i
nit
__.
py
ii
i)place/wr i
tet hemodul e(s)int hef ol
derwher eisit
consi deredas PackageName

Example:
-
---
--
--
--
--
--
bank <-
--
--
PackageName
-
--
--
--
--
--
__i
nit_
_.py <--
--
EmptyPyt
honFi
le
si
mplei
nt.
py<---Modul
eName

========================================================
b)re-usethepackage
--
--
--
--
---
--
--
---
---
--
--
--
--
--
--
=>Tot here-usethemodulesofthepackagesacrossthefol
ders/dri
ves/
envir
onment s,wehav et
ot woapproaches.Theyar
e
i
)Byusi ngsysmodule
i
i
)byusingPYTHONPATHEnv i
ronmentalVari
ableName
-
--
---
---
--
--
--
--
--
--
--
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
i
)Byusi ngsysmodul e:
-
--
---
---
--
--
--
--
--
--
--
--
---
--
--
---
--
Syntax:
-
--
---
---
--sys.
path.append("
Absolut
ePat hofPackage"
)

=>sysispre-
def
inedmodul e
=>pathisapre-
defi
nedobject/v ar
iabl
epresentinsysmodul
e
=>append()i
spre-
definedfunct
ionpresentinpathandi
susedforl
ocat
ingt
he
packagenameofpy thon(speci
fytheabsolutepath)

Exampl
e:

sys.pat
h.append("
E:\\KVR-PYTHON- 11AM\ \ACKAGES\ \
BANK" )
(or)
sys.pat
h.append("
E:\KVR-PYTHON- 11AM\ ACKAGES\ BANK" )
(
or)
sys.pat
h.append("
E:\KVR-PYTHON- 11AM/ ACKAGES/ BANK" )
--
---
--
--
--
--
--
--
--
--
--
---
--
--
--
---
--
--
--
--
---
--
--
--
--
--
---
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
---
--
i
i)byusingPYTHONPATHEnv i
ronmentalVariabl
es:
--
---
--
--
--
--
--
--
--
--
--
---
--
--
--
---
--
--
--
--
---
--
--
--
--
--
---
--
--
--
--
--
---
=>PYTHONPATHi soneoft heEnvir
onment alVari
able
Stepsforsetti
ngPYTHONPATH=E: \KVR-PYTHON- 11AM\ PACKAGES\
BANK
--
---
--
--
--
--
--
--
--
--
--
---
--
--
--
---
--
--
--
--
---
--
--
--
--
--
---
--
--
--
--
--
---
--
--
--
--
--
--
--
-
Except
ionHandl
i
ngi
nPy
thon-
--
Mosti
mp

I
ndex:
--
--
--
--
--
-
=>PurposeofExcept ionhandl i
ng
=>Whati smeantbyExcept ion
=>Whati smeantbyExcept ionHandling
=>TypesofError
s
a)Compi l
eTimeEr rors
b)Logi calErr
ors
c)Runt imeEr r
or
=>TypeofExceptions
a)Pr e-
defined(or)bui
lt-
inexcepti
ons
b)Pr ogrammer (or
)User( or
)Custom Def
inedexcept
ion
=>keywordsusedi nexcept ionhandling
1)t ry
2)except
3)el se
4)f i
nal l
y
5)r aise
=>SyntaxforHandlingExcept ions
=>ProgrammingExampl es
=>DevelopmentofPr ogr ammer -Defi
nedExceptions
=>ProgrammingExampl es
=>ATM UseCasewi thExcept ions.

Except
ionHandl
i
ngi
nPy
thon-
--
Mosti
mp

=>Thepur poseofExcept i
onhandl ingi sthat"ToDev el
oporBui ldRobust(
Strong)
Applicati
ons" .
=>InReal Time, Todev el
opanypr ojectorappl i
cati
on,weneedt ochooseal anguage.
=>Byusi ngt hi
slanguage, wedev elop, compileandrun/execut etheprogr
ams.
Duringpr ocess,wegetVar i
ouser rorsandt heyareof3t ypes.
1)Compi leTimeEr rors
2)LogicEr r
ors
3)RuntimeEr rors.
--
--
--
----
--
--
----
--
--
--
--
--
--
--
--
----
--
--
--
---
--
---
--
----
---
--
--
--
--
--
---
--
--
--
--
--
--
--
--
---
--
--
--
--
---
--
--
--
--
1)Compi l
eTi meErrors:
--
--
---
--
---
----
----
--
-------
--
---
---
-
=>Compi l
eTi meEr rorsar ethose, whi char eoccur ri
ngdur ingCompi l
ation
Process( .py -
--
>. py c)
=>Compi l
eTi meEr rorsoccur sduet oSy nt
axesnotf oll
owedandt heyar etraced
Python
Compi ler .
=>Compi l
eTi meEr rorssol vedbyPy thonPr ogrammer satpr ojectdev elopmentl evel
.
--
--
---
--
---
----
----
--
-------
--
---
---
--
--
---
---
--
---
---
--
---
- -
--
---
--
----
-
2)Logi cEr rors:
--
--
---
--
---
----
----
--
-------
--
---
---
--
--
---
---
--
---
---
--
---
- -
--
---
--
----
=>Logi cEr rorsar ethosewhi char eoccur ri
ngdur ingExecut ionTi me/RunTi me.
=>Logi cEr rorsar ethosewhi char eoccur ri
ngduet oWr ongr epr esentationoflogic.
=>Logi cEr rorsal waysgi vesWr ongr esul tsandt heymustbesol vedbyPy thon
Programmer s
duringpr oj
ectdev elopmentl ev el
.
--
--
---
--
---
----
----
--
-------
--
---
---
--
--
---
---
--
---
---
--
---
- -
--
---
--
----
--
---
--
--
--
---
---
--
----
--
-----
--
--
---
-
3)Runt imeEr ror s:
--
--
---
--
---
----
----
--
-------
--
---
---
--
--
---
---
--
---
---
--
---
- -
--
---
--
----
=>Runt i
meEr r orsar et hosewhi char eoccur ringduringExecut i
onTi me/RunTi me.
=>Runt i
meEr ror saret hosewhi char eoccur r i
ngduet oI NVALI DorWRONGI NPUT
enteredby
Appl i
cat i
onUserorEndUser s.
=>Runt i
meer rorsar eaddr essedbyPr ogr ammer swi t
ht heirFor ecastingKnowl edge
bystudy i
ng
thepr obl em st atement
--
--
---
--
---
----
----
--
-------
--
---
---
--
--
---
---
--
---
---
--
---
- -
--
---
--
----
--
---
--
--
--
---
---
--
----
--
-----
--
--
---
--
----
--
--
---
--
--
Pointst ober emember edinExcept ionHandl i
ng
--
--
---
--
---
----
----
--
-------
--
---
---
--
--
---
---
--
---
---
--
---
- -
--
---
--
----
--
---
--
--
--
---
---
--
----
--
---
1)Whent heappl i
cationuserent ersInv ali
dorWr ongI nputt henwegetRunt ime
Err
ors.
2)Runt imeEr ror sbydef aultgivesTechni cal Err
orMessages, whi char e
underst anabl eby
Progr ammer sbutnotbyend- users.I ndust r
yal waysrecommendst ogi v
esUser -
Fri
endl yEr rorMessagesi nsteadofTechni cal Er
rorMessages.

3)Defini
tionofexcept ion:RuntimeEr r
orsofaPr ogram arecalledExcepti
ons.
(
InvalidInput-
-->RuntimeEr r
or--
--
>exception).HenceEv er
yInval
idInputgiv
es
Except i
on.
4)Except ionsbydef aultgeneratestechnicalErr
ormessages.Pr ogrammat i
call
y,
Program can
convertTechni calEr r
orMessagesi ntoUser -
FriendlyErrorMessages.
--
--
---
--
---
--
----
--
--
--
--
--
---
---
--
---
--
---
--
--
--
--
5)Def i
niti
onofExcept ionHandling:
--
--
---
--
---
--
----
--
--
--
--
--
---
---
--
---
--
---
--
--
--
--
=>ThePr ocessofConv ert
ingtechnicalerr
ormessagesi ntoUser -
Fri
endlyErr
or
Messagesi s
call
edExcept i
onHandl i
ng.
6)Whenanexcept ionoccur sinpy t
hon, I
nter
nally3stepst akesautomat i
call
y.
a)PVM st opsthepr ogram execut i
onabnormally.
b)PVM comesoutoft hePr ogram flow
c)PVM gener atesbydefaul
tTechnicalErr
orMessages.
7)Todo( a)
,(
b)and( c)steps, PVM cr eatesanobjectofanappr opri
ateexcepti
on
cl
ass
8)Whenanexcept ionoccur sthenPVM cr eatesanobjectofappropri
ateexcepti
on
cl
assandbydef aultgeneratesTechni cal Er
rorMessages.
9)Henceeveryexcept i
oni sonet heobjectofappropriat
eexcept i
onclass.
NOTE:
==>I
nvali
dInput
--Gives---
->Exception--
MakesPVM- --
>cerat
eobjectofexception
cl
ass--
andgenerates->technicalerrormessages.

Ty
pesofExcept
ionsi
nPy
thon

=>I
nPy
thonPr
ogr
ammi
ng,wehavetwotypesexcept
ions.Theyare
1)Pr
e-def
inedorbui
l
t-i
nexceti
ons
2)Pr
ogrammeroruserorcustom defi
nedexcept
ions.

1)Pre-defi
nedorbui l
t-i
nexcet ions:
--
--
--
--
--
---
--
--
---
--
--
--
--
--
---
---
--
---
--
---
---
----
=>Theseexcept i
onsar edev elopedbyLanguageDev eloper sandt heyar eav ai
labl
ein
PythonAPI sanbtheyar ealway susedf ordeal i
ngwi thUni versalProblems.
=>Someoft heUniversalProblemsar e
1)div i
sionbyzer opr oblems(Zer oDivi
sionError)
2)Inv ali
dNumberf or mats(Val ueError
)
3)Inv ali
dnumberv aluespassi ng( TypeError)
4)Inv ali
dIndices( IndexEr r
or)
5)Inv ali
dat tr
ibutesusedi npr ogram (Attri
buteError)
6)Inv ali
dmodul enamesi mpor ti
ng( Modul eNotFoundEr r
or)
....
...
..
..
...
..
..
..
...
..
...
...
.etc
--
--
--
--
--
---
--
--
---
--
--
--
--
--
---
---
--
---
--
---
---
----
--
--
--
---
----
--
--
----
--
2)Programmeroruserorcust om def i
nedexcept i
ons.
--
--
--
--
--
---
--
--
---
--
--
--
--
--
---
---
--
---
--
---
---
----
--
--
--
---
----
--
--
----
--
=>Theseexcept i
onsdev elopedbyPy thonPr ogr ammer sandt heyar eav ai
lablein
PythonProjectandusedbyot herpy t
honpr ogr ammer sandt heyareal way susedfor
deali
ngwi t
hCommonPr oblems.
=>Someoft heCommonPr oblemsar e
1)At t
empt ingt oenterI nvalidPI N.
2)At t
empt ingI nvali
dUsernameorPasswor d
3)At t
empt ingt owi t
hdr awmor eamountt hanav ai
lablebal ance.
4)Attemptingt or epresentI nvalidPattern..
.etc
Handl
i
ngt
heExcept
ionsi
nPy
thon

=>Handl
ingtheExceptionsinPythoni
nnothingbutconv
ert
ingTechnicalEr
ror
MessagesintoUser-Fr
iendl
yErrorMessages.
=>Todot hi
sprocess,I
nPy t
honPr ogr
ammi ng,wehave5keywords.Theyare
1)tr
y
2)except
3)el
se
4)fi
nall
y
5)r
aise

Handl
i
ngt
heExcept
ionsi
nPy
thon

=>Handlingt heExcept ionsi nPy t


honinnothingbutconv
ert
ingTechnicalEr
ror
Messagesi ntoUser -
FriendlyEr rorMessages.
=>Todot hisprocess, I
nPy thonPr ogrammi ng,wehave5keywords.Theyare
1)try
2)except
3)else
4)finally
5)raise
--
--
--
---
--
--
----
--
---
--
--
--
---
---
--
---
----
---
--
----
--
--
SyntaxforHandl ingt heexcept ions:
--
--
--
---
--
--
----
--
---
--
--
--
---
---
--
---
----
---
--
----
--
--
try:
BlockofSt atement s
generatingexcept ions
except<except i
oncl assname- 1>:
Blockofst atement sgenerates
User -
FriendlyEr rorMessages.
except<except i
oncl assname- 2>:
Blockofst atement sgenerates
User -
FriendlyEr rorMessages.
--
---
--
--
---
--
--
---
---
---
---
--
---
-----
--
--
--
--
--
-
--
---
--
--
---
--
--
---
---
---
---
--
---
-----
--
--
--
--
--
-
except<except i
oncl assname- n>:
Blockofst atement sgenerates
User -
FriendlyEr rorMessages.
else:
Blockofst atement srecommeded
togener ateResul t
s
fi
nally:
Blockofst atement sexecutedby
PVM Compul sor i
ly.

#program f orcaldivi
si
onoft wonumber
s
#Div1.py
s1=input("EnterFir
stValue:")
s2=input("EnterSecondVal ue:"
)
a=i
nt (
s1)#- -
--
---
--
--
--
--
--
--
--
---
--
X
b=int(
s2)#- --
---
--
--
--
--
--
--
--
---
--
X
c=a/b#- -
----
--
---
--
--
--
--
--
--
--
--
---
X
pri
nt("
v alofa=" ,
a)
pri
nt("
v alofb=" ,
b)
pri
nt("
Di v
=" ,
c)
#program forcal divisi
onoft wonumber s
#Div2.
py
tr
y:
print
("\nIam t r yBlock")
s1=input( "\nEnt erFir
stValue:"
)
s2=input( "EnterSecondVal ue:
")
a=int(
s1) #- -
---
---
---
--
--
---
--
--
--
--
X
b=int(
s2)#- ---
---
---
--
--
---
--
--
--
--
X
c=a/b#- -----
---
---
---
--
--
--
---
--
--
--
X
exceptZeroDivisi
onEr ror:
print
("\nDON' TENTERZEROFORDEN. .
."
)
exceptValueError:
print
("\nDON' TENTERst r
s/sy mbol
s/alpha-
numer
icst
rs"
)
el
se:
print
("-
---
--elsebl ock--
--
")
print
("val ofa=" ,a)
print
("val ofb=" ,b)
print
("Div=" ,
c)
fi
nall
y:
print
("\niam f inallyblock")

Expl
anat
ionf
ort
hekey
wor
dsofexcept
ionhandl
i
ng

1.try:
--
---
---
---
---
--
-
=>Itist heblockinwhichwebl ockofst atement sgeneratingexcepti
ons.I
nOt her
wor ds, whatare
allthestatementsgener atesexcept i
ons, suchstatement smustbewr it
tenwithin
tryblockandhencet ryblocki scall
edexcept ionmoniteringblock.
=>Whenanexcept i
onoccur sintryblockthenPVM comesoutoft r
yblockand
execut es
appr opri
ateexceptblockandgener atesUser -
Fri
endlyer r
ormessages.
=>Af terexecuti
ngappr opriateexceptblock,PVM Nev ergoest ot r
yblocktoexecute
restoft he
statement sintr
yblock
=>Ev erytryblockmustbei mmedi atelyfol
lowedbyexceptbl ock.
=>Ev erytryblockmustcont ai
natleastoneexceptbl ockandr ecommendedt owr it
e
mul ti
ple
exceptbl ocksforgener ati
ngmul tipl
euser-fri
nedlyerrormessages.

2.exceptbl
ock:
=>Thisist
heblock,
Inwhi
chwewr
it
ebl
ockofst
atement
sforgener
ati
ngUser
-
Fri
endlyErr
or
Messages.I not herwordsexceptblocksupressesTechnical er
rormessagesand
generatesUser-Fr
iendlyErrorMessagesandhenceexcepti sbl ockiscal
led
Excepti
onPr ocessingBlock.
Note:-Handli
ngExcxept ion=tr
yblock+exceptblock
=>exceptblockwillexecutewhenanexcept ionoccursintr
ybl ock.
=>Evenwewr i
temul ti
pleexceptblocks,PVM wil
lexecuteonlyoneexceptblock
dependst y
peof
excepti
onoccur sintryblock.
=>exceptblockmustbewr i
tt
enaf t
ertrybl
ockandbef or
eelsebl ock(ifwewrit
eelse
bl
ock)

3.el
sebl ock:
=>Thisist hebl
ock,inwhichwewr i
teblockofstat
ementsrecommededtogener
ate
Resultof
program.
=>el
sebl ockwillexecut
ewhent hereisnoexcepti
onoccursint
rybl
ock.
=>Wr i
ti
ngel sebl
ocki sopti
onal
.
=>el
sebl ockmustbewr i
ttenaf
terexceptbl
ockandbeforefi
nal
lybl
ock(
ifwewri
te)
.

4.finall
yblock:
=>Itisthebl ockinwhichwewr i
teblockofstatementsandtheyar
er el
i
nqui
shi
ng
(Cl
ose/r el
ease/
giv e-
up/cl ean-
up)theresour
ces(fil
es,database)whi
chareobt
ainedint
rybl
ock
=>finall
yblockwi l
lexecut
ecompul sori
ly(
ifwewr ite)
=>Wr i
ti
ngfinall
yblockisopti
onal
=>finall
yblockmustbewr it
tenaft
erelseblock.
5.r
ai sekeywor d

=>rai
sekeywor disusedf
orhitt
ing/raisi
ng/generati
ngtheexcept
ionpr
ovi
ded
somecondi t
ionmustbesatisfi
ed.
=>Syntax:
- i f(
TestCond):
r
aise <except
ion-
class-
name>

Examples:
--
--
--
--
--
--
--
---
--
fr
om kvrimpor tKvr
Divisi
onErr
or
defdivi
sion(a,
b):
if(
b==0):
r
aiseKv r
Divi
sionEr
ror
else:
r
eturn(a/b)

Var
iousf
ormsofexceptbl
ocks

=>Theexceptblockcanbei nvari
ousforms.Theyare
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
-
Form-1:Thisform handl
esoneexceptionatat i
me
-
--
---
---
--
--
--
--
--
--
--
--
--
--
--
---
--
--
---
--
--
--
--
---
--
--
---
--
---
--
--
--
---
Syntax:
- t ry:
-
--
---
--
--
--
---
--
--
--
--
---
--
--
--
--
--
---
--
--
--
--
---
--
except<exception-cl
ass-name-
1>:
---
--
--
--
--
---
--
--
--
--
--
--
--
--
--
---
---
--
---
-
except<exception-cl
ass-name-
2>:
---
--
--
--
--
---
--
--
--
--
--
--
--
--
--
---
---
--
---
-
except<exception-cl
ass-name-
n>:
---
--
--
--
--
---
--
--
--
--
--
--
--
--
--
---
---
--
---
-
EXAMPLE:
#div
2.py
tr
y:
s1=i
nput
("
Ent
erf
ir
stv
alue:
")
s2=input
("Entersecondv al
ue:"
)
a=i
nt (
s1)#--
--
--x
b=int(
s2)#--
--
---
x
c=a/b#--
---
--
--
--x
exceptZeroDivisi
onError
:
pri
nt("
Dontent erzerofordenominat
or.
..
..
."
)
exceptValueError:
pri
nt("
Dontent erstr
/symbol/al
phanumeri
cv al
ue.
..
..
."
)

--
--
--
---
--
--
--
--
----
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
Form-2: Thisform handl
esmul ti
plespecif
icexcepti
onsatatimeandthi
sf eat
urei
s
call
edmul tiexcepti
onhandlingblock
--
--
--
---
--
--
--
--
----
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
Syntax:
- t ry:
-
--
--
---
--
--
--
--
--
--
--
--
--
-
--
--
---
--
--
--
--
--
--
--
--
--
except(excepti
onclassname- 1,excepti
onclassname-
2,.
.excepti
on
cl
assname- n):
-
---
--
--
--
--
--
--
--
--
--
--
---
--
-
---
--
--
--
--
--
--
--
--
--
--
---
-
-
---
--
--
--
--
--
--
--
--
--
--
---
--

EXAMPLE:
#div3.py
tr
y:
s1=input
("
Enterfi
rstval
ue:
")
s2=input
("
Entersecondval
ue:"
)
a=int(
s1)
#--
--
--x
b=int(
s2)
#--
--
---
x
c=a/b#- -
--
---
--
--x
except(ZeroDivisionEr r
or,
ValueError
):
pri
nt("\nDontent erzer ofordenomi nat
or..
..
..
")
pri
nt("Dontent erst r/
symbol /
alphanumer i
cvalue.
..
..
."
)
el
se:
pri
nt("Valueofdi vident:",
a)
pri
nt("Valueofdi visor:"
,b)
pri
nt("{}
/{}={
}".f
or mat (
a,b,
c))
fi
nall
y:
pri
nt("\n\nIam i nfinal
lyblock.
...
..
..
..
")
else:
pri
nt("Valueofdi vident:",
a)
pri
nt("Valueofdi visor:"
,b)
pri
nt("{}
/{}={
}".f
or mat (
a,b,
c))

Form-3:Thisform di
splaysTechErrormessage(Problem Name)generateddueto
excepti
on
occur
ence
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-

Sy
ntax:
- try:
--
--
---
--
--
--
--
--
--
--
--
---
--
--
--
--
--
---
--
---
---
--
---
except<excepti
on-class-name-1>asal
iasname:
-
--
--
--
--
--
---
---
--
---
--
--
---
---
--
--
---
--
--
-
except<excepti
on-class-name-2>asali
asname:
-
--
--
--
--
--
---
---
--
---
--
--
---
---
--
--
---
--
--
-
except<except i
on-cl
ass-name- n>asal
i
asname:
-
--
--
--
--
--
---
---
--
---
--
--
---
---
--
--
---
--
--
-

#div4.py
tr
y:
s1=input ("Enterfi
rstval
ue:"
)
s2=input ("Entersecondvalue:
")
a=int(s1) #--
--
--x
b=int(s2) #--
--
---
x
c=a/ b#-----
--
--
--x
exceptZer oDivisi
onErrorasz:
pri
nt (z)
exceptVal ueErrorasv :
pri
nt (v)
el
se:
pri
nt ("Valueofdi vi
dent:
",
a)
pri
nt ("Valueofdi vi
sor:
",
b)
pri
nt ("{}
/{}={}
".f
ormat(a,
b,c)
)
For
m-4:Thi
sfor
m deal
swi
thdef
aul
texceptbl
ock.
#div5.py
tr
y:
s1=input (
"Enterfi
rstvalue:"
)
s2=input (
"Entersecondv alue:
")
a=int(s1)#--
--
--x
b=int(s2)#--
--
---
x
c=a/ b#--
---
--
--
--x
except:
pri
nt ("
Ooop'ssomet hi
ingwentwr ong.
..
..
.!
!!
")
el
se:
pri
nt ("
Valueofdi vi
dent:",
a)
pri
nt ("
Valueofdi vi
sor:"
,b)
pri
nt ("
{}/
{}={}
".f
ormat (
a,b,
c))

Dev
elopmentofPr
ogr
ammer
-Def
inedExcept
ions
=>Theseexcept
ionsdevelopedbyPy thonProgr ammersandtheyareavai
l
ablein
PythonProj
ectandusedbyot herpyt
honpr ogrammersandt heyar
ealwaysusedfor
deali
ngwithCommonPr obl
ems.
=>Someoft heCommonPr oblemsare
1)Att
empt i
ngt oent
erInvalidPIN.
2)Att
empt i
ngInvali
dUsernameorPasswor d
3)Att
empt i
ngt owit
hdrawmor eamountthanavai
labl
ebalance.
4)At
temptingtorepresentInvali
dPat
ter
n..
.etc

=>ToDev el
oppr ogr
ammer -
defi
nedexcepti
ons,wemustfoll
owt hefol
l
owingst
eps
Step-
1:Chooset heProgr
ammer _def
inedCl
assName
Step-
2:ThePr ogrammer-
defi
nedclassmustinher
itf
rom ei
therExcept
ionor
BaseExcepti
on(Her eExcepti
onorBaseExceti
onarecal
ledbaseclassesi
n
excepti
onhandling)
Examples: classKv rDi
visi
onError
(Excepti
on):pass
cl
assPi nErr
or(BaseExcepti
on):
pass
--
--
--
--
--
--
--
--
--
--
--
---
---
--
--
--
--
--
--
---
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
-

Hence,Todev el
opanyprogrammer -def
inedexcepti
onsbasedapplicat
ions,
wemust
ensurethatther
eexist3phases.Theyare
1)DevelopmentofProgrammer -
defi
nedExceptionsubclass
2)DevelopmentaFuncti
onwhi chwillhi
tprogr
ammer -def
inedexcepti
on
3)developmentofmainprogram forhandl
ingtheexcepti
on.

r
aisekeywor
d

=>rai
sekeywor disusedf
orhitt
ing/raisi
ng/generati
ngtheexcept
ionpr
ovi
ded
somecondi t
ionmustbesatisfi
ed.
=>Syntax:
- i f(
TestCond):
r
aise <except
ion-
class-
name>

Examples:
--
--
--
--
--
--
--
---
--
fr
om kvrimpor tKvr
Divisi
onErr
or
defdivi
sion(a,
b):
if(
b==0):
r
aiseKv r
Divi
sionEr
ror
else:
r
eturn(a/b)

EXCEPTIONSEXAMPLES:
#Thi
sprogr am defi
nedProgrammerdefinedexcept
ionandworksl
ike
Zer
oDivi
sionError
#kvr
.py-
--
fil
enameandact sasModuleName
# (1) (2)
cl
assKv rDivi
sionEr
ror
(Excepti
on):
pass
#Phase-
1: DevelopmentofProgrammer-def
inedExcept
ionsubcl
ass

#ThisPr ogram acceptt wov al


uesfrom mainpr
ogram andcomputesthei
rdivi
sion
#div
op. py--
--
--
fi
lenameandact sasmodulename
fr
om kv rimportKv rDi
visionErr
or
defdi visi
on(a,b):
i
f (
b==0):
raiseKv r
Divisi
onErr
or#Hi tt
ingorgener
atingorr
aisi
nganexception
whencondi ssat i
sfi
ed.
else:
return(a/b)
#Phase- 2:Dev elopmentofFunct ionwhichwil
lhitpr
ogr ammer
-defi
nedexcepti
on
wit
hr ai
sekey wor d
#Thispr ogram accept st wof r
om KBD( enduser
)andgetsther
esul
t
#divdemo. py
fr
om div opimpor tdivi
si on
fr
om kv rimpor tKvrDivisionErrorasKS
tr
y:
a=int(input("EnterVal ueofa: "
))
b=int(input("EnterVal ueofb: "
))
result=di vi
sion(a,b)#Funct ioncall
exceptKS:
print(
"\ nDon'tent erzerof orden..
."
)
exceptVal ueEr ror:
print(
"\ nDon'tent erstrs/alpha-numeri
cs/
symbols"
)
except:
print(
"Somet hi
ngwentwr ong!")
el
se:
print(
"Di v=",
result)
fi
nall
y:
print(
"Iam f rom f inal
lyblock")

#Phase-
3:dev
elopmentofmai
npr
ogr
am f
orhandl
i
ngt
heexcept
ion(
tryandexcept
bl
ocks)

#Thispr ogr
am accept st wof rom KBD( enduser
)andgetsther
esul
t
#divdemo1. py
fr
om div opimpor tdivi
si on
fr
om kv rimpor tKv r
DivisionError
tr
y:
a=int(i
nput (
"EnterVal ueofa: "
))
b=int(i
nput (
"EnterVal ueofb: "
))
result
=di vi
sion(a,b)#Funct ioncall
except(Kv r
Div i
sionErr
or, ValueError
):
print
("\nDon'tent erzer oforden..
."
)
print
("\nDon'tent erstrs/alpha-numeri
cs/
symbols"
)
except:
print
("Somet hi
ngwentwr ong!")
el
se:
print
("Div=",
result)
fi
nall
y:
print
("Iam from f inal
lyblock")
#Sample.
py
cl
assKv rDi
vi
si
onEr
ror
(Except
ion)
:pass#Dev
elopmentofPr
ogr
ammer
-def
ined
Except
ionsubcl
ass

defdi vision( a,b):#Dev elopmentaFunct i


onwhichwillhitprogrammer -
defi
ned
excepti
on
i
f(b==0) :
raiseKv r
Div i
sionError#Hi t
ti
ngorgeneratingorr aisi
nganexcepti
on
whencondi ssat i
sfied.
else:
return( a/b)
#mainpr ogram- --
--dev elopmentofmai nprogram f
orhandl i
ngt heexcept
ion.
tr
y:
a=i nt(input("EnterVal ueofa: ")
)
b=i nt(input("EnterVal ueofb: ")
)
resul t=div i
sion(a,b)#Funct i
oncal l
exceptKv rDivisionError:
print (
"\ nDon'tent erzer oforden..."
)
exceptVal ueEr ror:
print (
"\ nDon'tent erst r
s/al pha-numerics/sy
mbol s")
el
se:
print (
"Di v=",
result)
fi
nall
y:
print (
"Iam f rom f inal
lyblock")

EXAMPLE-
2

GENARATETABLEOFGI
VENNUMBER…………….
.

#Phase-1: dev el
opmentofpr ogr ammer -
defi
nedexcept
ions
#excepts.py---
f i
l
enameandact sasmodul ename
cl
assNegat i
v eEr r
or(Excepti
on):pass
cl
assZer oEr r
or (BaseException):pass
Phase-2:dev elopmentofFUNCTI ONfedisplay
ingr
esul
tandhi
tt
ingexcept
ions
#multable.py---f
ilenameandact sasmodul ename
fr
om except si mpor tNegativeError,
ZeroErr
or
deft able(n):
i
f(n==0) :
raiseZer oEr
ror
el
if(n<0) :
raiseNegat i
veError
el
se:
print(
"-
"*40)
print(
"Mul Tablefor{ }
".
format(
n))
print(
"-
"*40)
fori i
nr ange(1,11):
print(
"\t
{}x{}={ }"
.for
mat(n,
i
,n*i
))
pr i
nt("-
"*40)
#Phase- 3: dev elopmentofmai nprogram whichwil
lhandl
etheexcept
ions
#multabl edemo. py
fr
om mul tablei mpor ttabl
e
fr
om except si mpor tNegat i
veErr
or,ZeroErr
or
tr
y:
n=i nt(i
nput (
"Enteranumber :
"))
tabl e(n)
exceptVal ueEr ror:
print (
"\nDon' tent erstr
s/alpha- numeri
cs/sy
mbols"
)
exceptNegat i
v eError:
print (
"\nDon' tent er-v
enumber s")
exceptZer oError :
print (
"\nDon' tent erZero:"
)
FI
LE

Fil
esinPython
(OR)
St
ream Handl
inginPyt
hon

I
ndex:
--
--
---
---
=>Pur poseofFi l
es
=>TypesofAppl i
cations
a)Non- Per sistantAppl icati
ons
b)Per sistantAppl icat i
ons
=>Def i
nitionofFi l
es
=>Oper ationsonFi les
a)Wr iteOper ati
ons
b)ReadOper ati
ons
=>TypesofFi l
es
a)TextFi l
es
b)Binar yFi l
es
=>Synt axf oropeningt heFi les
a)ByUsi ngOpen( )
b)Byusi ng"wi t
hopen( )"
=>Fil
eOpeni ngModes
1)r
2)w
3)a
4)r+
5)w+
6)a+
7)x
=>Funct ionf orwrit
ingt hedat at ot heFi l
es
a)wr i
te()
b)wr i
teline()
=>Funct ionf orReadingt hedat atot heFiles
a)read( )
b)read( no.ofchar s)
c)readl i
ne( )
d)readl i
nes( )
=>Random AccessFi l
esi nPy thon
a)tell
()
b)seek( )
=>Progr ammi ngExampl es
=>PicklingandUn- pickli
ngConcept
(ObjectSerial
izat i
onandDe- seri
ali
zati
on)
=>"pickle"modul e
=>Progr ammi ngExampl es
=>"os"modul e
=>Progr ammi ngExampl es
Fil
esinPython
(OR)
St
ream Handl
inginPyt
hon

=>ThepurposeofFi
lesconcepti
sthat"Tost
orethedat
aPermanently"
.
=>Theprocessofst
ori
ngthedatapermanent
lyi
sknownas"Persi
stency"
.

=->I
nThecont extoffil
es,wecandev el
opt wotypesofappli
cati
ons.Theyar
e
a)Non-persi
stencyAppli
cati
ons
b)Persi
stentAppli
cati
ons.
=>InNon-persi
stencyApplicati
ondevelopment,weacceptthedatafr
om Key
board,
stor
esi nmai nmemor yintheform ofobj
ects,
processthedataandshownt
he
resul
tontheconsol e.
=>Theresult
swhi chareav ail
abl
einthemai nmemor yar
eTempor ary.

=>InpersistentApplicati
ondevelopment ,weacceptthedatafrom Keyboard,stores
i
nmai nmemor yinthef or
m ofobjects,processthedat
aandwhoser esult
sare
storedpermanent l
y.
=>Tost orether esul
tofanyprogr ammingl anguagepermanently
,wehav etwo
approaches.t heyare
a)ByusingFiles
b)Byusingdat abasesof twares.
=>Not ethatifwewr i
teanypythonprogr ammi ngbyusi
ngFilesandDat abase
softwarest hensucht y
peofappl i
cati
onsar ecomesundert heexampl ePersi
stent
Applicati
ons.

Per
sist
entAppl
i
cat
iondev
elopmentbyusi
ngFi
l
esi
nPy
thon

=>Fil
eConcepti
sonelanguageIndependentwherewecanstor
ethedat
a
permanent
ly.
=>Thecommunicat
ionbetweenPy t
honPr ogr
am andFi
lesi
scomesunder
devel
opmentofPer
sistantAppl
i
cation.
=>Def
ini
ti
onofFi
l
es:

=>AFileisacoll
ect
ionofRecords
=>AFil
eNamei soneoft heNamedLocationinSecondar
yMemor y.
=>Fi
lesofanyprogr
ammi ngresi
desinSecondaryMemory.
=>I
nFilesProgr
ammi ng,
Ev er
yObjectDat
abecomesar ecordinafi
l
eofsecondar
y
memor yandeveryr
ecordoffil
eofsedondarymemor ywi
llbecomeanobj
ectinmain
memor y.

Def
ini
ti
onofSt
ream:
--
--
--
--
--
--
---
--
--
--
--
--
--
--
-
=>Theflowofdat abet
weenmai
nmemor
yandf
il
eofsecondar
ymemor
yiscal
l
ed
Str
eam.

Oper
ati
onsonFi
l
es

=>Ont hefi
les,wecanper form TwoTy pesofOperations.Theyare
1)Wr i
teOper ation.
2)ReadOper ation.
1)Wr i
teOper at
ion:
=>Thepur poseofwr i
teoper ationi sthat"Tot ransferorsav etheobjectdat
aof
mainmemor yasr ecordint hef il
eofsecondar ymemor y".
=>Steps:
1)Chooset heFi l
eName
2)Opent heFi leNamei nWrit
eMode
3)Perform cy cleofWr it
eOperati
ons.
=>Whileweper formingwr iteoper ati
ons, wegetthef oll
owingexceptions.
a)I OEr r
or
b)OSEr ror
c)Fi l
eExi stError
2)ReadOper ati
on:
=>Thepur poseofr eadoper ati
oni sthat"Tot r
ansferorr eadtherecordfrom f
il
eof
secondarymemor yint
ot heobj ectofmai nmeor y"
.
=>Steps
a)Chooset hef ilename
b)Opent hef i
lenamei nReadMode
c)Perform cy cleofr eadoperati
ons.
=>Whileweper formingreadoper ations, wegetthefollowingexcepti
ons.
a)Fil
eNot FoundEr r
or
b)EOFEr ror
Fi
l
eOpeni
ngModesi
nPy
thon

=>Toopenthefi
l
e,wemustspeci
fyt
ypeoff
il
emodeandt
heyar
ecl
assi
edi
nto7
ty
pes.Theyar
e

1)rmode
=>Thi
smodeisusedforopeningthefi
lei
nREADMode.
=>Thi
sisoneofdef
aultmode.
=>I
fweopenanyfil
enamei n"r"modeandift
hatf
il
edoesnotexi
stsi
nsecondar
y
memorywegetFil
eNotFoundErr
or.

2)w mode
=>Thi
smodeisusedf orcr
eati
nganewfil
eandopensinwri
temodealways.
=>I
fthefi
l
enamealreadyexist
sandifweopeniti
n"w"modetheni
topensin
wri
temodeandexisti
ngdataov
erl
apswithnewdata.

3)amode
=>Thi
smodeisusedforopeni
ngnewfil
eandperf
ormswri
teoper
ati
on.
=>Thi
smodecanalsobeusedforopeni
ngexi
sti
ngfi
lei
nwrit
emodeandnew
datawi
ll
beappendedtotheexi
sti
ngdat
a.

4)r+mode
=>Thismodeisusedforopeningthefil
einr
eadmode.
=>Whenweopent hefil
enamei n"r
+"modethenonthatf
il
e(i
ffi
leexi
sts)wecan
perf
orm Fi
rstr
eadoperati
onandlaterweperf
orm Wr
it
eOperati
on.

5)w+mode
=>Thi
sismodei
susedopeni
ngt
hef
il
eal
way
sinwr
it
emode,
Fir
stper
for
msWr
it
e
oper
ationandl
aterwecanperfor
m ReadOperati
on.
=>Notethatw+modeFuncti
onali
tyi
ssimilart
o"w"modebutwi
tht
hismode
addi
ti
onall
ywecanperfor
mr eadoperat
ion.

6)a+mode
=>=>Thi
smodei susedf oropeningnewf i
l
eandper f
ormswr i
teoperat
ion.
=>Thismodecanal sobeusedf oropeni
ngexist i
ngfil
einwritemodeandnew
datawil
l beappendedt otheexisti
ngdata.
=>Addit
ionall
ywiththismodewecanper form ReadOper at
ion.(
Fir
stweperfor
m
Writ
eOper ati
onandl aterweper f
ormreadoper ati
on)

7)xmode
=>Thi
smodeisexcl
usiv
elyisusedforopeni
ngorcreati
ngthefi
l
einwr
it
emode.
=>Thi
smodeopensanyfil
einwrit
emodeonl yonce.
=>I
fweopenexi
ti
ngfi
lein"x"modethenwegetFi l
eExi
stEr
ror

#Thisprogram opens" kv r.
data"inr eadmode
#Fil
eOpenEx1.py
tr
y:
fp=open( "kvr.
dat a")#Her ef pisanobjectofTextIOWr
apper
exceptFil
eNotFoundEr ror:
pri
nt("
Fi l
edoesnotexi sts")
el
se:
pri
nt("
\nFi leOpenedi nr eadmodesuccessf ull
y")
pri
nt("
Ty peoff p=",ty
pe( fp))
pri
nt("
-"*40)
pri
nt("
Fi l
eMode=" ,
fp.mode)
pri
nt("
isr eadabl e?=",f
p.readabl e()
)
pri
nt("
iswr i
teable? =",
fp.writabl
e())
pri
nt("
Isf il
eCl osed=" ,
fp.closed)
pri
nt("
-"*40)
fi
nall
y:
pri
nt("
i am f r
om f inall
ybl ock")
fp.
close( )#manual Closingoff il
es
pri
nt("
Isf il
eCl osedi nf i
nallyblock=",
fp.
closed)
#Thisprogram opens" kv r.
data"inwr i
temode
#Fil
eOpenEx2.py
kv=open("
kvr.
dat a","
w")
pri
nt(
"\nFil
eCr eatedSuccessf ull
yi nwr it
emode:")
pri
nt(
"Typeofkv =" ,
type(kv )
)

Ty
pesofFi
l
es

=>I
nPy
thonPr
ogr
ammi
ng,wehav etwotypesofFi
l
es.Theyar
e
a)TextFil
es
b)Binar
yFiles
1)TextFil
e:
=>ATextFilealwayscont ai
nsAl phabet
s,Digi
tsandSpeci
alSy
mbol
s.
=>TextFi
lesalway sdenotedbyal ett
er"t"
=>Thedefaultfi
leinpythonistextfi
le.
--
--
--
--
--
--
--
--
--
---
--
--
--
---
--
--
--
---
--
--
--
--
--
--
---
-
Examples: .py .
java .c . cpp . t
xt .doc.
..
.et
c

2)Bi
naryFil
e:
=>ABinar
yFil
eal
wayscont
ainsDat
ainBinar
yFor
mat(Pi
xl
es)
=>Bi
naryFi
lesal
way
sdenotedbyalet
ter"b"

Exampl
es: i
mages(
.j
pg,
.j
peg,.
png,
.gi
f)
audi
oandvideofi
l
es
PDFdocuments

openi
ngt
heFi
l
es

=>Toperf
ormv ar
iousoperati
onsonf i
les,Fi
rstwemustopenthefi
le.I
nPyt
hon,
we
have2syntaxest
oopent hefil
e.Theyar e
1)byusing "open()"
2)byusing "wi t
hopen( )"
1)byusi
ng "open()":
=>open(
)isoneofthepre-def
inedfuncti
onandi tpr
esenti
ndefaul
tmodul
ebuil
ti
ns
=>Thi
sfuncti
onisusedforopeninganyspeci f
iedfi
l
einspeci
fi
edfi
lemode.

=>Sy
ntax:
- v
arname=open(
"Fi
l
eName"
,"
Fil
eMode"
)

Explanati
on:
=>varnameisanobj ectofText
IOWr apperandi ti
spointi
ngtothefi
l
eanditiscal
l
ed
Fi
lepoi nt
er.
=>Fil
eNamer epr
esent sTypeoffi
le
=>Fil
eModecanbeei therofr,w,a,r+,w+,a+,
x
=>Onceweopent hefil
ewithopen(), t
heni ti
smandat or
ytoclosef
il
ebyusing
cl
ose( )anditisoneoft hemanual process.(Notsupport
ingAutoCl
oseabl
ePropert
y)
EXAMPLES:

#Thisprogram opens"kvr.
dat a"i
nreadmode
#Fil
eOpenEx1.py
tr
y:
fp=open("
kvr.
data")#Her efpi
sanobjectofText
IOWr
apper
exceptFil
eNotFoundError:
pri
nt("
Fil
edoesnotexi st
s")
el
se:
pri
nt("
\nFil
eOpenedi nreadmodesuccessful
l
y")
pri
nt("
Typeoff p=",
type(fp)
)
pr
int
("
-"
*40)
pr
int
("
Fil
eMode=" ,
fp.
mode)
pr
int
("
isreadable?=",
fp.r
eadable(
))
pr
int
("
iswriteable?="
,f
p.writ
able(
))
pr
int
("
Isfil
eCl osed=",
fp.
closed)
pr
int
("
-"
*40)
f
inal
l
y:
pri
nt("
i am from fi
nal
lybl ock"
)
fp.
close( )#manual Cl osingoffi
les
pri
nt("
Isf i
leClosedinf i
nallybl
ock=",
fp.
closed)
#Thisprogram opens" kvr.
data"inwr i
temode
#Fil
eOpenEx2.py
kv=open("
kvr.
dat a",
"w")
pri
nt(
"\nFil
eCr eatedSuccessf ull
yi nwri
temode:")
pri
nt(
"Typeofkv =",t
ype(kv)
)

2)byusi ng "wi thopen( )"


Syntax: wi t
h open( "
Fil
eName" ,"Fil
eMode" )as<v ari
ablename>:
--
---
--
----
--
---
---
---
--
----
--
---
--
--
--
--
--
--
---
---
--
--
---
--
--
--
--
--
---
--
---
--
----
--
---
---
---
--
----
--
---
--
--
--
--
--
--
---
---
--
--
---
--
--
--
--
--
---
Blockofst atement --Fi
leOperations
--
---
--
----
--
---
---
---
--
----
--
---
--
--
--
--
--
--
---
---
--
--
---
--
--
--
--
--
---
--
---
--
----
--
---
---
---
--
----
--
---
--
--
--
--
--
--
---
---
--
--
---
--
--
--
--
--
----
Explanation:
=>here" with"and" as"ar ethekey wor ds
=>open( )ispr e-defi
nedFunct ionusedf oropeninganyspeci fi
edf il
einspecif
iedfi
le
mode.
=>varnamei sanobj ectofText I
OWr apperandi ti
spoi nti
ngtot hefil
eandi ti
scall
ed
Fi
lepoi nter.
=>Blockofst atement sr epresentssetofexecut ablestatement smeantf or
perf
or mingf i
l
e
oper ati
ons.
=>Theadv antangeof"wi t
hopen( )as"appr oachi sthat"Asl ongasPVM pr esent
i
nsideof" withopen( )as"i ndent ation, Fi
leisacti
v el
yUnderopeni ngst at
eandOnce
PVM comesoutof" withopen( )as"I ndentati
ont henf i
l
ewi l
lbecl osedautomati
call
y.
=>Thisappr oachpr ovidesaut o-closeabl eoffi
les.(Noneedt owr it
ef i
nal
lybl
ockand
noneedt ousecl ose()).
EXAMPLES:

#Thisprogr
am demonstart
esv ari
ousf il
eopeningmodeswi
th"
wit
hopen(
)as"as
approach
#Fil
eOpenEx3.
py
tr
y:
wit
hopen("
hyd.i
nfo",
"r
+")asf p:
pri
nt(
"-"
*50)
pri
nt(
"Nameoff i
le=",f
p.name)
pri
nt(
"Fil
eMode=" ,
fp.mode)
pri
nt(
"i
sf i
lereadable=",f
p.r
eadabl
e()
)
pri
nt(
"i
sf i
lewr i
etable=",
fp.
wri
tabl
e()
)
print
("I
sf i
l
eclosedinwi
thopen(
)=",
fp.cl
osed)
print
("-
"*50)
exceptFi
leNotFoundError:
pri
nt(
"Fil
edoesnotexi sts"
)
el
se:
pri
nt(
"Isfi
leclosedinwithopen(
)inel
seblock=",
fp.
closed)

#Thisprogram demonst art


esv ariousfil
eopeningmodeswi
th"
wit
hopen(
)as"as
approach
#Fil
eOpenEx4. py
wit
hopen( "hyd.i
nfo",
"a+")asf p:
print
("-"
*50)
print
("Nameoff il
e=",fp.name)
print
("Fil
eMode=" ,
fp.mode)
print
("isfi
lereadable=" ,f
p. r
eadable(
))
print
("isfi
lewr i
etable=" ,
fp.wri
table(
))
print
("Isfi
leclosedi nwi thopen( )="
,f
p.cl
osed)
print
("-"
*50)
pri
nt("
\niam outofwi t
hopen( )i ndentati
on:")
pri
nt("
Isfi
leclosedi nwithopen( )=",
fp.
closed)

#Thisprogram demonst art


esv ari
ousf ileopeni ngmodeswi t
h"wit
hopen(
)as"as
approach
#Fil
eOpenEx5.py
tr
y:
withopen("hyd1.i
nfo","
x")asf p:
print(
"-"
*50)
print(
"Nameoff il
e=",fp.name)
print(
"Fil
eMode=" ,
fp.mode)
print(
"i
sf i
lereadable=" ,
fp.readable(
))
print(
"i
sf i
lewr i
etable=",fp.
wr i
table(
))
print(
"I
sf i
leclosedi nwi thopen( )
=",fp.cl
osed)
print(
"-"
*50)
exceptFil
eExi
stsErr
or :
pri
nt(
"Fil
eal r
eadyexi st
s--i
tcan' tcreateagain" )
el
se:
pri
nt(
"\niam outofwi t
hopen( )indentati
on--elseblock:
")
pri
nt(
"Isfi
leclosedi nwithopen( )="
,fp.
closed)
Wr
it
ingt
hedat
atot
hef
il
e
=>Towr i
tet hedat at ot hef il
e,wehav etwopr e-
defi
nedfuncti
ons.Theyar e
1)wr i
te()
2)wr i
teli
nes()
1)wr i
te()
=>Thisf unctioni susedf orwr i
ti
nganyt y
peofdat atothefi
leinthef orm ofst
r.
=>Syntax: - f i
lepoint er.write(
data)
=>fi
lepointerisav alidv ar i
ablenameandi ti
salwayspointi
ngtot hef i
l
e.
=>datar epresent sanyt ypeofv alueandi tmustbeintheform ofst ralways.
Exampl e:
#Thispr ogram demonst arteshowwr i
teaddressofvari
ouspeopl ebyusi ngwri
te(
)
#Fil
eWr iteEx1.py
wit
hopen( "addr 1.data" ,
"a")asf p:
fp.wr i
te("Denni sRi tche\n")
fp.wr i
te("5-4,Mount ai
nsi de\n")
fp.wr i
te("Bell Labs\ n")
fp.wr i
te("USA\ n")
print("
\nDat aWr it
tentot hefil
e--
plzveri
fy:
")

2)wr i
teli
nes()
=>Thisf uncti
onisusedf orwrit
inganytypeofIterabl
eobj
ectdatai
ntheform ofst
r.
=>Syntax:- f i
l
epointer
.wri
tel
ines(dat
a)
=>fi
lepointerisav al
idvari
ablenameandi tisalwayspoi
nti
ngtothefi
le.
=>datar epresentsanytypeofIterabl
eobjectanditmustbeinthef
orm ofst
ralways.
Exampl e:
#Thi sprogram demonst rateshowwr i
teaddr essofv ar
iouspeoplebyusing
wr i
teli
nes()
#FileWriteEx2.py
d={"Name" :
"Rossum" ,"
HNO" :
"3-4-Hil
lSide",
"Cname":"PSF","
countr
y":
"NetherLands"
}
wi t
hopen( "
addr 2.dat a",
"a")asf p:
fp.writeli
nes( "
\n"+st r
(d))
pr i
nt("
\nDat aWr i
ttent othefil
e--pl
zv eri
fy:
")
#Thi sprogram demonst rateshowwr i
tethedat adynami call
ytothefi
lebyreading
from KBD.
#FileWriteEx3.py
fname=i nput (
"Ent ert hefil
enamet owr it
ethedat a:
")
wi t
hopen( f
name, "a")asf p:
pr i
nt("
Ent ert hedat aandpr ess'@' tostop:"
)
whi l
e(Tr ue) :
kbddat a=input (
)
if(kbddat a==" @"):
break
el se:
fp.writ
e(kbddata+"\n")
print(
"Dat awr it
tent ot hefil
e--
verif
y")
Readi
ngt
hedat
afr
om t
hef
il
e

=>Toreadt hedat
afrom f
iles, wehav e4pr e-definedf
uncti
ons.Theyare
a)r ead()
b)r ead(no.ofchars)
c)r eadli
ne()
d)r eadli
nes()
a)read():
=>ThisFuncti
onisusedforr eadingent i
recont entoffi
lei
ntheform ofst
r
=>Syntax:- v ar
name=filepoi nt
er.
read()
=>Herev ar
nameisoftypest randi tcontai
nst heent i
recont
entoffi
le.

b)read(no.ofchars)
:
=>ThisFuncti
onisusedf orreadi
ngspecif
iednumbercharact
ersf
rom t
hefi
leint
he
for
m ofst r
=>Syntax:- v arname=fil
epoint
er.
read(
no.ofchars)
=>Herev ar
namei softy
pest randitcont
ainsthespeci
fi
ednumberchar
act
ers

c)readli
ne()
:
=>ThisFuncti
onisusedforreadi
ngOneLi neatati
mefrom t
hefi
leint
heform ofst
r
=>Syntax:- v ar
name=fil
epoint
er.
readl
ine()
=>Herev ar
nameisoftypestranditcont
ainstheoneLi
neofdat
afrom f
il
e.

d)readli
nes()
:
=>ThisFuncti
onisusedforreadi
ngAllLi
nesatat
imefr
om thefi
lei
nthef
orm ofl
i
st
=>Syntax:- v ar
name=fil
epoint
er.
readl
i
nes()
=>Herev ar
nameisoftypeli
standitcont
ainst
heal
lLi
nesoffi
le.

EXAMPLES:
#Thisprogram readsthecont entofanyfi
leanddi
spl
aysont
heconsol
e.-
--
-r
ead(
)
#Fil
eReadEx1.py
fname=input(
"Enterthefil
eName: ")
try
:
withopen( fname,"
r")asfp:
fi
l
edata=fp.r
ead()
pri
nt("
contentoffi
le:
")
pri
nt("
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
")
pri
nt(f
il
edata)
pri
nt("
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
")
exceptFil
eNotFoundEr r
or:
pri
nt("
Filedoesnotexi st
s:"
)

#Thisprogr
am readst
hespeci
fi
ednumberchar
act
ersf
rom f
il
e--
--
--
read(
no.ofchar
s)
#Fi
leReadEx2.
py
t
ry:
withopen("
addr1.data")asf p:
pri
nt(
"I
nitialPosi t
ionoffp=",
fp.t
ell
())#0
fdat
a=fp.read( 5)
pri
nt(
"fi
ledat a=",f
data)
pri
nt(
"NowPosi ti
onoffp=",
fp.t
ell
())#5
fdat
a=fp.read( 8)
pri
nt(
"fi
ledat a=",f
data)
pri
nt(
"NowPosi ti
onoffp=",
fp.t
ell
())#13
fdat
a=fp.read( )
pri
nt(
"fi
ledat a=",f
data)
pri
nt(
"NowPosi ti
onoffp=",
fp.t
ell
())#183
fp.
seek(0)#Her efpreposit
ionedt ost
art
ingi
ndex
pri
nt(
"-
---
----
--
---
---
--
---
--
--
--
--
--
--
--
---
--
--
--
")
fdat
a=fp.read( )
pri
nt(
"fi
ledat a=",f
data)
pri
nt(
"-
---
----
--
---
---
--
---
--
--
--
--
--
--
--
---
--
--
--
")
exceptFi
leNotFoundEr
ror:
pri
nt(
"Fil
edoesnotexi sts:
")

#Thi sprogram readst heonel i


neataf rom fil
e--
--
--r
eadli
ne()
#FileReadEx3.py
tr
y:
withopen( "
addr 1.data")asf p:
fdat
a=f p.readline()
pri
nt("Fil
eDat a=",
fdata)
fdat
a=f p.readline()
pri
nt("Fil
eDat a=",
fdata)
fdat
a=f p.readline()
pri
nt("Fil
eDat a=",
fdata)
pri
nt("I
ndexoff p=",
fp.t
ell
())
exceptFi l
eNotFoundEr ror:
pri
nt("
Filedoesnotexi sts:"
)
#Thi sprogram readst heal ll
inesatat imef r
om fi
le---
--
-r
eadl
ines(
)
#FileReadEx4.py
tr
y:
withopen( "
addr 1.data")asf p:
l
ines=f p.
readl i
nes( )
pri
nt("--
--
---
----
---
---
--
--
---
--
---
--
---
--
--
--
")
pri
nt("Fil
eDat a:"
)
pri
nt("--
--
---
----
---
---
--
--
---
--
---
--
---
--
--
--
")
forl
inei nlines:
pr i
nt("{}"
.f
ormat (l
ine),
end=""
)
pri
nt("--
--
---
----
---
---
--
--
---
--
---
--
---
--
--
--
")
exceptFi l
eNotFoundEr ror:
pri
nt("
Filedoesnotexi sts:"
)
#Thi sprogram copyt hecont entofonef il
eintoanotherfil
e
#FileCopy.py
sfi
le=input("
Enterthesour ceFi l
e:")
t
ry:
withopen( sf i
le,
"r"
)asr p:
dfile=input("Ent erDest i
nationFile:")
wit hopen( dfile,"a")aswp:
sfdat a=r p.r
ead()
wp. wr it
e( sf
data)
print("\n{}Fi l
eDat aCopi edi nto{}"
.for
mat(sf
il
e,
dfi
le))
exceptFil
eNotFoundEr ror:
pri
nt("
Fil
edoesnotexi sts")
#Thisprogram acceptanyf i
lenameandf i
ndnumberofl ines,wordsandcharacter
s.
#Fil
eCountInf
o.py
fname=input(
"EnterFi leName: ")
try
:
nol=0
nw=0
nc=0
withopen( fname, "r
")asf p:
Fileli
nes=fp. readl i
nes()
forl i
nei nFilelines:
print("{}".
format(li
ne),
end=" "
)
nol=nol +1
nw=nw+l en(li
ne.spli
t()
)
nc=nc+l en(li
ne)
else:
print("\n----
--
--
--
--
---
---
--
--
--
------
--
--
--
---
--
-"
)
print("Numberofl ines=",nol)
print("Numberofwor ds=" ,nw)
print("NumberofChar act ers=",
nc)
print("--
----
--
---
--
--
--
--
---
---
--
---
----
--
--
---
-"
)
exceptFil
eNotFoundEr ror:
pri
nt("
Fil
edoesnotexi sts:")

Pickl
ingandUn-Pickl
i
nginPyt
hon
(OR)
ObjectSeri
ali
zat
ionandDeser
ial
i
zat
ion

Pickli
ng(ObjectSer i
alizati
on) :
=>Letassumet hereexi stsanobjectwit
hmul ti
plev al
uesi nmai nmemor y
.To
tr
ansferorwr it
emul tiplev al
uesofobjecti
ntot hefil
esecondar ymemor yweuse
write(
)orwriteli
nes().Thesef uncti
onsbydef aultwrit
est heobjectval
uesintheform
ofv al
uebyv alueandi ti soneofthetimeconsumi ngpr ocess.
=>Toov er
comet hispr oblem,weuset heconceptofPi ckli
ng.
=>Theadv antageofpi ckl i
ngconceptisthatTot ransferorwr i
teenti
reobj
ectcontent
ofmai nmemor yintofilesecondarymemor ywi thsinglewr i
teoperati
on.

=>Defi
nit
ionofPi
ckl
ing:
=>Theprocessoft
ransf
err
ingorwr
it
ingent
ir
eobj
ectcont
enti
ntot
hef
il
esecondar
y
memor ybyperf
ormingsingleWr it
eOperat
ioniscall
edPickl
i
ng.
=>HencePickl
i
ngconceptpar ti
cipatesi
nwr i
teOperat
ion.
=>Attheti
meofdealingwithPi ckl
ingOper
ations,
wemustensuret
hatt
hef
il
esmust
betakenas
Bi
naryfor
mat(Fil
eTy pe=Binary).

Implement ati
onofPicklingConcept:
=>importpicklemodul e
=>Createanobj ectwithcoll
ecti
onv al
ues
=>Chooset hef i
lenameandopenedi nwrit
emodeasbi nar
yfil
e
=>Usepi ckle.
dump( ).Thepurposeofdump( )i
sthatt
owr i
teortr
ansf
erent
ir
eobj
ect
contentintofil
eof
secondar ymemor y.
Syntax:- pickle.
dump( obj
ect,f
il
epoint
er)

Un-Pickl i
ng(Obj ectDe-Seri
ali
zation):
=>Letusassumet hereexist
sar ecor d(s)inaf i
leofsecondarymemor y.Toreador
transfert heent i
rerecordcontentf rom thef i
l
eofsecondar ymemor yintotheobject
ofmai nmemor ybyusingread(),read(no.ofchars),
readli
ne()andr eadli
nes()then
theset akesr eadst herecordvaluesi ntheform ofvaluebyv al
ueandt akesmor e
execut i
ont i
meandi ti
soneoft het imeconsumi ngprocess.
=>ToOv ercomet hisprobl
em, wemustuset heconceptcal l
edUn- Pickl
ing.
=>Theadv antageofun- pi
ckli
ngconcepti sthatToreadent i
rerecordcont entata
ti
mef rom f i
leofsecondar ymemor yintoobjectofmai nmemor ybyper formi
ng
singler eadoper ati
on.

=>Defini
tionofUn- Pickl
ing:
=>Thepr ocessr eadingort r
ansfer
ringtheent
irerecordcontentatati
mef r
om fi
leof
secondarymemor y
i
ntoobj ectofmai nmemor ybyper f
ormi
ngsinglereadoper at
ioni
scall
edUn-
Pickli
ng.
=>HenceUn- Pickl
ingconceptpar t
icipat
esinReadOper at
ion.
=>Atthet imeofdeal ingwithUn-Pickli
ngOperati
ons,wemustensur ethatthef
il
es
mustbet akenas
Binaryformat (Fil
eTy pe=Binar
y) .

=>I
mpl ementati
onofUn- Pickl
ing:
=>I
mpor tpicklemodule
=>ChooseFi l
eNameandopeni ti
ntoReadModeasBi nar
yFormat
=>useload()ofpicklemodule.Thepurposeofl
oad()i
sthatt
otransf
erent
ir
erecor
d
contentf
rom fil
eofsecondar ymemor yi
ntoobj
ectofmainmemor y.
Syntax:pi ckl
e.l
oad(fi
lepoi
nter
)
#Program f oracceptingnoofst udent sdet ail
ssuchasst dno,stdname, marksand
col
legenameandsav et hem inaf ile( usepi ckling)
#st
udpi ckex1.py
i
mpor tpickle
wit
hopen( "
py t
hstud.data","ab" )asf p:
nos=int(
input("Enterhowmanyst udent suhav e:"
))
i
f(nos<=0) :
pri
nt("I
nv al
idi nput :")
el
se:
foriinrange( 1,
nos+1) :
print ("
-"*50)
print ("
Ent er{ }St udentI nformat i
on:"
.format(i
))
print ("
-"*50)
#acceptst udentv alues
stno=i nt(input (
"Ent erSt udentNumber :"
))
sname=i nput ("
Ent erSt udentName: ")
mar ks=float (i
nput ("Ent erSt udentMar ks:
"))
cname=i nput ("
Ent erSt udentCol l
egeName: "
)
#cr eat eanobj ect
lst=list()#cr eateanempt yli
st
#appendst udentdat a
lst.
append( st no)
lst.
append( sname)
lst.
append( mar ks)
lst.
append( cname)
#wr iteobj ectdat at ot hef il
e
pickl e.dump( l
st,fp)
print ("
-"*50)
print ("
{}St udentdat asav edsuccessf ull
yinFil
e".
for
mat(i
))

#Program readingtherecord(s)f
rom t hefi
le( useun-pickl
i
ng)
#studunpick.py
i
mpor tpickle
tr
y:
wi thopen("pyt
hstud.dat
a", "
rb")asfp:
pri
nt("
-"
*50)
pri
nt("
Stno\tName\ tMarks\tCname" )
pri
nt("
-"
*50)
while(
True):
try:
record=pickle.
load(f
p)
forvalinrecor d:
pri
nt (
"{}
\t"
.f
ormat(
val
),
end="
")
print(
)
exceptEOFEr r
or:
print(
"-
"*50)
break
exceptFileNotFoundErr
or:
pr
int
("
Fil
edoesnotexi
sts:
")

#Program f oraccept i
ngnoofst udent sdet ai lssuchasst dno, stdname, marksand
coll
egenameandsav ethem i naf i
le( usepi ckl i
ng)
#studpickex2.py
i
mpor tpickle
defpi ckleexampl e():
withopen( "pyt
hstud.data","ab" )asf p:
nos=int(
input("Enterhowmanyst udent suhav e:"))
i
f(nos<=0) :
pri
nt("I
nvalidi nput :")
else:
foriinrange( 1,
nos+1) :
print ("
-"*
50)
print ("
Ent er{ }St udentI nformat ion:"
.f
ormat(i
))
print ("
-"*
50)
#acceptst udentv alues
stno=i nt(input (
"Ent erSt udentNumber :"
))
sname=i nput ("Ent erStudentName: ")
mar ks=float (
input ("EnterSt udentMar ks:
"))
cname=i nput ("Ent erStudentCol legeName: "
)
#cr eat eanobj ect
l
st =list()#cr eateanempt yli
st
#appendst udentdat a
l
st .
append( stno)
l
st .
append( sname)
l
st .
append( mar ks)
l
st .
append( cname)
#wr iteobj ectdat at othef il
e
pickl e.
dump( lst,fp)
print ("
-"*
50)
print ("
{}St udentdat asav edsuccessf ull
yin
Fi
le".
format (i
))

#mai
npr ogr
am
pi
ckl
eexample(
)

#Pr
ogram readingtherecor
d( s)from thefi
le(useun-
pickl
ing)
#st
udunpickex2.py
i
mportpickl
e
defunpickleexample(
):
try:
withopen("pythstud.dat
a","
rb")asf
p:
pr
int (
"-"
*50)
pr
int (
"Stno\tName\tMarks\
tCname")
pr
int (
"-"
*50)
while(True):
t
ry:
record=pi
ckl
e.l
oad(fp)
forvalinr
ecord:
pr
int
("
{}
\t"
.f
ormat
(val
),
end="
")
pri
nt(
)
exceptEOFErr
or:
pri
nt(
"-
"*50)
break
exceptFi
leNotFoundEr
ror
:
pri
nt(
"Fil
edoesnotexi
sts:
")

#mainprogr
am
unpi
ckl
eexampl
e()

#writeapy thonpr ogram whichwi l


lacceptempl oyeedet ail
ssuchasempl oyee
number, empl oyeename, salar
yandcompanynameandst oreempl oy eedet ail
si na
fi
lebyusi ngpickli
ngconcept
#EmpPi ck.py
i
mpor tpickle,
sys
defst r
or eempdat a():
withopen( "
emp. data",
"ab"
)asf p:
while(
True):
tr
y:
#acceptempl oy eedetail
s
print("-
"*50)
eno=i nt(i
nput ("
Ent erEmpl oyeeNumber :"
))
ename=i nput ("
Ent erEmpl oyeeName: ")
sal=f l
oat(i
nput ("EnterEmpl oyeeSal ary :
")
)
cname=i nput (
"Ent erEmpl oyeeCompany :"
)
#cr eateanempt yl i
st
lst=[]
#appendt heempl oyeedat a
lst.
append( eno)
lst.
append( ename)
lst.
append( sal)
lst.
append( cname)
#wr iteorsav eent ir
eobjectdatat oFi le--
--
dump( )
ofpickl
emodul e
pickle.dump( l
st,
f p)
print("-
"*50)
print("Empl oyeeRecor dSav edi
naf ile:"
)
print("-
"*50)
ch=i nput("
Douwantt oinsertanotherEmpl oyee
Record(yes/no):
")
if(
ch. l
ower ()=="no" )
:
sys.exit()
exceptValueEr ror:
print("Don'tenterst rs/
sysmbol s/alpha- numer ics
fornumberandsal :
")

#mainpr
ogram
st
ror
eempdata(
)
#Program forreadingal l
therecor dsf r
om f il
ebyusi ngun-pickl
ing
#empunpi ck.py
i
mpor tpickle
tr
y:
wi thopen("emp.data",
"rb")asf p:
print
("-"
*50)
print
("EmployeeDet ai
ls")
print
("-"
*50)
whi l
e(True):
try
:
empr ecord=pi
ckle.l
oad(fp)# empr ecor
dvarof
<cl
ass,'l
i
st '
>
forv alinempr ecord:
pri
nt(
"{}\
t".
for
mat (
val)
,end="
")
print()
exceptEOFEr ror:
print("-
"*50)
break
exceptFileNotFoundError:
pr i
nt("
Fil
edoesnotexi sts")

osmodul
e
=>"os"i
soneofpr e-definedmodul e
=>Thepurposeof' os'modul eist hat"Toper for
m cerat
inOsLev
elOper
ati
ons"
=>TheessentialOsLev el Operationsar e:
1)getti
ngcur rentwor kingf older( getcwd())
2)createaf ol
der(mkdi r(
))
3)createaf ol
der shierarchy (makedi rs())
4)remov eaf older(r mdi r())
5)remov eaf oldersHi erarchy(r emovedi
rs())
6)renameaf older(r ename( ))
7)l
istfi
lesinf older(l i
stdi r
())

1)getti
ngcurrentwor kingfolder:
=>Togetcurrentwor kingfolder,weuseapr
e-def
inedf
unct
ionget
cwd(
)ofos
module
=>Syntax: v
arname=os. get
cwd()
#cwdex1.py
i
mpor tos
cwdname=os. getcwd()
pri
nt(
cwdname)

2)creat eaf ol
der :
=>Tocr eateaf older,weusemkdi r(
)ofosmodul e.
=>Sy ntax:- os. mkdi r("foldername" )
=>mkdi r (
)cancr eateonef olderatatimeandi tisunablecreateFol
dersHier
archy.
=>mkdi r (
)gener ateFi l
eExi stsErr
orprovidedift hefol
deralr
eadyexist
s.
=>mkdi r (
)gener atesFi l
eNot FoundErr
orpr ovidedwhenweat temptcreat
eFolders
Hierarchy .
Exampl es:
#mkdi rex.py
i
mpor tos
tr
y:
os.mkdi r
("D:\\kiwi\mango\ guav a")
pri
nt(
"Fol dercr eatedsuccessf ully
--v
erify"
)
exceptFi leExi
stsEr ror:
pri
nt(
"Fol deralreadyexi sts"
)
exceptFi leNotFoundEr ror:
pri
nt(
"Cr eationofFol dersHierarchyisnotpossible:"
)

3)cr
eateaf ol
der
shierarchy:
=>Tocreat
eaf ol
dershierarchy,
weusemakedir
s()ofosmodul
e
=>Synt
ax:- os.
makedi rs("
fol
der
shi
erar
chy
")
=>Ift
hef oldersHi erar
chyal r
eadyexiststhenwegetFi l
eExi
stsEr
ror
.
Examples:
#Program f orcr eati
ngaf oldersHier
archy
#mkdirsex.py
i
mpor tos
tr
y:
os. makedi rs(
"D:\\
India\Hyd\
Ameer pet\
Python\Dat
aScience"
)
pr i
nt("Folderscreatedsuccessfull
y-
-ver
if
y")
exceptFileExistsError
:
pr i
nt("Folderalr
eadyexi st
s")

4)remov eafol
der:
=>Toremov eafolder,
weuser mdir(
)ofosmodul e
=>Synt
ax: os. r
mdir("
fol
dername")
=>I
ffoldernamedoesnotexiststhenwegetFileNotFoundEr
ror.
=>I
fthef ol
dercontai
nsanyfi
lesorsubfol
derthenitisnotpossi
blet
oremovefol
der
andwegetOSEr r
or.
=>rmdi
r (
)canremov eonefol
deratatimebutpossibeltoremoveFol
dersHi
erar
chy.

Exampl es:
#rmdirex.py
i
mpor tos
tr
y:
os.r
mdi r
("D:
\\hyd"
)
pri
nt("
Folderremov edsuccessf
ull
y-
-veri
fy"
)
exceptFileNotFoundError:
pri
nt("
Specifi
edFoldersdoesnotexists"
)
exceptOSEr ror
:
pri
nt("
Specifi
edFolderisnotempty--
notpossi
blet
oremov
e")

5)remov eaf oldersHi erarchy :


=>Tor emov eaf oldersHi erarchy, weuser emov edirs()ofosmodul e
=>Syntax:- os. remov edirs("f
older sHierarchy")
=>Iff
older sHierarchydoesnotexi ststhenwegetFi l
eNot FoundError.
=>Ift
hef olderhier ar
chycont ainsanyf ilesorsubf olderthenitisnotpossi
blet
o
removef oldershierachyandwegetOSEr ror.
Exampl es:
#remov emdi r
ex.py
i
mpor tos
try
:
os.r
emov edirs( "
D: \\I
ndia/Hy d\Ameer pet/Py t
hon/ dj
ango")
pri
nt("
FoldersHi erarhcyr emov edsuccessf ul
ly--
veri
fy"
)
exceptFileNotFoundEr ror :
pri
nt("
Speci f
iedFol dersdoesnotexi sts")
exceptOSEr ror:
pri
nt("
Speci f
iedFol dersisnotempt y
--notpossi bl
et oremov e"
)
6)renameaf older:
=>Torenameaf older, weuser ename( )ofosmodul e
=>Syntax:os. rename( "exi sti
ngf oldername" ,"NewFol dername" )
=>Ifexi
sti
ngf oldernamedoesnotexi ststhenwegetFil
eNot
FoundEr
ror
.
Examples:
#renamedirex.py
i
mpor tos
tr
y:
os.rename( "
c:\\mango"
,"
c:\\
india"
)
pri
nt (
"Folderrenamedsuccessf ul
ly-
-ver
if
y")
exceptFil
eNot FoundError:
pri
nt (
"Foldersdoesnotexist
s")

7)listfilesinf older :
=>Tol istt hef i
lesinf older, weusel istdi
r()ofosmodule
=>Sy ntax:-l istobj=os.listdi
r("f
oldername" )
=>ifthe" f
oldername"doesnotexi ststhenwegetFi l
eNotFoundEr
ror
Exampl es:
#Progr am f orl isti
ngf il
es
#li
st f
il
es. py
i
mpor tos
tr
y:
foldername=i nput (
"EnterFolderName: "
)
li
stfil
es=os. li
stdir(f
oldername)
pr i
nt("-"
*50)
pr i
nt("Numberoff i
lein'{}
'folder={}"
.f
ormat
(fol
dername,l
en(
li
stf
il
es)
))
pr i
nt("-"
*50)
forfilenamei nl i
stf
iles:
print("
\ t
{}"
.format(f
ilename) )
pr i
nt("-"
*50)
exceptFi l
eNot FoundEr ror:
pr i
nt("Foldersdoesnotexi sts:")

#Program forr emov i


ngaf older
#rmdirex
.py
i
mpor tos
tr
y:
os.rmdi r
("D:
\\hyd"
)
pri
nt("Folderremov edsuccessf
ull
y-
-veri
fy"
)
exceptFil
eNotFoundEr ror:
pri
nt("Specifi
edFoldersdoesnotexists"
)
exceptOSEr r
or:
pri
nt("Specifi
edFolderisnotempty--
notpossi
blet
oremov
e")

#Program f
orsear
chi
ngf
orf
il
es
#searchf
il
e.py
i
mpor tos
t
ry:
foldername=i nput (
"EnterFolderName: "
)
l
istfil
es=os.li
stdir(fol
dername)
print("
-"
*50)
print("
Numberoff i
lein'{}
'folder
={}
".f
ormat (
fol
dername,l
en(li
stfi
les)
))
print("
-"
*50)
forf i
l
enamei nl i
stfil
es:
print
( "
\ t
{}"
.format(f
il
ename) )
print("
-"
*50)
fname=i nput("Enterf i
lenamet osearch:"
)
i
f( fnamei nli
st fi
les):
print
( "
{}f i
l
eexi stsin{}"
.f
ormat(fname,folder
name))
else:
print
( "
{}f i
l
edoesnotexi stsin{}
".f
ormat(fname,f
oldername))
exceptFi
leNot FoundEr ror:
print("
Foldersdoesnotexi sts:"
)

Communi
cat
ionbet
weenPy
thonandOr
acl
eDat
aBase
=>st
epsf
ordev
elopi
ngapy
thonpr
ogr
am f
orcommuni
cat
ingwi
thOr
acl
edat
abase:

1.i
mpor tcx_Oracl
e
2.PythonProgr
am mustgett heconnect
ionf
rom Or
acl
eDataBase.
3.Createanobj
ectofCursor.
4.DesigntheQuery
,PlacetheQueryinanobj
ectofCur
sorandexecut
e.
5.PythonProgr
am ProcesstheResult
6.PythonProgr
am Closestheconnecti
on.

Expl
anat
ion:
1.i
mportcx _Or
acl
e

=>I
fpythonPr ogr
am wantstocommunicat
ewithOracl
edatabasethenmustimpor
t
corr
espondingcx_Oracl
emoduleanditmustbeinstal
l
edbyusingpiptool
=>Exampl e: impor
tcx_ Or
acl
e
=>Oncet hemodulei
si mpor
tedthenPy
thonProgr
ammerr eadytouseVari
abl
e
Names, Funct
ionNamesandCl assNames.

2.Pyt
honProgr
am mustgettheconnect
ionfr
om OracleDat
aBase.
=>I
faPythonProgr
am want
st oper
form someoper
ationsonOr
acledat
abaset
hen
Fir
stwemustgetConnect i
onf r
om or acledat abase.
=>IfaPy t
honPr ogram want sgetconnect i
onf r
om Or acledat abaset henwemust
useconnect ()ofcx_Or acl emodul e.
Syntax:- varname=cx_ Or acle.connect ("Connect i
onur l
")
=>Var namei sanobj ectof<cl ass, '
cx_Or acl e.connect i
on">
=>cx_ Oracleispre-definedt hirdpar t
ymodul eusedt ocommuni catewi t
hOr acle
Database.
=>connect ()isoneoft hepr e-def i
nedf unct ionpr esenti ncx_ Or aclemodul eandi tis
usedt ogett heconnect ionf rom Or acleDat abase.
=>TheGener al f
ormatofConnect ionUr lis" User Name/ Passwor d@DNS/ servi
ceid"
(OR)
=>TheGener al f
ormatofConnect ionUr lis
"User Name/ Passwor d@I PAddr ess/ servi
ceid"
=>Her e"username"r epr esent sUserNameofOr acleDat abase( Ex:scott)
=>Her e"passwor d"r epr esent spasswor dofOr acl eDat abase( Ex: ti
ger)
=>hereDNS( Domai nNami ngSer v i
ce)r epr esent sNameofMachi ne,whereOr acle
Databasesof twareinst alled.Thedef aultDNSofev erycomput eri s"local
host"
=>Her eIPAddr ess(Inter netPr otocol Addr ess)r epresent sAddr essofamachi ne
whereOr acleDatabasei nstal l
ed.Thedef aultIPAddr essofev erycomput eris
"127.0.0.1"(
LoopBackAddr ess)
=>hereser viceidrepresent sonwhatnameOr acledat abasei si nstal
led(or)alias
nameOr acleDat abasei nt hecur r
entwor kingmachi ne.
=>OnceConnect i
onURLi swr ongt henwegetDat abaseEr rorofcx_ Oracleandwe
handlet hatexcept i
on.
=>Tof indser vi
ceidofOr acl eDat abaseofanymachi ne, gotoSQLPr ompt .

ORacl
eEnv
iroment
:
SQL>sel
ect*f
rom gl
obal
_name;

OUTPUT
-
--
--
--
--
--
--
--
GLOBAL_NAME
-
--
--
--
--
--
--
--
--
--
--
--
--
--
ORCL<---
--
Servi
ceId
-
--
--
--
--
--
--
--
--
--
--
--
--
--
Pyt
honProgrammi ngEnv:
i
mportcx_Oracle
kvr
=cx_Oracle.
connect
("scot
t/t
iger
@localhost/or
cl"
)
(OR)
kvr
=cx_Oracle.
connect
("scot
t/t
iger
@127.0.0.1/or
cl"
)
pri
nt("
PythonProgram gotconnect
ionfr
om Or acl
eDB")

3.Creat
eanobj
ectofCur
sor.
=>Herecur
sori
sapre-
defi
nedcl
asspr
esenti
ncx_
Oracl
emodul
e.
=>Thepur poseofcr eatinganobj ectofcur soristhat"Tocar r
ytheQueryfr
om
PythonPr ogr am t oDat abase, QueryExecut edinDat abase, Quer
yresul
tplacedby
Databasei nt heobj ectofcur sorandcur sorgivesr esultoft
hequerytothePy t
hon
Program" .
=>Henceanobj ectofcur soractsasdr i
verbet weenPy thonprogr
am andDatabase
Software.
=>Programmat i
call
y,tocr eat
eanobj ectofcur sor,wemustusecur sor
()whichis
presentinconnect i
onobj ect.
Syntax:
- v ar name=conobj .
cursor()
=>herev arnamei sanobj ectof<cl ass,'cx_Oracle.cursor'>

4.DesigntheQuer y,PlacetheQuer yinanobjectofCur


sorandexecut
e.
=>AQuer yisrequest/Quest ion/statementtothedatabasef
rom PythonProgr
am
forperfomingcertai
nDat abaseOper ati
ons.
=>Toexecut etheQuer yfrom PythonProgram,wemustuseexecute()
, whi
chis
presentincursorobject.
=>Syntax:- varname=cur sorobj.
execut
e("
Quer y
")
=>HereQuer ycanbeEi t
herDDLorDMLorDRL

Py
thonDat
aBaseCommuni
cat
ion(
PDBC)

=>Evenweachi evedt heDat aPersi


stencywit
hFil
esconcept,wehavethefol
lowi
ng
l
imitat
ions.
1.Fil
esConceptofanyl anguagedoesnotcont ai
nsecuri
tybcozfi
les
conceptdoesnotcont ainusernamesandpasswor ds.
2.Toextractorpr ocesst hedatafrom fi
l
esisverycomplexbcozFil
esdat
a
mustal way spr ocessedwi thI
ndices.
3.Thedat aoft hef i
lesdoesnotcont ainCol
umnNamesandVer ycomplexto
Process/Quer yt hedata
4.Fil
esar eunabl etostor elar
geVolumeofDat a.
5.TheAr chit
ect ureofFilesChangesf r
om OneOSt oanotherOS
(OR)Fi lesareDependentonOS.

=>ToOvercometheli
mitati
onsofFi
l
es,wemustusetheconceptofDat
aBase
Soft
waresWhicharepurelyRDBMSProduct
s(Or
acl
e,MySQL,MongoDB,SQLI
TE3,
DB2,SQLSERVER..
..
..
..
..
.)

=>WhenweDataBaseSof
twar
eforachev
ingt
hedat
aper
sist
ency
,wegett
he
fol
l
owingadv
antages.

1.Dat
aBasesof
twar
ear
eFul
l
ySecur
edbecauset
heypr
ovi
desUserName
and
passwor
d
2.ToProcessorExt
ractorQuer
yingthedatafrom DataBaseSoft
warei
s
ver
y easybcozthedat
apresenti
ntabl
esofDat abasesoftwarearequal
if
iedwi
th
Col
umnNames.
3.DataBaseSoft
wareareablet
ost or
elargeVolumeofDat a.
4.DataBaseSoft
wareareInDepeendentfrom OS.

=>IfPythonPr ogr am wantt ocommuni catewithAnyDat abaseSof twarePr oduct


thenwemustusepr e-defi
nedmodulesandsuchpr e-def
inedmodul esar enot
presentinPy thonLi brary
.SothatPythonProgrammermustget/I nstallthepre-
definedmodul esofDat abaseSoft
war ebyusingat oolcall
edpi p.
=>ToMakeanyPy thonPr ogr
am tocommuni catewi t
hanydat abasesof t
war ethen
wemusti nst
al lat hirdpartymodulewhichisrelatedDatabasesof tware.
=>ForExampl e, Tocommuni cat
ewi t
hOr acl
eDat abase,wemusti nstal
l cx_Oracle
Modul e,Tocommuni catewit
hMy SQLdat abase, wemusti nstall
my sql-
connector..
..
.et candt heymustbeinstal
ledexplici
tl
ybyusi ngpi ptool

=>Sy
ntax: pi
pinst
allmodul
ename

=>her
epiptoolpr
esenti
nthefoll
owingfolder
"C:
\User
s\nar
eshi
t\AppDat
a\Local
\Programs\Py
thon\
Pyt
hon310\
Scr
ipt
s"

=>I
fwegetaner
roras"pi
pisnotr
ecogni
zedi
nter
nal
command"t
hensett
hepat
h
asfol
l
ows

C:\
Users\nar
eshit
>set
path="
C:\
Users\nareshi
t\
AppDat
a\Local
\Pr
ogr
ams\
Pyt
hon\
Pyt
hon310\
Scr
ipt
s"

Example: int
sallcx_Or
acl
e
-
---
--
--
--
--
--
pi
pi nstal
lcx_Or
acl
e

Exampl
e: i
nst
allmy
sql
-connect
or

pi
pi nstal
lmy sql-connect
or
#Thisprogram testtheconnect ionwi thOracl
e
#Testcon1.py
i
mpor tcx_Oracl
e
tr
y:
con=cx_ Oracle.connect(
" scott
/ti
ger
@local
host/or
cl"
)
pri
nt("\
nTy peofcon=" ,
type(con))# <cl
ass'cx_Or
acl
e.Connect
ion'
>
pri
nt("\
nPy thonPr ogram obt ai
nsconnecti
onf r
om Oracl
eDB")
exceptcx_Oracle.
Dat abaseErrorasdb:
pri
nt("\
nProbl em indatabase: "
,db)
#Thisprogram testtheconnect ionwi thOracl
e
#Testcon2.py
i
mpor tcx_Oracl
e#st ep-1
tr
y:
con=cx_ Or acle.connect ("scot t/ti
ger@127. 0.
0.1/orcl
") #st
ep-2
exceptcx_ Oracle.Dat abaseEr rorasdb:
pri
nt("\nPr oblem i ndatabase: ",db)
el
se:
pri
nt("\nTy peofcon=" ,
type(con) )# <class'cx_ Or
acle.
Connect
ion'
>
pri
nt("\nPy thonPr ogram obt ainsconnect i
onf rom Oracl
eDB")
fi
nall
y:
con.close( )#st ep-6
pri
nt("\nConnect ionCl osed" )
#Thisprogr am cr eateanobj ectofcur sor
#cursorex1.py
i
mpor tcx_ Oracle
con=cx_Or acle.connect ("scott/ti
ger @127. 0.
0.1/orcl"
)
pri
nt("
\nPy thonPr ogram gotcol l
ect ionf rom OracleDB: ")
cur=con.cursor()
pri
nt("
\nPy thoncr eat esanobj ectofcur sor"
)
pri
nt("
Ty peofcur =",t
y pe(cur))#<cl ass' cx_Oracle.
Cur sor'
>

1)DDLst
atement
s(Dat
aDef
ini
ti
onLanguage)

=>Thepur
poseofDDLstat
ementsi
sthat"Tocr
eate,al
teranddr
oppi
ngat
abl
e".
=>I
nOracl
e,wehave3typesofDDLstat
ements.Theyare
1)cr
eate
2)al
ter
3)dr
op

1)create:
=>"cr
eate"isusedforcreat
ingat
abl
eonor
acledat
abase.
=>Syntax:-
SQL>cr eatet
abl
etable-
name(Col1Dat
aType,Col
2datatype.
..
..
Col
-ndat
aty
pe)

Exampl
e:cr
eat
est
udentt
abl
ewi
thsno,
nameandmar
ks

SQL>creat
etablest
udent(snonumber
(3)pr
imar
ykey
,namev
archar
2(10)notnul
l
,
marksnumber(5,
2)notnul
l
) ;

2)alt
er:
=>"al
ter"commandi susedf oral
ter
ingt
hetableeit
herbyaddi
ngnewcolumnname
orbychangi ngcol
umnsi zes.
=>Syntax1:-
SQL>alt
ertabl
et able-
namemodify(exi
sti
ngcolname dat
atype)
=>Syntax2:-
SQL>alt
ertabl
et able-
nameadd(newcol name dataty
pe)

Exampl
e: SQL>al
tert
abl
eteachermodify(
tnonumber(
4))
;
SQL>al
tertabl
eteacheradd(
subvar
char
2(10)
);

3)drop:
=>"dr
op"commandisusedfordroppingordel
eti
ngt
heent
ir
etabl
e.
=>Syntax:
-SQL>>dr
opt abl
et abl
e-name

=>Exampl
e:del
ete/dr
op studentt
able
SQL>dropt
ablestudent
;

#writ
eapy thonpr ogr am whi chwi llcreateemployeetablewithempno, empname
andsalaryinor acledat abase
#tabl
ecreate.py
i
mpor tcx_Or acle#st ep- 1
tr
y:
con=cx_ Or acl e.connect (
"scott/t
iger
@localhost/orcl
")#step-
2
cur=con. cur sor ()#st ep-3
#desi gnt hequer yandex ecute---
-st
ep-
4
ctq=" creat et ableempl oyee(enonumber (
2)pr i
mar ykey,
enamev archar2(
10)
notnull
,sal number (8, 2))"
cur.execut e(ct q)
print("Empl oy eeTabl eCr eatedSuccessfull
yinOr acl
eDB- -
veri
fy"
)#st ep-
5
exceptcx_Or acle.Dat abaseEr r
orasdb:
print("\nPr obl em i ndatabase:",db)
#writ
eapy thonpr ogr am whi chwi llalt
ertheemploy eetable,
changethecolumnsi ze
andaddnewcl oumn
#alt
erwit
hadd. py
i
mpor tcx_Or acle#st ep- 1
t
ry:
con=cx_Or acle.
connect (
"scot
t/ti
ger@localhost
/orcl
")#st
ep-
2
cur=con.cur sor
()#st ep-3
#designt hequer yandex ecute--
--
step-
4
aq="alt
ert ableemploy eeadd(cnamev archar2(
10))"
cur.
execut e(aq)
pri
nt("
Empl oyeeTablealteredSucecssf ul
lyinOracl
eDB--
ver
if
y")#st
ep-
5
exceptcx_Oracl
e.Dat abaseErr
orasdb:
pri
nt("
\nPr oblem indatabase:
" ,
db)

#writ
eapy thonpr ogr am whichwi llal
tertheempl oyeetable,changethecolumnsize
andaddnewcl oumn
#alt
erwit
hmodi fy.py
i
mpor tcx_Oracle#st ep-1
tr
y:
con=cx_ Oracl e.
connect (
"scot
t/ti
ger@localhost/orcl")#step-
2
cur=con.cur sor()#st ep-3
#designt hequer yandex ecute--
--
step-
4
aq="altertableempl oy eemodi f
y(enonumber (3),enamev archar
2(15))"
cur.
execut e(aq)
pri
nt("Empl oy eeTablealteredSucecssf ull
yinOr acleDB--ver
if
y")#step-
5
exceptcx_Oracle.DatabaseEr r
orasdb:
pri
nt("\nProbl em indatabase:",
db)

#writ
eapy thonpr ogram whi chwillal
tertheemployeetabl
e,changethecolumnsi
ze
andaddnewcl oumn
#droptable.py
i
mpor tcx_ Oracl e#st ep-1
tr
y:
con=cx_ Oracle.connect (
"scott
/ti
ger@local
host/or
cl")#step-2
cur=con. cursor( )#st ep-3
#desi gnt hequer yandex ecute--
--
step-
4
cur.execut e("dropt ablestudent"
)
pri
nt (
"St udentTabl eDroppedSucecssf ull
yinOracl
eDB- -
v er
if
y")#st
ep-
5
exceptcx_ Oracl e.DatabaseEr rorasdb:
pri
nt (
"\nPr oblem i ndatabase:",
db)

2)DMLst
atement
s(Dat
aMani
pul
ati
onLanguage)
=>Thepur poseofDMLst atement sinDat abasesoftwaresist
hat"ToMani pul
ate
recor dsoft able.
"
=>Mani pulatingrecordsofat ableisnothinginserti
ngrecords,del
eti
ngrecordsand
updat ingr ecor
ds.
=>InDat abasesof t
wares, wehav e3t y
pesofDMLst atements.Theyare
a)inser t
b)del ete
c)updat e
=>WhenweuseanyDMLst atement ,wemustcommi t(
permanentchanges) t
hedata
basebyusi ngcommi t()andr ol
lback(undot hechanges)theDMLoper ati
onweuse
rol
lback( )
.
=>commi t()androllback()arepr esentinconnectionobject.

a)insert
:
=>Thisstatementisusedf
orinser
ti
ngarecor
dintoat abl
e.
=>Syntax:-
SQL>insertint
oempl oy
eeval
ues(val
1forcol
1,val
2forcol 2..
.val
-nf
orcol
-n)
=>Exampl es:
SQL>inser
tint
oemployeeval
ues(
222,'
Renuka',
7.7,
'TCS')
;

b)delete:
=>Thiscommandi susedfordeletingtherecords.
=>Syntax1:- SQL>deletefrom tabl
e-name
SQL>del etefrom t
able-
namewherecondi
ti
onl
i
st
=>Exampl e1:
- SQL>delet
ef rom employee
=>Exampl e2:
- SQL>delet
ef rom employeewher eeno=555
=>Exampl e3:
-SQL>del
etefrom empl oyeewheresal>4.
0andsal
<6.
0;

c)update:
=>Thiscommandisusedforupdati
ngtherecor
dvaluesoftable
=>Syntax:(
Updat
ingAll
Records)
SQL>updateTableNameset
Exi
sti
ngColName1=Expr
essi
on1,Exi
sti
ngColName2=Expr
ession2..
.

=>Synt
ax:(Updat
ingPert
icul
arrecor
ds)
SQL>updateTableName
setExi
sti
ngColName1=Expressi
on1,Exi
sti
ngCol
Name2=Expr
essi
on2.
..
whereconditionl
ist

Exampl e:
SQL>updat eempl oyeesetsal=sal
+sal *(
10/100);
--
--
--
--
--
----
--
---
--
---
--
-
SQL>updat eempl oyeesetsal=sal+sal*(20/100)wher
eeno=600;
--
--
--
--
--
----
--
---
--
---
--
--
----
--
--
--
--
--
--
--
--
---
--
--
---
---
--
---
--
--
--
--
-
#writ
eapy thonpr ogram whichwi l
linsertemployeenumber,ename,
sal
aryand
companynameasar ecordinempl oyeet abl
eoforacl
edatabase
#recordinsertex1.
py
i
mpor tcx_ Oracle#st ep-1
t
ry:
con=cx_Oracl e.
connect(
"scott
/ti
ger@local
host /orcl
")#step-2
cur=con.
cur sor()#step-3
#designandexecut ethequery
i
q="inser
tint oemployeev al
ues(103,
'Aj
ay',
5.5,'
TCS')"
cur.
execute(iq)
con.commi t()
pri
nt("
Numberofr ecordsinsert
ed:{}
".f
ormat (cur.
rowcount))#1
pri
nt("
Empl oy eeRecordInsert
edsuccessfullyinEmpl oyeetable:
")

exceptcx_
Oracl
e.DatabaseEr
rorasdb:
pr
int
("
Problem inDat
abase:
",
db)

"
""
Not
e:
incurobject
,wehav
erowcount
,whi
chwi
l
lgi
venumberofr
ecor
ds
updat
edi
ndatabase.
""
"

#wri
teapythonprogram whi chwill
insertempl oyeenumber ,ename, sal
aryand
companynameasar ecordinempl oyeet ableoforacl
edat abase
#emp.py
---
fi
lenameandact sasmodul ename
i
mportcx_Oracl
e#st ep-1
defempinsert(
):
try:
con=cx_ Oracle.
connect("scott
/ti
ger@localhost/orcl
")#step-2
cur=con.cursor()#step- 3
#desi gnandexecut ethequer y
iq="i
nsertintoemployeev al
ues(105,
'Si
va',
4.5,'
HCL')"
cur.execut
e( i
q)
con.commi t
()
print(
"Numberofr ecordsi nsert
ed:{}
".f
ormat (cur.
rowcount))#1
print(
"EmployeeRecor dI nsert
edsuccessf ul
lyinEmpl oyeetable:
")

exceptcx_
Oracl
e.DatabaseEr
rorasdb:
pr
int
("
Problem inDat
abase:
",
db)

#writ
eapy thonprogram whi
chwi
ll
inser
temploy
eenumber,ename,
sal
aryand
companynameasar ecor
dinempl
oyeetabl
eoforacl
edat
abase
#recordi
nsertex1.
py
i
mpor tcx_Oracle#step-
1
tr
y:
con=cx_ Oracl e.connect ("scot t/tiger@localhost / orcl")#step- 2
cur =con. cur sor ()#st ep- 3
#desi gnandexecut et hequer y
iq=" i
nser tint oempl oy eev alues( 103, '
Ajay',
5.5,'
TCS' )"
cur .execut e(iq)
con. commi t()
pr i
nt (
"Numberofr ecor dsi nser t
ed: {
}".
format (cur .r
owcount ))#1
pr i
nt (
"Empl oy eeRecor dI nsert edsuccessf ullyinEmpl oyeet able:"
)
exceptcx_ Oracl e.Dat abaseEr rorasdb:
pr i
nt (
"Pr oblem i nDat abase: ",
db)
""
"Note:
incurobj ect ,wehav er owcount , whichwi l
l givenumberofr ecords
updatedindat abase.
""
"
#writeapy thonpr ogr am whi chwi l
linser templ oyeenumber ,ename, salaryand
companynameasar ecor di nempl oyeet ableofor acledat abase
#emp1.py --
-fil
enameandact sasmodul ename
i
mpor tcx_Or acl e#st ep-1
defempi nser t():
try:
whi le(True) :
t
ry :
con=cx_ Oracl e. connect ("scott/t
iger@l ocal host/orcl"
)#st ep-2
cur =con. cur sor ()#st ep- 3
#acceptempl oy eedat a
empno=i nt (i
nput ("Ent erEmpl oyeeNumber :
"))
ename=i nput ("Ent erEmpl oyeeName: "
)
sal=f loat(input ("EnterEmpl oyeeSal ar y:"))
cname=i nput ("Ent erEmpl oyeeCompanyName: "
)
#desi gnt hequer yandexecut e
cur .
execut e( "inser tint oempl oyeev alues( %d,'%s'
,%f,'
%s' )
"%( empno, ename, sal ,
cname))
con. commi t()
print (
"{}Empl oy eeRecor dInserted:".for mat (cur.
rowcount )
)
print (
"-"*50)
ch=i nput ("Douwantt oanot herRecor d(y es/no):")
if(ch. l
ower () =="no" ):
print("Thanksf orusi ngthisprogr am" )
break
ex ceptVal ueEr ror :
pr i
nt ("\nDon' tent erst r
s/symbol s/alpha-numer icsforEmp
Numberandsal ary.
.")
exceptcx_ Or acle. Dat abaseEr rorasdb:
pri
nt ("
Pr obl em i nDat abase: ",db)

#recor
dinser
tex3.
py
fr
om emp1i mportempi
nser
t
empinsert
()
#writeapy thonpr ogr am whi chwi l
ldeletear ecordfrom empl oyeetablebasedon
employ eenumber .
#recorddelet eex.py
i
mpor tcx_ Or acle
defempdel ete():
tr
y:
whi l
e(Tr ue) :
t
ry:
con=cx_ Or acl
e.connect("scott/
tiger@localhost/orcl
")#step-
2
cur =con. cursor()#st ep-3
#acceptempl oyeedata
empno=i nt(i
nput ("
Ent
erEmpl oyeeNumber :"
))
#desi gnandexecut ethequer y
cur.execut e("deletef
rom empl oy eewher eeno=%d"%empno)
con.commi t(
)
i
f(cur.rowcount >0):
print("{}Empl oyeeRecor d(s)deletefrom empl oyee
tabl
e:".
format (
cur .
rowcount ))
else:
print (
"Empl oyeeRecor ddoesnotexi sts"
)
print (
"="*50)
ch=i nput (
"Douwantt odeleteanotherRecor d(yes/
no):"
)
if(ch.lower()=="
no"):
pri
nt("Thanksforusi ngt hi
sprogram" )
break
exceptVal ueError:
print("\nDon' tenterstr
s/ symbol s/
alpha-numer i
csforEmpNumber" )
exceptcx_ Oracle. DatabaseErrorasdb:
print (
"Problem inDat abase:",
db)

#mai nprogr am
empdel et
e( )
#wr i
teapy thom pr ogram whi chwillupdatesalar
yofanemp, cnameofanemp
basedonempno
#recordupdat eex.py
i
mpor tcx_ Oracle
defempupdat e():
t
ry:
while(True):
try:
con=cx_ Oracl
e.connect("scott
/ti
ger@local
host/
orcl
")#st
ep-2
cur=con.cursor()#st ep-3
#acceptempl oyeedata
empno=i nt(i
nput("Ent
erEmpl oyeeNumber :
")
)
newsal=float(i
nput (
"EnterNewsal aryf orEmployee:"
))
newcomp=i nput(
"EnternewCompNameofEmpl oy
ee:"
)
#designandexecut ethequer y
cur.
execut e("
updat eempl oyeesetsal
=%f, cname='
%s'whereeno=%d"
%( newsal,newcomp, empno))
con.commi t
()
i
f(cur
.rowcount >0):
pri
nt("{}Empl oyeeRecor d(s)updatedinemployee
table:"
.for
mat (cur.r
owcount ))
el
se:
pr i
nt (
"Empl oyeeRecor ddoesnotexi st
s")
pr i
nt (
"="*50)
ch=i nput("Douwantt oupdateanotherRecord(
yes/
no)
:"
)
if(ch.lower()=="no"):
pri
nt("
Thanksf orusingthisprogr
am" )
break
exceptVal ueError:
pri
nt("
\ nDon'tent erstrs/
sy mbols/al
pha-
numer i
csforEmpNumberand
Salary" )
exceptcx_ Oracle.DatabaseEr rorasdb:
pr i
nt (
"Problem inDat abase:
",db)

#mainprogr
am
empupdate(
)

DRLst
atement
s(Dat
aRet
ri
eval
Language)

=>Thepur
poseofDRLst
atement
sist
hat"
Tor
eadorext
ractt
her
ecor
dsdat
afr
om
tabl
e".
=>TheDRLst
atementi
nDat
abasesof
twar
esi
s"sel
ect
"

=>Sy
ntax:-
SQL>selectcol
name1,
col
name-
2..
.Col
name-
nfr
om t
abl
e_name;

SQL>sel
ectcol
name1,
col
name-
2..
.Col
name-
nfr
om t
abl
e_namewher
econdl
i
st;

Exampl
es:
SQL>sel
ect*f
rom empl
oyee;

SQL>sel
ect*f
rom empl
oyeewher
esal
>4.
0andsal
<6.
0;

=>Inpy
thonProgr
amming,Oncesel ectqueryexecuted,al
lther
ecordsarepl
acedi
n
theobj
ectcur
.
=>Toextr
actt
herecor
dsfrom curobject,wehav e3Functi
ons.Theyare
1)fetchone()
2)fetchmany (
no.ofrecords)
3)fetchal
l()

=>f
etchone()isusedforfetchi
ngoner ecor
datat
imewher
ecurobj
ectpoi
nti
ngand
i
tret
urnther ecor
dinthef orm oftuple.
Syntax:
-r ecord=curobj.
fetchone(
)

=>f
etchmany
(n)
:her
e' '
n"representsnumberofrecords
Syntax:
-r ecords=cur
obj.
fet
chmany (n)
1)ifn<0t henwenev ergetanyrecords
2)ifn==totalnumberofrecordsintablethenwegetal
lrecor
ds
3)ifn<totalnumberofrecordsthenwegetnr ecor
ds
4)ifn>totalnumberofrecordsthenwegetal lt
herecor
ds.

=>fet
chal
l(
)isusedforfet
chingallt
herecor
dsoftabl
eandi
tret
urnst
her
ecor
dsi
n
thefor
m ofli
stoft
uples.
Syntax:-records=cur
obj.
fet
chal
l
()

#wri
teapythonpr ogr
am whi
chwi
l
lreadal
lther
ecor
dsf
rom empl
oyeet
abl
e--
sel
ect
Quer
y
#sel
ect
recordsex1.py
i
mportcx_Oracle
defrecor dssel ect ()
:
tr
y:
con=cx_ Or acle.connect("
scott/t
iger
@local
host
/or
cl"
)
cur=con. cursor ()
cur.execut e("select*from employee")
whi l
e( True) :
rec=cur .fetchone()
if(rec!=None) :
forv al i
nr ec:
print("{
}".
format(
v al
),
end="")
print()
else:
break
exceptcx_ Oracl e.
Dat abaseErr
orasdb:
print("Probl em I nDatabase:",
db)

#mai npor ogr am


recordssel ect ()
#wr i
teapy thonpr ogr am whi chwi l
lreadallt
her ecordsfr
om empl
oyeet
abl
e--
sel
ect
Query
#select recor dsex2. py
i
mpor tcx_ Or acl e
defr ecor dssel ect():
tr
y :
con=cx_ Oracle. connect("scott
/ti
ger@localhost/
orcl
")
cur=con. cur sor( )
cur.execut e("sel ect*from empl oyee"
)
recor ds=cur .f
et chmany (3)
forr ecor di nrecor ds:
f orv al i
nr ecor d:
print("
{}".format(val)
,end="")
print()
exceptcx_ Or acle.Dat abaseEr r
orasdb:
print("Pr oblem I nDat abase:"
,db)

#mainporogr
am
recor
dssel
ect
()

#wri
teapy thonpr ogram whi
chwi
l
lreadal
lther
ecor
dsf
rom empl
oyeet
abl
e--
sel
ect
Query
#sel
ectrecordsex3.py
i
mpor tcx_Oracle
defrecordsselect()
:
tr
y:
con=cx_ Oracle.connect ("scott/
ti
ger@local
host
/or
cl"
)
cur=con.cur sor()
cur.execute("select*f rom empl oyee")
records=cur .f
etchall(
)
forrecor dinrecor ds:
forv alinrecord:
pr i
nt("
{}"
.format (val
),
end="")
pr i
nt()
exceptcx_ Oracle.DatabaseEr rorasdb:
print
("Problem InDat abase:",db)

#mai npor ogr am


recordsselect ()
#wr i
teapy t
honpr ogr am whi chwi l
l r
eadal lt
herecor dsfrom employ
eet
abl
e--
sel
ect
Quer y
#colnames. py
i
mpor tcx_Or acl e
defcol names( ) :
try:
con=cx_ Or acl e.
connect ("
scot t/
ti
ger@localhost/orcl
")
cur=con. cur sor()
cur.execut e( "
select*f rom emp" )
colinfos=cur .
descr iption
colnames=[ colinfo[0]f orcolinfoincoli
nfos]
print("="* 50)
forcol namei ncolnames:
pr i
nt (
" {}".format (colname) ,
end="" )
pr i
nt (
)
pr i
nt (
" ="* 50)
exceptcx_ Or acl e. DatabaseEr r
orasdb:
pri
nt("Pr obl em I nDat abase: "
,db)
#mai npor ogr am
colnames( )
#wr i
teapy t
honpr ogr am whi chwi l
l r
eadal lt
herecor dsfrom employ
eet
abl
e--
sel
ect
Quer y
#colnamesdi r.py
i
mpor tcx_Or acl e
defcol names( ) :
try:
con=cx_ Oracl e.connect ("scott/ti
ger@localhost/orcl
")
cur=con. cur sor ()
tname=i nput (
" Entert ablename: ")
cur.
execut e( "sel ect*f rom %s"%t name)
pri
nt("=" *50)
forcol namei n[colinfo[ 0]forcol i
nfoincur.descript
ion]
:
print("{}".for mat (colname) ,end="" )
print()
print("="* 50)
exceptcx_ Or acl e.Dat abaseEr rorasdb:
print("Probl em I nDat abase: ",db)
#mai npor ogr am
colnames( )
#wr i
teapy t
honpr ogram whi chwi lldi
splayallther ecordsofanytablealongwi
th
columnnames
#tabledat aex. py
i
mpor tcx_ Oracl e
defal lrecords( ):
try:
con=cx_ Or acle.connect ("scott/t
iger@localhost/orcl
")
cur=con. cur sor ()
tname=i nput ("Entert abl ename: ")
cur.execut e( "
sel ect*f rom %s"%t name)
#pr i
ntingcol umnnames
print(
" =" *70)
forcol namei n[colinfo[ 0]f orcolinfoi
ncur .descript
ion]
:
pr int( "
{}".
format (
col name) ,
end="" )
pr int( )
pr int( "
=" *
70)
#di splayr ecor dsoft able
#nor =0
recor ds=cur .
fetchal l()
forr ecor dinr ecor ds:
#nor =nor +1
forv al i
nr ecor d:
print("{}
".format (val
),end="" )
print()
print("="*70)
print("Total NumberofRecor ds={ }
".
format(l
en(r
ecords))
)
print("="*70)
exceptcx_ Or acle.Dat abaseEr rorasdb:
pr i
nt("Pr obl em I nDat abase: ",
db)
#mai npor ogr am
al
lrecor ds()

I
ntr
oduct
iont
oMy
SQL

=>My
SQLi
soneRDBMSSof
twar
e
=>MySQLisoft
heFr eewareandOpenSour ce
=>MySQLissui
tablef orsmallandl
argescaleappl
i
cat
ionf
orDat
aPer
sist
ency.
=>MySQLisVer
yFast, rel
iabl
eandScalabl
eandEasytousef
ormai
ntai
ningDat
a
Per
sist
ency.
=>MySQLwasfirstreleasedinthey
ear1995

Communi
cat
ionbet
weenPy
thonPr
ogr
am andMYSQLDat
abase

=>Toperfor
mv ari
ousdat abaseoper ati
onsbyusi ngPyt
honl anguage,Fi
rstwemust
l
earnstepsforcommuni cati
onbet weenpy t
honprogram andMYSQLDat abase
softwar
e.
Steps:
1)importmy sql.
connect or
2)PythonProgram mustgett heconnecti
onf rom MYSQLDatabase.
3)Createanobj ectofcursor
4)DesigntheQuer y,placethequeryincursorandexecute.
5)Processther esultwhichisavail
abl
eincur sorobj
ect.
6.PythonProgram Cl osestheconnecti
on.

Step-1:
importmy sql
.connect
or
=>Ifpyt
honPr ogr
am wantt ocommunicat
ewithMYSQLdat
abase,Fi
rstwemust
i
nstallmysql
-connectormodulebyusi
ngpipandlat
erwemusti
mporti
npython
program.
Exampl
e: i
mpor
tmy
sql
.connect
or

Step-2:PythonPr ogr
am mustgettheconnecti
onfrom MYSQLDatabase.
=>Ifapy t
honpr ogram wantaconnecti
onfr
om MYSQLDat abase,
wemustuseapr
e-
definedfuncti
onconnect (
)whichi
spresenti
nmy sql.
connect
ormoduleandi
t
returnsanobjectof<class,
mysql.
connect
or.
Connecti
on>

Sy
ntax:
- v
arname=my
sql
.connect
or.
connect
(host
="DNS/
IPAddr
ess"
,

user
="UserNameofMYSQL"
,

passwd="
passwor
dofMYSQL"

=>"varname"i sanobj ectof<cl ass,mysql.connect or


.connect
ion.MySQLConnect i
on'
>
=>my sql.connectoriscalledModul ename
=>connect ()i
spr edefi
nedf unct i
oninmy sql.connectormodule
=>Here" username"ofMYSQLDBi s" r
oot "
=>here" passwd"ofMYSQLDBi s" r
oot"
=>Here"DNS( Domai nNami ngSer vi
ce)"r epresentsNameofMachi neWher e
DatabaseSof t
war esresi
des" .Thedef aultDNSofev er
ymachi neis"l
ocalhost"
.
=>Here" IPAddr ess(I
nternetProt ocoladdr ess)"repr
esentsNumer i
calAddressofa
machi newher eDat abasesof twar eresi
des.Thedef aultI
Paddr essofeverycomputer
i
s" 127.0.0.1"
(al
soknowasLoopBackAddr ess).

Exampl
e:- conobj=my sql
.connect
or.
connect(
host
="l
ocal
host"
,
user
="r
oot",
passwd="
root
")
pri
nt(
"pythonpr ogr
am gotconnect
ionf
rom MYSQL")

3)Createanobj ectofcursor
=>Thepur poseofcr eat
inganobj ectofcur soristhat"
Tocar aythequeryfrom
PythonPr ogr am andbringstheresultfrom databasesof t
war eandhandov ert
o
pythonpr ogram" .
=>Tocr eat eanobjectofcur sor
,weuseapr e-
definedcall
edcur sor
(),whichis
presentinconobj .
=>Syntax:- v
arname=connobj .cursor()
=>here"v arname"isanobj ectof<cl ass'my sql.
connector
.cursor.
My SQLCursor
'>
=>Here" connobj"isanobj ect<cl ass,
my sql
.connect or.
connection.MySQLConnect i
on'>

Exampl
es:
kv
rcur=conobj.
cur
sor(
)
pr
int
("
Cur sorobj
ectcr
eat
ed.
."
)

4)Desi
gntheQuer y,pl
acethequeryincur
sorandexecute.
=>AQueryisrequest/Questi
ontot hedat
abasefrom pyt
honProgram.
=>ToexecuteanytypeofQuer y
,weuseapr e-defi
nedFunct
ioncal
ledexecut
e()
,
whichi
spresentin<class'
my sql.
connect
or.
cursor.
MySQLCursor
'>
=>Sy
ntax:
- cur
obj
.execut
e("
Quer
y")

5)Processtheresultwhichisav
ail
ableincursorobj
ect.
=>Thisprocessmakesust ounderstand,r
etr
ievethedat
afr
om cur
sorobj
ectand
di
splayitontheconsole.
Example:Handlingexceptionmessages
deal
ingwithr
esults.

6)Closetheconnect ion:
=>Toclosetheconnect i
onmanual l
y,wewr i
tef
inal
lybl
ock.
Example:
tr
y:
--
--
--
---
--
--
----
--
--
--
---
--
--
----
except.
..
..
..:
--
--
--
--
--
--
--
-
fi
nall
y:
pri
nt("
\nFinallyBlock")
i
f(conobj!=None) :
conobj .
close(
)
pri
nt("DatabaseConnect
ionClosed"
)

#Thisprogram obtainsconnecti
onMy SQLDB
#contestmy sql
.py
i
mpor tmy sql.
connector
conobj=my sql.
connector
.connect
(host
="l
ocal
host
",

pri
nt("
typeofconobj =" ,
type(conobj)
)#<class
'
my sql.
connect or.connect ion.
My SQLConnect i
on'
>
pri
nt("
pythonpr ogram gotconnect i
onf r
om MYSQL" )
#Thisprogram cr eateasanobj ectcursor
#cursorex.
py
i
mpor tmy sql.connect or
conobj=my sql.connect or.connect(
host="local
host
",
user
="r
oot
",
passwd="
root
")
pri
nt("
pythonpr ogram gotconnect i
onf r
om MYSQL" )
cur=conobj.cursor()
pri
nt("
cursorobj ectcr eated:")
pri
nt("
typecur =",t
ype( cur))#t ypecur=<cl ass
'
my sql.
connect or.cursor.My SQLCursor'>

#Program forcreati
ngadat abaseonthenameof"batch9am"
#databasecreate.
py
i
mpor tmy sql.
connector
tr
y:
conobj=my sql
.connector
.connect
(host
="l
ocal
host
",user="
root
",passwd="
root
")
cur=conobj .
cur sor ()
#desi gnt hequer yandex ecut e
dq=" createdat abasebat ch9am"
cur.
execut e(dq)
pri
nt ("DataBasecr eat edi nMy SQLandVer if
y:")
exceptmy sql .connect or .
Dat abaseEr rorasd:
pri
nt ("Problem i nDat aBase: ",
d)
#writ
eapy thonpr ogram whi chwi lldel etear ecordf r
om empl oy eet
ablebasedon
employ eenumber .
#recorddeleteex. py
i
mpor tmy sql .connect or
defempdel et e():
tr
y:
while(Tr ue):
try:
con=my sql .
connect or.connect (host ="l
ocalhost ",
user=" root ",passwd=" root"
, database="bat ch9am")
cur =con.cur sor ()#st ep- 3
#acceptempl oy eedat a
empno=i nt (
input ("Ent erEmpl oyeeNumber :
"))
#desi gnandexecut et hequer y
cur .
execut e(" delet ef rom empl oy eewher eeno=%d"%empno)
con.commi t()
if
(cur .
r owcount >0) :
pr i
nt ("{}Empl oy eeRecor d(s)deletef r
om empl oyee
tabl
e:"
.format (cur .
rowcount ))
else:
print ("
Empl oy eeRecor ddoesnotexi sts")
print("=" *50)
ch=i nput ("Douwantt odel eteanot herRecor d(yes/
no):
")
if
(ch. lower ()=="no"):
pr i
nt ("Thanksf orusi ngthispr ogr am")
br eak
exceptVal ueEr ror :
print ("
\ nDon' tent erstrs/ sy
mbol s/alpha-numer i
csforEmp
Number" )
exceptmy sql.connect or .
Dat abaseEr rorasdb:
print("Probl em i nDat abase: ",
db)

#mainpr
ogram
empdel
ete(
)

#writ
eapy t
honpr ogr
am whi
chwil
linser
temploy
eenumber,ename,
sal
aryand
companynameasar ecordi
nemployeetabl
eoforacl
edat
abase
#recordi
nsertex.
py--
-
i
mpor tmy sql
.connector#st
ep-
1
defempi nser t
():
try:
whil
e(Tr
ue)
:
t
ry:
con=my
sql
.connect
or.
connect
(host
="l
ocal
host
",

cur=con. cur sor()#st ep-3


#acceptempl oy eedat a
empno=i nt (
input ("EnterEmpl oyeeNumber :
")
)
ename=i nput ("Ent erEmpl oyeeName: ")
sal=f l
oat(input ("EnterEmpl oyeeSal ary:"
))
cname=i nput ("Ent erEmpl oyeeCompanyName: ")
#desi gnt hequer yandexecut e
cur.execut e("inser tint
oempl oyee
v
alues(
%d,'
%s',
%f,
'%s')"%( empno, ename, sal,cname))
con. commi t()
print("
{}Empl oy eeRecor dInserted
:
".f
ormat(
cur.
rowcount )
)
print("
-"*
50)
ch=input ("Douwantt oanot herRecor d(yes/no)
:"
)
if
(ch. l
ower ()==" no" )
:
print("Thanksf orusingt hisprogram")
break
exceptVal ueEr r
or:
print("
\nDon' tent erstrs/symbol s/alpha-
numer i
cs
f
orEmpNumberandsal ary.
.")
exceptmy sql
.connect or
.DatabaseEr rorasdb:
print
("Problem i
nDat abase: ",
db)

#mainpr ogr am
empinsert()
#writ
eapy thom pr ogram whi chwi l
lupdatesal aryofanemp, cnameofanemp
basedonempno
#recordupdat eex.py
i
mpor tmy sql .
connector
defempupdat e():
tr
y:
while(True):
tr
y :
con=my sql.connect or.
connect(host="local
host"
,user
="r
oot
",
passwd=" root ",
database=" batch9am")
cur=con.cur sor()#st ep-3
#acceptempl oy eedat a
empno=i nt(input("EnterEmpl oyeeNumber :
"))
newsal =fl
oat (i
nput ("
EnterNewsal aryforEmployee:"
))
newcomp=i nput ("EnternewCompNameofEmpl oyee:
")
#designandexecut ethequer y
cur.
execut e("updat eempl oyeesetsal =%f,
cname=' %s' wher eeno=%d"%( newsal,newcomp,empno))
con.commi t()
if
(cur.r
owcount >0) :
print
("{}Empl oyeeRecord(s)updatedinemployee
table:
".
format(cur.
rowcount ))
el
se:
print
("Empl oyeeRecor ddoesnotexi st
s")
print
("="*50)
ch=input (
"Douwantt oupdateanot herRecor
d(yes/
no)
:"
)
if(
ch.lower()=="no"
):
print("
Thanksf orusingthi
spr ogram")
break
exceptValueError:
print
("
\nDon' tenterstrs/sy
mbols/alpha-numeri
csforEmpNumberand
Salary")
exceptmy sql.
connect or.Dat
abaseEr r
orasdb:
print
("Problem inDatabase:"
,db)

#mainprogr
am
empupdate(
)

#wr it
eapy thonpr ogram whi chwi l
lcreateemploy eetabl
ewithcolumnname
eno,ename, sal andcnamei nMYSQL
#tablecreate.py
i
mpor tmy sql.connect or
try:
conobj =my sql.
connect or.connect(host="
local
host "
,user
="r
oot",passwd="r
oot
",
database="batch9am")
cur=conobj .cursor()
#designt hequer yandexecut e
tq="cr
eat et ablestudent( snoi ntprimarykey ,
snamev ar
char(
10)notnull,
marks
realnotnul l,cnamev archar( 10)notnull)"
cur.
execut e( t
q)
pri
nt("
Tabl ecr eatedinbat ch9am dat abaseofMy SQLandVerify
:")
exceptmy sql.connector .
Dat abaseErrorasd:
print( "
Problem inDat aBase:",
d)

#wr i
teapy thonpr ogram whi chwil
ldisplayall
ther ecordsofanytabl
ealongwit
h
columnnames
#tabledataex. py
i
mpor tmy sql.connect or
defal lr
ecor ds():
try
:
con=my sql.
connect or.
connect(
host ="l
ocalhost",
user="
root"
,passwd="
root
",
database="batch9am")
cur=con. cursor()
tname=i nput ("
Ent ertablename:")
cur.
execut e("select*f rom %s"%t name)
#printi
ngcol umnnames
pri
nt("="*70)
f
orcol namei n[colinfo[
0]f orcoli
nfoincur.
descri
pti
on]
:
pri
nt("{}
".f
ormat(
colname),
end="")
print (
)
print (
"="*70)
#di splayr ecordsoft able
recor ds=cur .f
etchall(
)
forr ecor dinrecor ds:
forv alinrecor d:
print("
{}"
.format(val)
,end="")
print()
print("
="*70)
print("
Total NumberofRecor ds={
}".
for
mat(l
en(
recor
ds)
))
print("
="*70)
exceptmy sql.connect or.
DatabaseErrorasdb:
pri
nt("Pr oblem I nDat abase:",db)
#mainpor ogr am
al
l
records()

St
ri
ngHandl
i
ngi
nPy
thon(
par
t-
2)

=>Weknowt hataSt ri
ngisacol l
ect i
on/sequenceofChar act
ersencl
osedwit
hin
singl
e/doubl eQuot es(or)t r
iplesi ngl
e/doubleQuotes.
=>Str
ingdatai softype<class,
'str
'>
=>Todov ari
ousoper eati
onsonSt ringdata,wehavetousethefol
lowi
ngthe
funct
ions.
1)capital
i
ze():
=>Thisfunct
ioni susedforcapitalizi
ngt hegi
venstrdat
a
=>Syntax: v arname=str
obj.capitali
ze()

Exampl
es:
>>>s="py
thonisanoopl ang"
>>>pri
nt(
s,t
ype(s) )
--
--
--
--
-pyt
honisanoopl
ang<class'str
'>
>>>cs=s.
capit
alize()
>>>pri
nt(
cs,t
ype( cs))
--
--Pythoni
sanooplang<class'st
r'
>
>>>pri
nt(
s,t
ype(s) )
--
-- pythonisanoopl
ang<class'str
'>

2)ti
tl
e():
=>ThisFunct
ioni
susedforget
ti
ngallwor
dsFi
rstChar
act
ersascapi
tal
.
=>Syntax:
- v ar
name=str
obj.
ti
tl
e()

Exampl es:
>>>s="py thonisanoopl ang"
>>>ts=s.titl
e()
>>>print(ts,
type(t
s))-
--
--
--
-Py
thonI
sAnOopLang<cl
ass'st
r'
>
>>>print(s,t
ype(s))
--
--
-pyt
honisanoopl
ang<cl
ass'
str
'>

3)f
ind(
):

=>Thisfuncti
onisusedf orf i
ndingani ndexofthef
ir
stoccur
anceofspeci
fi
edst
r
datainthegivenstrdata.
=>Ifthedatafoundtheni tret
urnsI t
s+v eindexval
ue
=>Ifthedatanotfoundt henitreturns- 1
Syntax:
-v arname=strobj.f
ind(strdata)

Exampl es:
>>>s=" py thoni sanoopl ang"
>>>pr i
nt (s,t
ype( s))
pythoni sanoopl ang<cl ass'str
'>
>>>ind=s. fi
nd("python")
>>>pr i
nt (i
nd) -
--
---0
>>>ind=s. fi
nd("n")
>>>pr i
nt (i
nd) -
--
---5
>>>ind=s. fi
nd("k")
>>>pr i
nt (i
nd) -
--
---- -1
>>>ind=s. fi
nd("o")
>>>pr i
nt (i
nd) -
--
----
4
Exampl es:
forleti ns:
ind=s. f
ind( l
et)
pri
nt( i
nd)
Exampl es:
#Indexex .py
l
ine=input ("Enteral i
neoft ext:"
)
pri
nt("GivenDat a={}".
for
mat (l
ine))
forchi nl i
ne:
print
("\tCharacter:{}Index={
}".
for
mat
(ch,
l
ine.
fi
nd(
ch)
))

#indexex.
pt
l
ine=input
("
Ent
erl
i
neoft
ext
:"
)#Py
thon
i
=0
forchi nli
ne:
pri
nt("
Character:
{}-
--
>Index :{
}andorginalIndex={}
".
format(ch,
l
ine.i
ndex (
ch),
i))
i
=i+1
--
--
---
--
---
--
--
--
--
--
---
--
--
--
--
---
--
--
--
--
--
---
---
---
---
--
--
--
--
--
--
--
--
--
---
--
---
--
--
--
--
--
--
-
4)isalnum():
=>ThisFunct i
onreturnsTruePr ovidedstrdatacont ai
ns"Alphabet
swi t
hdigit
sor
onlywi t
hdigit
soronl ywithalphabet s"
=>ThisFunct i
onreturnsFalsePr ovidedstrdataisacombi nati
onof" Al
phabetsand
number swi t
hanyspeci alSymbol s"

Syntax:-v ar
name=st robj .
isal
num()
(or
)
strobj .
isalnum()
Exampl es:
--
--
--
---
--
---
---
>>>s=" 12345"
>>>b=s. i
salnum()
>>>print(b)-
--
--
--
---
--True
>>>s=" python12345"
>>>s.isalnum()--
---
---
--True
>>>s=" python12345#"
>>>s.isalnum()--
---
---
-False
>>>s=" python12345"
>>>s.isalnum()--
---
---
--False
>>>s=" Pythonisanoopl ang"
>>>s.isalnum()--
---
---
---False
>>>s=" python"
>>>s.isalnum()--
---
---
Tr ue

5)isal
pha(
):
=>Thi
sFuncti
onr
etur
nsTr
uepr
ovi
dedst
rdat
acont
ainsonl
yAl
phabet
sot
her
wise
i
tretur
nsFalse.

=>Sy
ntax:
- v
arname=st
robj
.i
sal
pha(
)

Examples:
>>>s="Python"
>>>b=s.i
salpha()
>>>pri
nt(b)-
--
--
---
--
--
True
>>>s="1234"
>>>pri
nt(s.i
sal
pha())-
--
--
--
-False
>>>s="python1234"
>>>pri
nt(s.i
sal
pha())-
--
--
--
False
>>>s="python_1234"
>>>pri
nt(s.i
sal
pha())-
--
--
--
False

6)isdigi
t(
):
=>ThisFuncti
onretur
nsTruepr
ovi
dedst
rdat
acont
ainsonl
ypur
lydi
git
s(0-
9)
otherwisei
tret
urnsFalse.
Syntax:
-v arname=strobj.
isdigit
()
or
st
robj.
isdigit
()
Exampl es:
--
--
--
---
--
---
---
>>>a="1234"
>>>print(a.i
sdigi
t()
)-
--
--
---
---
-True
>>>a="py th1234"
>>>print(a.i
sdigi
t()
)-
--
--
---
False
>>>a="py thon"
>>>print(a.i
sdigi
t()
)-
--
--
-False
>>>a="py th#$123"
>>>print(a.i
sdigi
t()
)-
--
--
---
-False

7)isl
ower():
=>ThisFunct
ionretur
nsTrueprov
idedt
hest
rdat
aiscompl
etel
yav
ail
abl
ein
l
ower caseot
herwiseitr
etur
nsFal
se.

Synt
ax:-v arname=strobj.i
slower()
or
st
robj.
islower()
Examples:
>>>s="
py thon"
>>>pri
nt(s.i
slower(
))-
--
--
----
-True
>>>s="
Py thon"
>>>pri
nt(s.i
slower(
))-
--
--
----
False
>>>s="
py thonisanoopl ang"
>>>pri
nt(s.i
slower(
))-
--
-True
>>>s="
py thonisAnoopl ang"
>>>pri
nt(s.i
slower(
))-
--
--
--False

7)isupper
():
=>ThisFunct
ionreturnsTrueprovi
dedt
hest
rdat
aiscompl
etel
yav
ail
abl
einupper
caseotherwi
seitreturnsFalse.
Syntax:
-v ar
name=st robj
.i
supper(
)
or
st
robj
.i
supper (
)

Examples:
>>>s="
Py thon"
>>>pri
nt(s.i
supper
())
--
--
--
--
--False
>>>s="
PYTHON"
>>>pri
nt(s.i
supper
())
--
--
--
-True
>>>s="
py thonisanooplang"
>>>pri
nt(s.i
supper
())
--
--
--
--
-False
>>>s=" PYTHONI SANOOPLANG"
>>>print(s.i
supper())-
---
---
True
9)isspace( )
=>ThisFunct ionreturnsTr uepr ovidedst
rdat
acont
ainspur
elyspaceot
her
wisei
t
ret
urnsFal se.
=>Syntax:- v arname=st robj.
issapce(
)
(
or)
st
r obj.
isapce()
Exampl es:
>>>s=" Pythonisanoop"
>>>print(s.i
sspace())--
---
--
-False
>>>s=""
>>>print(s.i
sspace())--
---
--
-True
>>>s=" "
>>>print(s.i
sspace())--
---
--
-True
>>>s=" 123345"
>>>print(s.i
sspace())--
-False
>>>s=" "#empt ystring
>>>s.isspace( )
--
--
--
----
-False

10)upper
():
=>Thi
sFunctioni
susedforconv
ert
ingl
owercasedat
aint
ouppercasedat
a.
Synt
ax:-v ar
name=str
obj.
upper
()

11)lower ():
=>ThisFunct ioni susedf orconvert
inguppercasedat
aint
olowercasedat
a.
Synt
ax:-v arname=st robj.l
ower
()
Exampl es:
>>>s="py thoni sanoopl ang"
>>>uc=s. upper (
)
>>>print(uc)---
--
--PYTHONI SANOOPLANG
>>>print(s)--
---
--
py t
honi sanoopl ang
>>>print(uc)---
-PYTHONI SANOOPLANG
>>>lc=uc. l
ower ()
>>>print(l
c) -
--
---
--pythoni sanooplang

12)join()
:
=>ThisFunctioni
susedconcati
nati
ngall
thesequenceofv
alueswhi
char
eav
ail
abl
e
i
nt hef or
m str
Syntax:-v ar
name=st
robj
1.j
oin(
it
erabl
eobj)

Examples-:
>>>t
pl=('
j
av a'
, '
py t
hon','
DataScience')
>>>pri
nt(tpl,
type( t
pl))
--
('
java'
,'
python','
Dat
aSci
ence'
)<cl
ass'
tupl
e'
>
>>>s2=""
>>>s3=s2.join(tpl)
>>>pri
nt(s3)---
->javapyt
honDataSci ence

>>>l
st=[
"Appl
e",
"Mango"
,"
Kiwi
",
"Guav
a"]
>>>fr
s=""
>>>fr
s=frs.j
oin(
lst
)
>>>pri
nt(
f r
s)-
---
--
--
--
--
--
--
--
-Appl
eMangoKi
wiGuava
>>>l
st=["
Appl e"
,"
Mango","
Kiwi
",
"Guav
a"]
>>>fr
s=""
>>>fr
s=frs.j
oin(
lst
)
>>>pri
nt(
f r
s)-
---
--
--
--
--
--
AppleMangoKiwiGuava

13)spli
t()
:
=>Thi
sf unct
ionisusedforspl
it
tingthegivenstrdat
aintodi
ff
erentt
okensbased
spi
tti
ngv al
ue.Thedefaul
tspli
tt
ingvalueisspace
=>Thi
sFunct i
onretur
nsspli
tti
ngv al
uesintheform ofl
ist
.

Sy
ntax:
-li
stobj
=st
robj
.spl
i
t()
OR
l
i
stobj
=st
robj
.spl
i
t("
spl
i
tingv
alue"
)

Examples:
>>>s="
Py t
honi sanoopl ang"
>>>s.
split
()-
--
--
--
--['
Py t
hon' ,'
i
s','
an'
,'
oop'
,'
lang'
]
>>>s="
9-11-2021"
>>>l
=s.spli
t(
"-"
)
>>>pri
nt(l
)-
--
--
---
--
['
9'
,'11'
, '
2021']
>>>s="
apple#kiwi#guav a-banana"
>>>l
=s.spli
t(
"#")
>>>pri
nt(l
)-
--
--
---
--
['
apple'
, '
kiwi'
,'
guava-
banana']
>>>l
[2]
.spli
t(
"-"
)--
--
--
--
['
guav a','
banana'
]

#Indexex.py
l
ine=input("
Enteralineoftext
:")
pri
nt("Giv
enDat a={}"
.for
mat(l
ine)
)
forchi nli
ne:
pri
nt(
"\tCharact
er:{
}I ndex
={}
".
for
mat
(ch,
l
ine.
fi
nd(
ch)
))

#wr i
teapy t
honprogr
am whichwill
acceptalineoftextandsepar
atet
hem wi
th
vowelsandconsonentsandspecialsymbols
#alhabets.
py
l
ine=input(
"Ent
erali
neoftext:
")#a3$b56hq3rt$#P"
vs=[]
cs=[]
ds=[]
ss=[]
forchinli
ne:
i
fchi n['
a',
'
e',
'
i'
,
'o',
'
u',
'
A','
E'
,'
I'
,
'O',
'U']
:
vs.append(ch)
el
if(chnoti n['
a',
'
e',
'i
'
,'
o',
'
u',
'A',
'
E' ,
'
I'
,'
O',
'
U']andch.
isal
pha()):
cs.append(ch)
el
if(chnoti n['
a',
'
e',
'i
'
,'
o',
'
u',
'A',
'
E' ,
'
I'
,'
O',
'
U']andch.
isdi
git
()):
ds.append(ch)
el
se:
ss.append(ch)
else:
pri
nt("
--
--
---
--
--
--
---
--
--
---
--
--
---
--
---
--
----
--
-")
pri
nt("
GivenLine={}"
.format(li
ne) )
pri
nt("
Vowel sList
={}".
format (
v s))
pri
nt("
Cons.List={}"
.f
ormat (cs))
pri
nt("
Digit
sList={}"
.f
ormat (ds))
pri
nt("
SpecialSymbol sList={}"
.format(ss))
pri
nt("
--
--
---
--
--
--
---
--
--
---
--
--
---
--
---
--
----
--
-")

Li
stofObj
ectOr
ient
edPr
inci
ples

=>ToSayPy
thonisoneoft heObj ectOri
ent
edPr
ogr
ammi
ngLanguage,
Ithast
o
Sati
sfyt
hef
oll
owi
ngOOPsPr i
nciples.
1)Classes
2)Objects
3)DataEncapsul ation
4)DataAbst racti
on
5)Inheri
tance
6)Polymor phism
7)MessagePassi ng
I
mpor
tanceofObj
ectOr
ient
edPr
inci
ples

=>InRealTimetodevelopanypr oject,wemustuseal anguageandi tcansati


sfyt
wo
ty
pesofPr i
ncipl
es.Theyare
1)ProcedureOrientedPrincipl
es(Funct
ionalOr
iented).
2)ObjectOrient
edPr inci
ples.
=>PythonisoneofBothPr ocedureandObj ectOrient
edProgramming.
=>EventhoughPy t
honbelongst oBot hProcedureandObjectOri
entedProgramming
,everythi
ngtreat
edasobj ects.

"
Beni
fi
tsofTr
eat
ingEv
eryt
hingasobj
ect"(
or)Adav
nat
gesofOOPs

=>I
nObj ect,wecanst orelargeVol umeofDat aandachi ev esPlat
formIndependency
(Python)
=>Theconf i
denti
al Dat acanbet ransferedbetweenmul t
ipleremotemachi neinthe
f
orm ciphertext( Encryptedf ormat )
.Sot hatsecur
itycanbeenhanced(I mprov ed).
=>TheLar geofVol umeofDat aTr ansferedbetweenMul tipleMachinesallatoncei n
t
hef orm ofobjectandl eadst oef f
ectivecommuni cati
on.
=>All
Valuesar eav ail
ablear oundt heobj ectsandprovidesef f
ecti
vememor y
Management .

#Program forstudentmar ksreportgener at


ionwithClassesandObj
ectal
ong
Database.
#StudentMarksRepor tMySQL. py
i
mpor tmy sql
.connect or
cl
assSt udentMarksRepor tMySQL:
defgetstudentdetail
s(self
): #getti
ngstno,name,CM,CPPM,
PYTM
#validat
ionofSt udentNumber
while(Tr
ue) :
self
.sno=int (
input("
Ent
erSt udentNumber
:"
))
if
(self
.sno>0)and( sel
f.
sno<=100):
break
self
.sname=i nput("EnterStudentName: ")
#validat
ionofmar ksi nC
while(Tr
ue) :
sel f
.cm=i nt(input (
"EnterMar ksi nC: "
))
if(self.cm>=0)and( self.
cm<=100) :
br eak
#v al
idat i
onofmar ksi nCPP
whi l
e(Tr ue) :
sel f
.cppm=i nt(input("
Ent erMar ksinCPP: ")
)
if(self.cppm>=0)and( self.
cppm<=100) :
br eak
#v al
idat i
onofmar ksi nPYTHON
whi l
e(Tr ue) :
sel f
.py tm=i nt(input("EnterMar ksi nPYTHON: "))
if(self.pytm>=0)and( self.pytm<=100) :
br eak
defdeci
degrade( self):#cal totmar ks,percent ageandgr ade
#calcul atet otal andper cant ageofmar ks
self.
tot mar ks=sel f.cm+sel f.
cppm+sel f.
py tm
self.
per cent =(sel f
.totmar ks/300) *100
#deci det hegr ade
if
(self.cm<40)or( self.
cppm<40)or( self.pytm<40) :
sel f
.grade=" FAI L"
else:
if(self.tot
mar ks>=250)and( sel f.
totmar ks<=300):
sel f
.grade=" DISTI NCTI ON"
elif(self.t
ot mar ks>=200)and( self.
totmar ks<=249)
:
sel f
.grade=" FIRST"
elif(self.t
ot mar ks>=150)and( self.
totmar ks<=199)
:
sel f
.grade=" SECOND"
elif(self.t
ot mar ks>=120)and( self.
totmar ks<=149)
:
sel f
.grade=" THI RD"

defst
oredt
sudentdata(
self)
:#Py thonDataBaseCommunicati
oncode
tr
y:
con=my sql
.connect
or.
connect
(host
="l
ocal
host
",

cur =con.cursor()
#desi gnt hequer yandexecut e
iq="insertintoresultval
ues(%d,'
%s',
%d,%d,
%d,%d,%f,
'%s'
)"
cur .
execut e(i
q
%(self
.sno,
sel
f.
sname,sel
f.cm, self
.cppm,self.
pytm,sel
f.t
otmarks,
sel
f.
percent
,self
.gr
a
de))
con. commi t(
)
pr i
nt("\n{}StudentRecordInsertedi
nResultTable-
-
ver
if
y".
format(
cur.
rowcount))
exceptmy sql.connect or
.DatabaseErr
orasdb:
pr i
nt("Problem inDatabase:"
,db)

#mainprogr
am
s=St
udentMarksRepor
tMy
SQL(
)
s.
getstudentdet
ail
s()
s.
decidegrade()
s.
storedtsudent
data(
)

#Program forst
udent mar ksreportgener at i
onwi t
hCl assesandObj ectal
ong
Database.
i
mpor tcx_Oracl
e
cl
assSt udentMarksRepor t:
defgetstudentdetail
s(self
) :#get ti
ngst no, name, CM,CPPM, PYTM
#validat
ionofSt udentNumber
while(Tr
ue) :
self
.sno=int (i
nput ("Ent erSt udentNumber :")
)
if
(self.
sno>0)and( self.sno<=100) :
break
self
.sname=i nput("Ent erSt udentName: ")
#validat
ionofmar ksi nC
while(Tr
ue) :
self
.cm=i nt(input (
"Ent erMar ksi nC:"
))
if
(self.
cm>=0)and( self.cm<=100) :
break
#validat
ionofmar ksi nCPP
while(Tr
ue) :
self
.cppm=i nt(input ("
Ent erMar ksinCPP:"))
if
(self.
cppm>=0)and( self.cppm<=100) :
break
#validat
ionofmar ksi nPYTHON
while(Tr
ue) :
self
.pytm=i nt(input ("EnterMar ksinPYTHON: "
))
if
(self.
pytm>=0)and( self .
py tm<=100) :
break
pri
nt(sel
f.sno,self
.sname, sel f.
cm, self.cppm,self
.pytm)

defdeci
degrade(self):#cal tot
mar ks,percentageandgr ade
#calculatetotalandper cantageofmar ks
self.
totmarks=sel f.
cm+sel f.cppm+sel f.
pytm
self.
percent=(self.t
otmar ks/300)*100
#decidet hegr ade
if
(self.
cm<40)or( self.
cppm<40)or( self.
pytm<40):
self
.grade=" FAIL"
else:
i
f(self.t
otmar ks>=250)and( self.
tot
marks<=300):
self.grade="DISTINCTI ON"
eli
f(self.
totmar ks>=200)and( sel
f.t
otmarks<=249)
:
self.grade="FIRST"
eli
f(self.
totmar ks>=150)and( sel
f.t
otmarks<=199)
:
self.grade="SECOND"
eli
f(self.
totmar ks>=120)and( sel
f.t
otmarks<=149)
:
sel
f.
grade="
THI
RD"

defstoredtsudentdata(self)
:#Py thonDat aBaseCommuni cationcode
try:
con=cx_ Oracle.
connect ("
scott/t
iger
@local
host /orcl
")
cur=con.cursor()
#designt hequer yandexecut e
i
q="insertintoresultv al
ues(%d,'
%s',
%d,%d,
%d, %d,%f,'
%s'
)"
cur.
execut e(i
q
%(self
.sno,
sel
f.sname,self.
cm, self
.cppm,self.pytm,sel
f.t
otmarks,
sel
f.percent,
self
.gr
a
de))
con.commi t(
)
pri
nt("\n{}StudentRecor dInsertedi
nResultTabl e--
ver
if
y".
format(
cur.rowcount))
exceptcx_ Oracle.DatabaseEr r
orasdb:
pri
nt("Problem inDat abase:"
,db)

#mai nprogram
s=StudentMarksRepor t
()
s.
getstudentdetai
ls()
s.
decidegrade()
s.
storedtsudentdata(
)

1)Cl
asses

=>ThepurposeofCl assesConcepti sthat"Todev elopProgrammer( or


)Custom
Defi
nedDat atypesandt odev el
opanyr ealt i
meappl icati
on" .
=>ThePurposeofDev el
opingProgrammer( or)Cust om DefinedDatatypesi
sthat
"To
stor
eCust omizeddat aandtoper for
m cut omi zedoper ati
ons."
=>Todevelopprogrammerdef ineddat atypebyusi ngclassesconcept,weusea
keywordcall
ed" cl
ass".
=>Ever
yClassNamei sconsideredasPr ogrammerdef i
neddat atype.

=>Def
ini
ti
onofCl
ass:
=>AClassi
sacoll
ect
ionofDataMembersandMethods
=>Whenwedefi
neaclass,Memorywil
lnotcr
eat
ef orDatamember
sandMet
hods
butwhosememorywill
becreat
edwhenwecreat
eanobj ect
.
Sy
ntaxf
ordef
ini
ngacl
assi
npy
thon
cl
ass<ClassName>:
def i
nst ancemet hodname( self,
l
istofformalparamsi fany
):
-
----
---
---
--
---
--
--
--
--
--
---
--
---
---
---
--
--
---
-
--
--Specif
yInstanceDat aMember s-
--
-
--
->PerfomsSpeci ficOper ati
ons--
---
@classmet hod
defclassl evelmethodname( cl
s,li
stofformal paramsifany):
--
---
--
---
--
--
---
--
---
--
--
--
----
--
---
--
--
--
---
--
--
--Specif
yCl assLev elDataMember s--
--
--
->PerfomsCl assLev elOperati
ons--
---
@staticmet hod
defstaticmet hodname( l
istoff ormalparamsi fany):
--
---
--
---
--
--
---
--
---
--
--
--
----
--
---
--
--
--
---
--
--
--
--
---
--
Ut i
li
tyOperations---
--
--
---
--
--
--
--
---
--
---
--
---
--
--
---
--
---
--
--
--
----
--
---
--
--
--
---
--
--
--

Expl
anat
ion:

=>"cl
ass"isakeywor
d, whi
chisusedt odevel
opProgrammer -definedDat
aTy
pes.
=><classname>isoneofvalidv ari
ablenameandtreatedasCl assNameandEver
y
ClassNamei soneoftheProgrammer -
Defi
nedDataType.
=>InClassofPyt
hon,wecandef inetwotypesofdatamember s.Theyare
a)InstanceDat aMembers
b)ClassLev elDataMember s
=>InClassofPyt
hon,wecandef ineThreetypesofMet hods.Theyar e
a)InstanceMet hods
b)ClassLev elMethods
c)StaticMet hods

Ty
pesofDat
aMember
sinCl
ass

=>I
nacl
assofPy
thon,
wecandefinet
wot y
pesofTwoDat
aMember
s.Theyar
e
a)I
nstanceDat
aMember s
b)Cl
assLevelDataMembers

a)I
nst
anceDat
aMember
s

=>InstanceDatamember sar
eusedf orStoringSpecificValues
=>InstanaceDatamemebr smemoryspacecr eatedEveryTimewhenanobj ect
created.
=>InstanceDataMember smustbespecif i
edin3way s.Theyare
a)Throughanobjectname
b)ThoughInst
anceMet hodName
c)ThoughConstr
uct or
s.
=>InstanceDataMember sar
ealwaysav ail
ableinsideofobj ect
(al
soknownasobj
ect
l
eveldat
amember
s).
=>I
nstanceDat
aMembersmustbeaccessedw.r.
tobjectnameorsel
f
obj
name.instancedat
amembername
sel
f.
inst
ancedat amembername

b)Cl
assLev
elDat
aMember
s

=>ClassLevelDat
aMembersareusedf orStoringCommonVal ues.
=>ClassLevelDat
amemebrsmemor yspacecr eatedOnlyOnceI r
respect
ivenumber
ofobjects
created.
=>ClassLevelDat
aMembersmustbespeci fiedint woway s.Theyar e
a)Insi
deofCl assdef i
niti
on
b)Insi
deofCl assLev elMet hodDef i
niti
on
=>ClassLev el
DataMember
sarealway savailabletoalltheobj ectsbcoztheyar
e
common
=>ClassLevelDat
aMembersmustbeaccessedw. r.tClassNameorobj ectname
or
selforcl
s.
ClassName. ClassLev eldatamembername
ObjectName. ClassLev eldatamembername
self
.ClassLev eldatamembername
cl
s.ClassLev eldatamembername

#Thi
sprogram stor
esst
no,
nameandmar ks
#st
udentex1.
py
cl
assStudent
:pass#hereStudenti
scal
l
edProgr
ammer
-def
ineddat
aty
pe

#mai nprogram
s=Student()
pri
nt("
contentofs="
,s.
__di
ct_
_)# {}
pri
nt("
Numberofv al
uesins=",l
en(
s._
_di
ct_
_))

#Thi
sprogram stor
esst
no,
nameandmar ks
#st
udentex2.
py
cl
assStudent
:pass#hereStudenti
scal
l
edProgr
ammer
-def
ineddat
aty
pe

#mainpr ogr
am
s1=Student(
)
s2=Student(
)
pri
nt(
"Contentofs1bef
oreaddi
ngt
hedat
a="
,s1.
__di
ct_
_)
pri
nt(
"Contentofs2bef
oreaddi
ngt
hedat
a="
,s2.
__di
ct_
_)
pri
nt(
"-"
*50)
#addthedat atos1
s1.
sno=100
s1.
sname=" RS"
s1.
mar ks=22.22 #heresno,
snameandmarksarecall
edI
nstancedat
amembers
#addthedat atos2
s2.
sno=101
s2.
sname=" TR"
s2.
mar ks=33.33 #heresno,
snameandmar ksar
ecall
edInst
ancedatamember
s
pri
nt(
"Contentofs1af
teraddi
ngthedat
a="
,s1._
_di
ct_
_)
pri
nt(
"Contentofs2af
teraddi
ngthedat
a="
,s2._
_di
ct_
_)

#Thi
sprogram stor
esst
no,
nameandmar ks
#st
udentex3.
py
cl
assStudent
:pass#hereStudenti
scal
l
edProgr
ammer
-def
ineddat
aty
pe

#mainpr ogr am
s1=Student (
)
s2=Student (
)
pri
nt("
Cont entofs1bef oreaddi ngthedata="
,s1.
__di
ct_
_ )
pri
nt("
Cont entofs2bef oreaddi ngthedata="
,s2.
__di
ct_
_ )
pri
nt("
-"*
50)
#addt hedat at os1
s1.
sno=100
s1.
sname=" RS"
s1.
mar ks=22. 22 #her esno, snameandmar ksarecal
ledInstancedat
amembers
#addt hedat at os2
s2.
sno=101
s2.
sname=" TR"
s2.
mar ks=33. 33 #her esno, snameandmar ksarecall
edI nst
ancedatamember
s
pri
nt("
-"*
50)
pri
nt("
FirstSt udentI nf
or mat ion:")
pri
nt("
-"*
50)
pri
nt("
StudentNumber =",
s1. sno)
pri
nt("
StudentName=" ,s1. sname)
pri
nt("
StudentMar ks=",s1.mar ks)
pri
nt("
-"*
50)
pri
nt("
SecondSt udentInf ormat ion:"
)
pri
nt("
-"*
50)
pri
nt("
StudentNumber =",
s2. sno)
pri
nt("
StudentName=" ,s2. sname)
pri
nt("
StudentMar ks=",s2.mar ks)
pri
nt("
-"*
50)
#Thisprogr am st oresst no,nameandmar ks
#studentex4. py
cl
assSt udent :pass#her eSt udenti scal
l
edPr ogr
ammer -defi
neddatatype
#mainpr ogr am
s1=Student (
)
s2=Student (
)
pri
nt("
Cont entofs1bef oreaddi ngthedata="
,s1.
__di
ct_
_ )
pri
nt("
Cont entofs2bef oreaddi ngthedata="
,s2.
__di
ct_
_ )
pri
nt(
"-"
*50)
#addthedat atos1
pri
nt(
"EnterFir
stSt udentI nformat i
on")
pri
nt(
"-"
*50)
s1.
sno=int(i
nput("
Ent erSt udentNumber :
"))
s1.
sname=i nput("
Ent erSt udentName: "
)
s1.
mar ks=fl
oat(i
nput ("
Ent erStudentMar ks:"
)) #her
esno,
snameandmar
ksar
e
cal
ledInstancedatamember s
#addthedat atos2
pri
nt(
"EnterSecondSt udentI nformation")
pri
nt(
"-"
*50)
s2.
sno=int(i
nput("
Ent erSt udentNumber :
"))
s2.
sname=i nput("
Ent erSt udentName: "
)
s2.
mar ks=fl
oat(i
nput ("
Ent erStudentMar ks:"
)) #her
esno,
snameandmar
ksar
e
cal
ledInstancedatamember s
pri
nt(
"-"
*50)
pri
nt(
"Fir
stStudentI nformat ion:")
pri
nt(
"-"
*50)
pri
nt(
"StudentNumber =",s1.sno)
pri
nt(
"StudentName=" ,s1.sname)
pri
nt(
"StudentMar ks=" ,
s1.mar ks)
pri
nt(
"StudentCour se=" ,
s1.crs)
pri
nt(
"-"
*50)
pri
nt(
"SecondSt udentI nformat ion:"
)
pri
nt(
"-"
*50)
pri
nt(
"StudentNumber =",s2.sno)
pri
nt(
"StudentName=" ,s2.sname)
pri
nt(
"StudentMar ks=" ,
s2.mar ks)
pri
nt(
"StudentCour se=" ,
s2.crs)
pri
nt(
"-"
*50)

#Thi
sprogram st
oresst
no,
nameandmar ks
#st
udentex5.
py
cl
assStudent
:#her eSt
udenti
scal
ledProgr
ammer -
defi
neddat
aty
pe
cr
s="
PYTHON"#her ecrsi
scall
edClassLevel
Datamembers

#mainpr ogram
s1=Student ()
s2=Student ()
pri
nt(
"Cont entofs1bef or
eaddingthedata="
,s1.
__di
ct_
_)
pri
nt(
"Cont entofs2bef or
eaddingthedata="
,s2.
__di
ct_
_)
pri
nt(
"-"*50)
#addt hedat atos1
pri
nt(
"Ent erFir
stStudentI
nformati
on")
pri
nt(
"-"*50)
s1.
sno=i nt(i
nput("
EnterSt
udentNumber :
")
)
s1.
sname=i nput(
"EnterSt
udentName:")
s1.
mar ks=f l
oat(i
nput("
Ent
erStudentMarks:
")
) #her esno,
snameandmar
ksar
e
cal
ledI nstancedatamember s
#addt hedat atos2
pri
nt("EnterSecondSt udentI nfor mati
on")
pri
nt("-"
*50)
s2.sno=int(i
nput(
"Ent erSt udentNumber :")
)
s2.sname=i nput
("Ent erSt udentName: "
)
s2.mar ks=fl
oat(
input ("
Ent erStudentMar ks:
")
) #heresno,
snameandmar
ksar
e
call
edI nstancedatamember s
pri
nt("-"
*50)
pri
nt("Fir
stStudentI nformat ion:")
pri
nt("-"
*50)
pri
nt("StudentNumber =",s1.sno)
pri
nt("StudentName=" ,s1.sname)
pri
nt("StudentMar ks=" ,
s1.mar ks)
pri
nt("StudentCour se=" ,
Student .crs)#accessingCl
assLev
elDat
aMember
sw.r
.t
ClassName
pri
nt("-"
*50)
pri
nt("SecondStudentI nformat ion:")
pri
nt("-"
*50)
pri
nt("StudentNumber =",s2.sno)
pri
nt("StudentName=" ,s2.sname)
pri
nt("StudentMar ks=" ,
s2.mar ks)
pri
nt("StudentCour se=" ,
Student .crs)#accessingCl
assLev
elDat
aMember
sw.r
.t
ClassName
pri
nt("-"
*50)

#Thi
sprogram storesst no,nameandmar ks
#st
udentex6.
py
cl
assStudent:
def r
eadst uddat a(sel
f):
print
("-
"* 50)
self.
sno=i nt(i
nput("EnterStudentNumber :")
)
self.
sname=i nput(
"EnterSt udentName: "
)
self.
mar ks=f l
oat(i
nput( "
EnterStudentMar ks:
")
)
print
("-
"* 50)
defdispstuddat a(self
):
print
("-
"* 50)
print
("StudentNumber :{
}".
format(self
.sno))
print
("StudentName: {}".
format(self
.sname) )
print
("StudentMar ks:{
}".
format(self.
mar ks))
print
("-
"* 50)

#mainprogr
am
s1=St
udent(
)
s2=St
udent(
)
pri
nt(
"EnterFir
stStudentInformat i
on:")
s1.
readstuddata()
pri
nt(
"EnterSecondSt udentInformation:"
)
s2.
readstuddata()
pri
nt(
"Fi
rstStudentInformation:")
s1.
dispstuddata()
pri
nt(
"SecondSt udentInf
ormat ion:"
)
s2.
dispstuddata()

#Thi
sprogr am st
oresst no,nameandmar ks
#st
udentex7.py
cl
assStudent:
crs="
PYTHON"#Cl assLevel Dat aMember s
def readstuddat a(sel
f):#I nstanceMet hod
print
("-
"* 50)
self.
sno=i nt(i
nput("EnterStudentNumber :")
)
self.
sname=i nput(
"Ent erStudentName: "
)
self.
mar ks=f l
oat(i
nput ("
EnterStudentMar ks:
"))
#her esel f
.sno,sel
f.sname, self
.mar ksarecalledInst
anceDat
a
members.
print
("-
"* 50)
defdispstuddat a(self
):#I nstanceMet hod
print
("-
"* 50)
print
("StudentNumber :{
}".
format(self.
sno))
print
("StudentName: {
}".
format(self
.sname) )
print
("StudentMar ks:{
}".f
ormat(self.marks))
print
("StudentCour se:{}
".f
ormat(Student.crs)
)
print
("-
"* 50)

#mainpr ogr
am
s1=Student(
)
s2=Student(
)
pri
nt(
"EnterFir
stStudentInformat i
on:")
s1.
readstuddata()
pri
nt(
"EnterSecondSt udentInformation:"
)
s2.
readstuddata()
pri
nt(
"Fir
stStudentInformation:")
s1.
dispstuddata()
pri
nt(
"SecondSt udentInf
ormat ion:"
)
s2.
dispstuddata()
Ty
pesofMet
hodsi
nCl
assofPy
thon

=>InPy
thonPr
ogr
ammi
ng,wecandefi
ne3Ty pesofMet
hodsi
nsi
deofCl
ass.They
are: 1)I
nstanceMethod
2)Cl
assLevelMethod
3)St
aticMethod.

1)Inst
anceMet hod:
=>Inst
anceMet hodsareusedf orPerformingSpeci f
icOperatonsont hedat
aof
object
andHenceI nst
anceMet hodsarecal l
edObj ectLevel Met
hods.
=>Inst
anceMet hodsal
way sTakes" self
"asFi rstPosit
ionalParametersf
orobt
aini
ng
i
dofCur rentCl
assobject.
=>Syntax:
-
def InstanceMethodName( self,
li
stofformal par
ams):
-
--
--
--
---
--
--
---
--
--
--
--
---
--
--
---
--
----
--
---
--
Specifi
cOper ati
ons---
--
--
--
---
--
--
--
--
--
---
---
--
--
--
--
--
----
--
--
--
=>I
nst
anceMet
hodsofaCl assmustbeaccessedw.
r.
tobj
ectnameorsel
f
obj
ectname. I
nst
anceMethodName(
)
(or)
sel
f.
InstanceMethodName()

Whati sself:
=>selfisoneoft hei
mpl i
citobj
ectusedasaFi
rstf
ormalpar
ameteri
nthedef
ini
ti
on
ofInstanceMet hod
=>Thesel fcont
ainsIdormemor yaddr
essorr
efer
enceofCurr
entCl
assobj
ect.
=>selfisappli
cableforobject
sonly.

2)ClassLev elMethod:
=>ClasslevelMet hodsareusedf orPerformingCl assLev elOperat
onsSuchas
Specify
ingCl assLevelDataMember sandPer f
or msoper ationsonthem (i
frequir
ed)
.
=>ClassLev elMethodsalway sTakes" cls"asFirstPositionalParameter
sfor
obtaini
ngCur rentCl
assName.
=>EveryClassLev elMethodmustbepr ecededwi thapr e-defi
neddecorat
orcal l
ed
@classmet hod
=>Syntax:
-
@classmet hod
def ClassLev el
Met hodName( cl
s, l
i
stoff ormalparams):
-
--
---
--
--
---
--
---
---
--
--
--
---
--
--
--
---
--
--
--
---
CommonOper at
ions---
---
-
--
--
---
--
---
---
--
--
--
----
--
--
--
--
--
- -
--
--
=>EveryClassLev elMethodcanbeaccessedw. r.
ttoCl assNameorcl sorobj ect
nameorsel f

Cl
assName. ClassLevelmethodName(
)
(OR)
cl
s.ClassLevelmethodName( )
(OR)
obj
ect name.Cl
assLev el
methodName(
)
(OR)
sel
f.ClassLevelmethodName()

Whati
scl
s:

=>cl
sisoneoft hei mpli
citobj
ectusedasaFir
stformal
parameteri
nthedefi
nit
ion
ofClassLevelMet hod
=>TheclscontainsNameofCur rentCl
ass
=>cl
sisapplicableforClassLevelDataMembersandClassLev
elMethodsonl
y.

3)St
ati
cMet
hod:

=>Stati
cMethodsareusedf orPerfor
mingUti
li
tyorUniver
salOper
atonsSuchas
cal
uclator
,di
spl
ayingthedat aofanyobnj
ectetc.
=>tati
cMethodsneitherTakes"cl
s"nortakes"sel
f"asFir
stPosi
ti
onalPar
ameter
s
butitmaytakeanotherobject(
s).
=>Ever
yStati
cMethodmustbepr ecededwithapr e-
defi
neddecor at
orcal
l
ed
@stati
cmethod
=>Synt
ax:
-
@stat
icmethod
def Stati
cMethodName( l
istoffor
mal paramsifany)
:
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
-
-
--
--
--
Util
i
tyorUniversalOperat
ions--
--
--
-
-
--
--
--
--
--
--
---
--
--
--
--
--
--
---
--
--
--
--
--

=>Ev
erySt
ati
ccanbeaccessedw.r
.tt
oCor r
espondi
ngCl
assNameorobj
ectname
ClassName.
stati
cmethodName()
(
OR)
object
name.st
ati
cmet hodName(
)

#Progr
am forcalcul
atingSi mpl eI nterestbyusingCl assesandObj
ect
s
#Si
mpleInt.
py
cl
assSimpleInt
:
defreadval
ues( sel f
):
sel
f.p=float(input (
"EnterPrinci
pleAmount :"
))
sel
f.t=float(i
nput ("
Ent erTime:"
))
sel
f.r=float(i
nput ("
Ent erRateOfInterest:
")
)
defcalSimpleInt(self):
sel
f.si=(self.
p* self
.t*self
.r)
/100
def di
spresult(self):
pri
nt("="*50)
pri
nt("PrincipleAmount :
{}
".
format(self
.p)
)
pri
nt("Time: {}".
format (self
.t
))
pri
nt("Rat eofInt erest:{}
".
format(sel
f.r
))
pri
nt("Simpl eInterest :
{}
".f
ormat(self
.si
))
pri
nt("="*50)

#mai nprogram
si
=Si mpleInt
()
si
.readvalues()
si
.calSi
mpl eInt
()
si
.dispr
esul t
()

#Progr
am forcal cul
ati
ngSi mpleInterestbyusi
ngCl assesandObject
s
#Si
mpleInt1.py
cl
assSimpl eI
nt:
defr eadval
ues(self)
:
sel
f.
p=float(
input(
"EnterPri
nci
pleAmount :
")
)
sel
f.
t=fl
oat(i
nput("
EnterTime:"
))
sel
f.
r=fl
oat(i
nput("
EnterRateOfInterest
:"
))
sel
f.
calSimpleInt
()
sel
f.
dispresult
() #OneI nst
anceMet hodcall
inganot
herI
nst
ance
Method

defcal
Simpl
eInt
(sel
f):
sel
f.
si=(
self
.p*
sel
f.
t*sel
f.
r)
/100
def di
spresul
t(self)
:
pri
nt(
"="*50)
pri
nt(
"Princi
pleAmount :
{}".
format(
self
.p))
pri
nt(
"Time: {}
".f
ormat(
self.t
))
pri
nt(
"Rat eofInter
est:
{}"
.format(
self
.r)
)
pri
nt(
"SimpleInterest
:{
}".
format(
self.
si)
)
pri
nt(
"="*50)

#mainprogram
si
=SimpleInt
()
si
.r
eadvalues()

#Thisprogram demonst art


esaboutcl
assLevelmethod
#ClassLevel
Met hodEx1.py
cl
assEmpl oy ee:
@cl assmethod
defget compnames( cls)
:
cl
s.cname="IBM"#ClassLevelDataMember
@cl assmethod
defget comploc(cl
s):
cl
s.cl
oc="HYD"#Cl assLevelDat
aMember

defget
empdet (self)
:
pri
nt("
-"*
50)
sel
f.eno=int(
input(
"EnterEmpl
oyeeNumber:
"))
sel
f.ename=i nput
("EnterEmpl
oyeeName:"
)
sel
f.sal
=float(i
nput("
EnterEmpl
oyeeSal
ary
:")
)
pri
nt("
-"*
50)

defdi spempdet ( self):


pri
nt("
-"*50)
pri
nt("
Empl oyeeNumber :
{}".
format(self
.eno)
)
pri
nt("
Empl oyeeName: {
}".
format(self
.ename))
pri
nt("
Empl oyeeSal ar
y:{
}".
format(self.
sal)
)
pri
nt("
Empl oyeeCompName: {
}".
format(Employee.cname)
)
pri
nt("
Empl oyeeCompLoc: {
}".
for
mat (Employee.cl
oc))
pri
nt("
-"*50)
#mainpr ogram
Employee.getcompnames( )
Employee.getcomploc()#cal li
ngCl assLev elMethods
e1=Employ ee()
e2=Employ ee()
pri
nt(
"EnterFirstEmploy eeI nformation:")
e1.
getempdet ()
pri
nt(
"EnterSecondEmpl oy eeInformation:"
)
e2.
getempdet ()
pri
nt(
"\nFir
stEmpl oyeeInf ormation:
")
e1.
dispempdet ()
pri
nt(
"\nSecondEmpl oyeeI nformati
on:")
e2.
dispempdet
()

#Thisprogram demonst art


esaboutclassLevel met hod
#ClassLevel
Met hodEx2.py
cl
assEmpl oy ee:
@cl assmethod
defget compnames( cls):
cl
s.cname="IBM"#Cl assLev el DataMember
cl
s.getcomploc()#orEmpl oy ee.get
compl
oc(
)-
--
cal
l
ingCl
ass
LevelMethodf rom anotherClassLev
el Met
hod
@cl assmethod
defget comploc(cls)
:
cl
s.cl
oc="HYD"#Cl assLevel DataMember

defget empdet (sel f):


pri
nt("-
"*50)
sel
f.eno=i nt(i
nput ("
Ent erEmpl oy eeNumber :
"))
sel
f.ename=i nput (
"Ent erEmpl oy eeName: "
)
sel
f.sal=f loat(input("EnterEmpl oyeeSal ary
:")
)
pri
nt("-
"*50)
defdi spempdet (sel f
):
pri
nt("-
"*50)
pri
nt("Empl oy eeNumber :{
}".
format (self
.eno))
pri
nt("Empl oy eeName: {
}".
format (self
.ename) )
pri
nt("Empl oy eeSal ar y
:{}
".
format (
self.
sal)
)
pri
nt("Empl oy eeCompName: {}
".format(Employee.cname)
)
pri
nt("Empl oy eeCompLoc: {}".
for mat(Employee.cl
oc))
pri
nt("-
"*50)
#mainpr ogr am
Employee.get compnames( )
e1=Employ ee( )
e2=Employ ee( )
pri
nt("
EnterFi rstEmpl oy eeI nformat i
on: ")
e1.
getempdet (
)
pri
nt("
EnterSecondEmpl oy eeI nformat i
on:"
)
e2.
getempdet (
)
pri
nt("
\nFir
stEmpl oyeeI nf ormat i
on:")
e1.
dispempdet ()
pri
nt("
\nSecondEmpl oyeeI nfor mation: "
)
e2.
dispempdet ()
#Thisprogr am demonst ar tesaboutcl assLev elmet hod
#ClassLevelMet hodEx3. py
cl
assEmpl oy ee:
@cl assmet hod #Pr e-defineddecor at or
defget compnames( cls):
cl
s.cname=" IBM"#Cl assLev el DataMember
@cl assmet hod
defget compl oc( cls):
cl
s.cloc=" HYD"#Cl assLev el Dat aMember
defget empdet(sel f):
pri
nt("
-"*50)
sel
f.eno=i nt(i
nput (
"Ent erEmpl oyeeNumber :
"))
sel
f.ename=i nput (
"EnterEmpl oyeeName: "
)
sel
f.sal=f loat(input("EnterEmpl oyeeSal ary
:")
)
pri
nt("
-"*50)
defdi spempdet ( sel f
):
pri
nt("
-"*50)
pri
nt("
Empl oy eeNumber :
{}".
format(self
.eno))
pri
nt("
Empl oy eeName: {
}".
format(self
.ename) )
pri
nt("
Empl oy eeSal ary:{
}".
format (
self.
sal)
)
sel
f.getcompnames( )
sel
f.getcompl oc()#cal li
ngCl assLev elMethodsfrom Inst
ance
Methods
pri
nt("
Empl oy eeCompName: {
}".
format(Employee.cname))
pri
nt("
Empl oy eeCompLoc: {}".
format(Employee.cl
oc))
pri
nt("
-"*50)
#mainpr ogram
e1=Employ ee(
)
e2=Employ ee(
)
pri
nt(
"EnterFir
stEmpl oy eeI nformat i
on: ")
e1.
getempdet ()
pri
nt(
"EnterSecondEmpl oy eeI nformat ion:"
)
e2.
getempdet ()
pri
nt(
"\nFir
stEmpl oyeeInf ormat i
on:")
e1.
dispempdet ()
pri
nt(
"\nSecondEmpl oyeeI nfor mation:")
e2.
dispempdet ()

#Thisprogram demonst rat


esaboutcl assLevelmethod
#ClassLevel
Met hodEx4.py
cl
assEmpl oy ee:
@cl assmethod #Pr e-def
ineddecorator
defget compnames( cls)
:
cl
s.cname="IBM"#Cl assLevelDataMember
@cl assmethod
defget comploc(cl
s):
cl
s.cl
oc="HYD"#Cl assLev elDat
aMember

defgetempdet(self)
:
pri
nt("
-"*
50)
sel
f.eno=int(
input(
"EnterEmpl oyeeNumber :
"))
sel
f.ename=i nput
("EnterEmpl oyeeName: "
)
sel
f.sal
=float(i
nput("
EnterEmpl oyeeSal ary
:")
)
pri
nt("
-"*
50)
defdispempdet (
self):
pri
nt("
-"*
50)
pri
nt("
Empl oyeeNumber :
{}".
format(self
.eno))
pri
nt("
Empl oyeeName: {
}".
format(self
.ename) )
pr
int
("
EmployeeSal
ary
:{}
".
for
mat (
self
.sal)
)
pr
int
("
EmployeeCompName: {}
".
format(Empl
oyee.cname)
)
pr
int
("
EmployeeCompLoc:{}
".
format(Employ
ee.cl
oc))
pr
int
("
-"
*50)
#mainpr ogram
e1=Employ ee(
)
e2=Employ ee(
)
pri
nt(
"EnterFirstEmpl oyeeInformati
on:")
e1.
getempdet ()
pri
nt(
"EnterSecondEmpl oyeeInf
ormat i
on:"
)
e2.
getempdet ()
#call
i
ngcl assl evelmet hodsw. r.
tobjectname
e1.
getcompnames( )
e2.
getcompl oc()
pri
nt(
"\nFir
stEmpl oy
eeInf ormati
on:")
e1.
dispempdet ()
pri
nt(
"\nSecondEmpl oyeeI nf
ormation:"
)
e2.
dispempdet ()

obj
ect
sinPy
thon

=>Whenwedefineaclass,
memor yspaceisnotcreatedforDataMembersand
Methodsbutwhosememor yi
screatedwhenwecr eateanobjectw.r.
tcl
assname.
=>TodoanyDataProcessi
ng,
Iti
smandat orytocreateanobject.
=>Tocreat
eanobject
,ther
emustexistsaclassDefini
ti
onotherwiseweget
NameError

Def
ini
ti
onofobj
ect:
=>I
nst
anceofaclassiscall
edobj
ect(I
nst
anceisnot
hingbutall
ocat
ingsuf
fi
cient
memoryspacef
ort heDataMembersandMethodsofaclass)

Synt
axforcreati
nganobj ect
var
name=classname(
)
Exampl
es:cr eat
eanobj ectofSt
udent
so=Student
()
Exampl
e:-createanobjectEmployee
eo=Employee()

Di
ff
erencebet
weencl
assesandobj
ect
:
Class:
1)Acl assisacoll
ect
ionofDat aMember sandMethods
2)Whenwedef i
neacl ass,memoryspaceisnotcreatedforDat
aMember sand
Met hodsanditcanbet r
eatedasspecif
icat
ion/model forr
ealt
imeappl
icati
on.
3)Def i
nit
ionofapart
icularexi
stsonl
yonce
4)Whenwedev elopanyPr ogr
am wit
hOOPspr inci
ples,
ClassLoadedFi
rstonl
yonce
i
nmai nmemor y.

Objects:
1)Instanceofaclassiscall
edObj ect
2)Whenwecr eat
eanobj ect,wegetthememor yspaceforDatamembersand
Met hods.
3)w.r.
tOneclassDefini
ti
on,wecancr eat
emult
ipl
eobjects.
4)wecancr at
eanobj ectaft
erloadingthecl
assdefi
nit
ionother
wiseweget
NameEr ror

Const
ruct
orsi
nPy
thon

=>Thepur poseofConstructori
sthat"ToInit
ial
iz
et heObjectwhenanobj ect
created".
=>Init
iali
zi
ngtheobjectisnothi
ngbutplacingourownv alueswithoutleavi
ngthe
objectempt ywhenanobj ectiscreat
ed.
Def i
nit
ion:
=>AConst r
uct
orisoneoft heSpecialMethod,whichisautomatical
lyorimplci
tl
y
calledbyPVM duringObjectCreati
onandwhosepur poseisthattoplaceourown
valueswi t
houtl
eavingtheobjectempty(Init
li
zati
onofobj ect)
.

Sy
ntaxf
ordef
ini
ngconst
ructorinclass:
def __i
nit
__(sel
f,li
stoff ormalparamsifany
):
-
--
--
--
--
---
--
---
--
--
---
--
---
--
---
-
--
--
--
---
--
--
---
--
--
---
--
---
--
---
--
BlockofSt atement s-
-I
nit
li
zat
ion
--
--
--
---
--
--
---
--
--
---
--
---
--
---
--
--
--
--
---
--
--
---
--
--
---
--
---
--
---
--

Properti
es/rules/Character
isti
csofConst r
uctor:
--
--
---
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
-
1.TheConst r
uctorwillaut
omat ical
ly/impli
cit
lycall
edbyPVM dur
ingobj
ect
creati
on
2.TheConstruct
orsareusedf orIni
ti
ali
zi
ngObjects
3.TheNameoft heconstr
uctorisalways __i
nit
__(sel
f,
..
..
..
..
.)
5.Constr
uctorswil
lnotreturnval
ue.
4.Constr
uctorsarealwaysParti
cipati
nginI
nheri
tance.
5.Constr
uctorscanbeOv erri
dden
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
---
--
--
--

Ty
pesofConst
ruct
orsi
nPy
thon

=>I
nPy
thonPr
ogr
ammi
ng,
wehav
etwot
ypesofConst
ruct
ors.Theyar
e

1.Def
aul
torParameter
-Lessorno-
argumentConst
ruct
or
2.Par
ameter
izedConst
ructor

1.Def aultorParameter -
Lessorno- argumentConst ruct or:
=>Def i
ni t
ion:-Aconstructorissai dtobeDef aultifandonl yifI
tneverTakesany
Formal
--
---
--
---
----
--
- Par ameters( exceptsel f
).
=>Thepur poseofDef aultConst ructoristhat"ToI niti
ali
zet hemul t
ipl
eobject
sof
samecl asswi thsameVal ues".
=>Sy ntax:- def _ _ i
nit_
_ (
sel f
):#Def aultConst ructor
---
--
----
--
--
--
--
---
---
---
---
---
Blockofst atement --
Init
li
zat
ion-
---
--
----
--
--
--
--
---
---
---
---
-
Exampl es:
--
---
--
---
----
--
--
-
#Test Ex1.py
classTest :
def__i
nit
__(
self):#Const r
uct ors-
-ObjectInitl
ization
pri
nt("
iam f rom Def aultConstructor")
sel
f.a=10
sel
f.b=20
pri
nt("
="*50)
pri
nt("
Val ofa={ }"
.format (
self
.a))
pri
nt("
Val ofb={ }"
.format (
self.
b))
pri
nt("
="*50)
#mai npr ogram
t1=Test () #obj ectcreati
on
t2=Test () #objectcr eation
t3=Test () #obj ectcreati
on

b)Parameteri
zedConst r
uctor
=>ThepurposeofParamet eri
zedConstructori
sthat"Toi
nit
li
zet
hemul t
ipl
eobj
ect
s
ofsameclasswi thdi
ffer
entv al
ues"
.
=>Aconstruct
orissaidtobePar ameter
izedifandonl
yifI
tal
waystakes
parameter
(s)alongself.

=>Sy
ntax: def __i
nit
__(sel
f,l
istoff
ormal
par
eams)
:
-
--
--
--
--
--
--
--
--
---
--
--
--
---
-
-
--
--
--
--
--
--
--
--
--
---
--
--
--
--
Bl
ockofstatements--
Ini
tl
izat
ion
-
--
--
--
--
--
--
--
--
--
---
--
--
--
--
-
--
--
--
--
--
--
--
--
--
---
--
--
--
--
Exampl es:
--
---
--
--
--
---
--
--
--
#TestEx2.py
classTest:
def__i
nit
__(
self,
a,
b):#Const ructor
s--ObjectI
nit
li
zati
on
pri
nt("
iam f
rom Paramet er
izedConstructor
")
sel
f.a=a
sel
f.b=b
pri
nt("
="*
50)
pri
nt("
Valofa={}"
.f
ormat(self
.a))
pri
nt("
Valofb={}"
.f
ormat(self.
b))
pri
nt("
="*
50)
#mai nprogram
t1=Test(10,
20) #objectcreat
ion
t2=Test(100,
200) #objectcr
eati
on
t3=Test(1,
2) #objectcreati
on

Note:I
nCl assofPyt
hon,wecan'tdefi
nebothdefaultandPar ameter
ized
constr
uctorsbcozPVM canrememberonl yl
atestconstructor(
duetoi t
s
i
nterpr
etationPr
ocess).Toful
lfi
llt
heneedofbot hdefaultandparamet er
ized
constr
uctors,wedefi
nesingl
econstruct
orwithdefaultparametermechani sm.

#TestEx4.py
classTest:
def_ _
ini
t__
(self,
a=1,
b=2):#Const ructors-
-Obj
ectI
nit
li
zati
on
print
("iam f
rom Defaul
t/Par ameteri
zedConstr
uctor"
)
self.
a=a
self.
b=b
print
("="*
50)
print
("Valofa={}"
.f
ormat(
self.a)
)
print
("Valofb={}"
.f
ormat(
self.b)
)
print
("="*
50)
#mai nprogram
t1=Test(
) #objectcr
eat
ion
t2=Test(
100,200) #objectcr
eati
on
t3=Test(
20,30)

#StudEx
1.py
cl
assStudent:
def_
_ini
t__
(sel
f):#Construct
ors
print
("
iam f
rom Constr
uctor
")
#mai nprogram
s=Student() #obj ectcreati
on
pri
nt("
cont entofsdur ingobj ectcreation=" ,
s.__dict__)
#StudEx2.py
cl
assSt udent :
def__init
__(sel f):#Const ructor s--ObjectI ni
tl
izati
on
print("iam from Const r uct or")
self.sno=10
self.name=" Raj"
self.mar ks=44.44
#mai nprogram
s=Student() #obj ectcreati
on
pri
nt("
cont entofsdur ingobj ectcreation=" ,
s.__dict__)
#StudEx3.py
cl
assSt udent :
def__init
__(sel f):#Const ructor s--ObjectI ni
tl
izati
on
print("iam from Def aultConst ructor"
)
self.sno=i nt
(i
nput("Ent erSt udentNumber :")
)
self.name=i nput("EnterSt udentName: ")
#mai nprogram
s1=Student (
) #obj ectcreati
on
pri
nt("
cont entofs1dur i
ngobj ectcreat i
on=" ,s1.__dict
__)
s2=Student (
) #obj ectcreati
on
pri
nt("
cont entofs2dur i
ngobj ectcreat i
on=" ,s2.__dict
__)
#StudEx4.py
cl
assSt udent :
def__init
__(sel f,
sno,sname) :#Const ructors--
ObjectIni
tl
izat
ion
print("iam from Par amet er i
zedConst ructor
")
self.sno=sno
self.name=sname
defdi spstuddet (
self)
:
print("="*50)
print("StudentNumber ={ }".
format (self
.sno))
print("StudentName={ }".format (self.
name) )
#mai nprogram
s1=Student (
10,"Rossum" ) #obj ectcr eation
s2=Student (
20,"Gosl i
ng" ) #obj ectcr eat i
on
s3=Student (
30,"Travis") #obj ectcr eat i
on
s1.
dispstuddet ()
s2.
dispstuddet ()
s3.
dispstuddet ()

#StudEx
5.py
cl
assStudent:
def_
_ini
t__
(self,
sno,
sname):#Constr
uct
ors-
-Obj
ectI
nit
li
zat
ion
print
("iam f
rom Par
amet
eri
zedConstr
uct
or")
self.
sno=sno
self.
name=sname
print
("="*
50)
pr
int
("
StudentNumber
={}".
for
mat(self
.sno)
)
pr
int
("
StudentName={
}".
format(
self
.name))
pr
int
("
="*50)
#mainprogr
am
s1=St
udent(
10,
"Rossum") #objectcreat
ion
s2=St
udent(
20,
"Gosli
ng") #obj
ectcreati
on
s3=St
udent(
30,
"Trav
is") #obj
ectcreati
on

#TestEx1.py
classTest:
def__i
nit
__(
self):#Const ructors-
-ObjectI
nit
li
zati
on
pri
nt("
iam from DefaultConstructor
")
sel
f.a=10
sel
f.b=20
pri
nt("
="*50)
pri
nt("
Val ofa={}
".
format (
sel
f.a))
pri
nt("
Val ofb={}
".
format (
sel
f .
b))
pri
nt("
="*50)
#mai nprogr
am
t1=Test(
) #objectcr
eat
ion
t2=Test(
) #objectcreation
t3=Test(
) #obj ectcreati
on

#TestEx2.py
classTest:
def_ _
ini
t__
(self,
a,
b):#Const ructor
s--ObjectI
nit
li
zati
on
print
("iam f
rom Paramet er
izedConstructor
")
self.
a=a
self.
b=b
print
("="*
50)
print
("Valofa={}"
.f
ormat(self
.a))
print
("Valofb={}"
.f
ormat(self.
b))
print
("="*
50)
retur
n( sel
f.
a+self.
b)
#mai nprogram
t1=Test(
10,20) #objectcreat
ion
t2=Test(
100,200) #objectcr
eati
on
t3=Test(
1,2) #objectcreati
on

#Test
Ex3.
py
cl
assTest
:
def_
_ini
t__
(self,
a,
b):#Const ruct
ors-
-ObjectI
nit
li
zati
on
print
("iam f
rom Parameteri
zedConstructor
")
self.
a=a
self.
b=b
print
("="*
50)
print
("Valofa={
}".
format(
self
.a)
)
print
("Valofb={
}".
format(
self
.b))
pr
int
("
="*
50)
#mai nprogr am
print
("
Ent erTwoVal uef orFirstObject:
")
x=int
(input())
y=int
(input())
t1=Test(x,y) #objectcreation
print
("
Ent erTwoVal uef orSecondObj ect:
")
t2=Test(fl
oat (
input())
, f
loat(i
nput(
))) #obj ectcreation
print
("
Ent erTwoVal uef orThi r
dObj ect
:"
)
t3=Test(i
nput (),i
nput()) #obj ectcreation
#TestEx4. py
classTest :
def_ _ini
t__(
self,a=1,
b=2):#Const r
uctor s-
-ObjectIni
tl
izati
on
pri
nt("
i am from Defaul
t/Par amet erizedConst r
uctor"
)
sel
f.a=a
sel
f.b=b
pri
nt("
=" *
50)
pri
nt("
Val ofa={}".
format(
self.a))
pri
nt("
Val ofb={}".
format(sel
f.b))
pri
nt("
=" *
50)
#mai nprogr am
t1=Test() #objectcr
eat
ion
t2=Test(100,200) #obj ectcreati
on
t3=Test(20,30)

Dest
ruct
orsi
nPy
thon
=>Weknowt hatGarbageCol l
ectorisoneoft hei n-builtprogr am i
npy t
hon, whichis
runni
ngbehindofev erypy thonpr ogram andwhosei sr oleist ocoll
ectun- used
memor yspaceandi timpr ovest heperformanceofpy thonbasedappl i
cations.
=>EveryGarbageCol lectorPr ogram isinternallycal l
i
ngDest ructorpr ogram
=>Thedestructornamei npy thoni s def_ _
del_ _(sel
f).
=>Thedestructoralway scal l
edbyGar bageCol lectorwhent hepr ogram execut ed
completedf orde-
allocat i
ngt hememor yspace. wher easconst r
uctorcal l
edByPVM
i
mpl i
cit
lywhenobj ectiscr eatedf orini
ti
alizingt heobj ect.
=>Whent heprogram execut i
oni scompl eted, GCcal l
si tsowndest ructortode-
all
ocatethememor yspaceofobj ectspresenti npr ogram. (
aut omaticall
yGCr unni
ng)
=>Hence, Wehav eTHREEpr ogrammi ngcondi tionsf orcal l
ingGC andt omaket he
garbagecoll
ectortocal ldest ructorFunctions.

a)Bydefaul
twhent heprogr
am executi
oncompl et
ed.
b)Maketheobj
ectrefer
eenceasNonebyFor cef
ull
y
Synt
ax:obj name=None
c)del
etet
heobjectbyusingdelbyForcefull
y
Synt
ax:-delobj name
=>Sy
ntax:
def __del
__(self
):
-
--
--
--
--
--
--
---
--
--
--
-
-
--
--
--
---
--
---
--
--
--
--
Gar
bageCol
l
ect
or

=>Gar
bageCol
l
ectorcontai
nsapr e-
defi
nedmodulecal
led"
gc"
=>Her
egccont
ainsthefoll
owingcontai
nsthef
oll
owingFunct
ions.
1)isenabl
ed()
2)enable(
)
3)disabl
e()

#gcex1.py
i
mpor tgc
pri
nt(
"isGCenabled=",
gc.isenabled())#Tr ue
pri
nt(
"\nThisi
sapy t
honcl ass")
gc.
disable(
)
pri
nt(
"isGCenabledafterdisabl
e( )=",
gc.
isenabl
ed())#Fal
se
pri
nt(
"\nGoingonDestructorConcept :
")
gc.
enable()
pri
nt(
"isGCenabledafterenable()=",
gc.i
senabled(
))#True
pri
nt(
"\nThisi
sOOPs" )

#Program f
ordemonst rati
ngFunctionalit
yofDestruct
or.
#gcex2.py
i
mpor ttime,
gc
cl
assEmpl oyee:
def__i
nit
__(self
,eno,
ename) :
sel
f .
eno=eno
sel
f .
ename=ename
pri
nt("\
t{}\
t{}
".
for
mat (self
.eno,
sel
f.
ename))
def_ _
del__
(self):
pri
nt("\
nDest r
uct
orcal l
edbyGar bageColl
ect
or"
)

#mainm pr ogram
pri
nt(
"isGCenabl ed=",
gc.isenabl
ed())#Tr ue
pri
nt(
"Program executi
onst art
ed:
")
gc.di
sable()
pri
nt(
"isGCenabl edafterdisabl
e()=",
gc.
isenabl
ed(
))#Fal
se
eo1=Empl oyee(10,
"RS"
)
eo2=Empl oyee(20,
"DR"
)
eo3=Empl oyee(30,
"TR"
)
pri
nt(
"Program executi
onended" )
ti
me.sleep(5)

#Program f
ordemonst
rat
ingFunct
ional
i
tyofDest
ruct
or.
#destex1.
py
i
mpor ttime
cl
assEmpl oyee:
def__ini
t__(self
,eno,
ename) :
self.
eno=eno
self.
ename=ename
pri
nt("\
t{}\
t{}
".f
ormat(sel
f.
eno,
sel
f.
ename))
def_ _del__(
self):
pri
nt("\
nDest r
uctorcall
edbyGarbageCol
l
ector
")
#mainm pr ogram
pri
nt(
"Program execut ionstarted:"
)
eo1=Empl oyee(10,"RS")
eo2=Empl oyee(20,"DR")
eo3=Empl oyee(30,"TR")
pri
nt(
"Program execut ionended" )
ti
me.sleep(5)

#Program f
ordemonst rati
ngFunctionalit
yofDestruct
or.
#destex2.
py
i
mpor tti
me
cl
assEmpl oyee:
def__i
nit
__(
self,eno,
ename) :
sel
f.eno=eno
sel
f.ename=ename
pri
nt("
\t{}\
t{}
".
for
mat (sel
f.eno,
sel
f.
ename))

#mainm pr ogram
pri
nt(
"Program execut ionstarted:"
)
eo1=Empl oyee(10,"RS")
eo2=Empl oyee(20,"DR")
pri
nt(
"Program execut ionended" )
ti
me.sleep(5)
#Program fordemonst rati
ngFunct i
onalit
yofDestruct
or.
#destex3.py
i
mpor ttime
cl
assEmpl oyee:
def__ini
t__(self
,eno,
ename) :
self.
eno=eno
self.
ename=ename
pri
nt("\
t{}\
t{}
".f
ormat(sel
f.eno,
sel
f.
ename))
def_ _del__(
self):
pri
nt("\
nDest r
uctorcall
edbyGar bageColl
ect
or"
)
#mainm pr ogram
pri
nt(
"Program execut ionstart
ed:"
)
eo1=Empl oyee(10,"RS")
eo2=Empl oyee(20,"DR")
eo3=Empl oyee(30,"TR")
#nolongeri nt
erestedt omai nt
ainobj
ecteo1
pri
nt(
"nolongeri nterestedt
omai ntai
nobjecteo1:")
eo1=None #Her et hememor yspaceeo1collectedbyGC-f
orcef
ull
y
ti
me.sleep(5)
#nolongeri nt
erestedt omai nt
ainobj
ecteo2
pri
nt(
"nolongeri nterestedt
omai ntai
nobjecteo2:")
eo2=None #Her et hememor yspaceeo2collectedbyGC-for
ceful
l
y
ti
me.sleep(5)
pri
nt(
"Program execut ionExecuti
onCompl et
ed:")
ti
me.sleep(5)
#Heret hememor yspaceeo3col l
ectedbyGC- automat
ical
l
y

#Program f
ordemonst rati
ngFunctionalit
yofDestruct
or.
#destex4.
py
i
mpor ttime
cl
assEmpl oyee:
def__i
nit
__(self
,eno,
ename) :
sel
f .
eno=eno
sel
f .
ename=ename
pri
nt("\
t{}\
t{}
".
for
mat (sel
f.eno,
sel
f.
ename))
def_ _
del__
(self):
pri
nt("\
nDest r
uct
orcal l
edbyGar bageColl
ect
or"
)

#mainpr ogram
pri
nt(
"Program executionstart
ed:"
)
eo1=Empl oyee(10,
"RS")
eo2=Empl oyee(20,
"DR")
eo3=Empl oyee(30,
"TR")
eo4=Empl oyee(40,
"TR")
#nolongeri nt
erestedtomai nt
ainobj
ecteo1
pri
nt(
"nol ongerint
erestedt
omai ntai
nobjecteo1:
")
deleo1#Her et hememor yspaceeo1col l
ect
edbyGC-f
orcefull
y
ti
me.sleep(5)
#nolongeri nt
erestedtomai nt
ainobj
ecteo2
pri
nt(
"nol ongerint
erestedt
omai ntai
nobjecteo2:
")
deleo2 #Her ethememor yspaceeo2col l
ectedbyGC-f
orcefull
y
ti
me.sleep(5)
pri
nt(
"Program executi
onExecut
ionCompl
eted:"
)
ti
me.sleep(
5)
#Heret hememor yspaceeo3andeo4col
lectedbyGC-
aut
omat
ical
l
y

#Program f
ordemonst rati
ngFunctionalit
yofDestruct
or.
#destex5.
py
i
mpor ttime
cl
assEmpl oyee:
def__i
nit
__(self
,eno,
ename) :
sel
f .
eno=eno
sel
f .
ename=ename
pri
nt("\
t{}\
t{}
".
for
mat (self
.eno,
sel
f.
ename))
def_ _
del__
(self):
pri
nt("\
nDest r
uct
orcal l
edbyGar bageColl
ect
or"
)

#mainm program
pri
nt(
"Progr
am executi
onstar
ted:
")
eo1=Employee(10,
"RS"
)
eo2=eo1#DeepCopy
eo3=eo1#DeepCopy #Her eGCcall
sDestur
ctorOnl
yoncebcozeo1,
eo2,
eo3ar
e
poi
nting
#si
nglememoryspace.

#Program f
ordemonst rati
ngFunctionalit
yofDestruct
or.
#destex6.
py
i
mpor ttime
cl
assEmpl oyee:
def__i
nit
__(self
,eno,
ename) :
sel
f .
eno=eno
sel
f .
ename=ename
pri
nt("\
t{}\
t{}
".
for
mat (sel
f.eno,
sel
f.
ename))
def_ _
del__
(self):
pri
nt("\
nDest r
uct
orcal l
edbyGar bageColl
ect
or"
)

#mainm program
pri
nt(
"Progr
am executi
onstar
ted:
")
eo1=Employee(10,
"RS"
)
eo2=eo1#DeepCopy
eo3=eo1#DeepCopy #Her eGCcall
sDestur
ctorOnl
yoncebcozeo1,
eo2,
eo3ar
e
poi
nting
#si
nglememoryspace.

#nolongerint
erestedtomaint
ainobj
ecteo1
pri
nt(
"nolongerint
erest
edtomaintai
nobjecteo1:
")
eo1=None# Her etheGCwi ll
notcal
lDestruct
orfor
cef
ull
ybcozst
il
leo2andeo3
point
ingtosamememor yspace.
ti
me.sleep(
5)
pri
nt(
"nolongerinterestedtomai ntai
nobjecteo2:
")
eo2=None# Her et heGCwi llnotcal
l Dest
ruct
orfor
ceful
l
ybcozst
il
leo3poi
nti
ngt
o
samememor yspace.
ti
me.sleep(
5)
pri
nt(
"Program executionended: ")
ti
me.sleep(
5)
#Her etheGCwi l
lcallDestructorautomati
call
yandeli
minat
essamememor y
spaceofeo3.

#Program f
ordemonst rati
ngFunctionalit
yofDestruct
or.
#destex7.
py
i
mpor ttime
cl
assEmpl oyee:
def__i
nit
__(self
,eno,
ename) :
sel
f .
eno=eno
sel
f .
ename=ename
pri
nt("\
t{}\
t{}
".
for
mat (sel
f.eno,
sel
f.
ename))
def_ _
del__
(self):
pri
nt("\
nDest r
uct
orcal l
edbyGar bageColl
ect
or"
)

#mainm program
pri
nt(
"Progr
am executi
onstar
ted:
")
eo1=Employee(10,
"RS"
)
eo2=eo1#DeepCopy
eo3=eo1#DeepCopy #Her eGCcall
sDestur
ctorOnl
yoncebcozeo1,
eo2,
eo3ar
e
poi
nting
#si
nglememoryspace.

#nolongerint
erestedtomaint
ainobj
ecteo1
pri
nt(
"nolongerint
erest
edtomaintai
nobjecteo3:
")
deleo3# Heret heGCwi l
lnotcal
lDest
ructorfor
cef
ull
ybcozst
il
leo1andeo2
point
ingtosamememor yspace.
ti
me.sleep(
5)
pri
nt(
"nolongerint
erest
edtomaintai
nobjecteo1:
")
deleo1# Her etheGCwi llnotcal
lDest
ructorfor
cef
ull
ybcozst
il
leo2poi
nti
ngto
samememor yspace.
ti
me.sleep(
5)
pri
nt(
"Program execut
ionended:")
ti
me.sleep(
5)
#Her etheGCwi l
lcal
lDestruct
oraut
omat i
call
yandeli
minat
essamememor y
spaceofeo2.

#Program f
ordemonst rati
ngFunctionalit
yofDestruct
or.
#destex8.
py
i
mpor ttime
cl
assEmpl oyee:
def__i
nit
__(self
,eno,
ename) :
sel
f .
eno=eno
sel
f .
ename=ename
pri
nt("\
t{}\
t{}
".
for
mat (sel
f.eno,
sel
f.
ename))
def_ _
del__
(self):
pri
nt("\
nDest r
uct
orcal l
edbyGar bageColl
ect
or"
)

#mainm program
pri
nt(
"Progr
am executi
onstar
ted:
")
eo1=Employee(10,
"RS"
)
eo2=eo1#DeepCopy
eo3=eo1#DeepCopy #Her eGCcall
sDestur
ctorOnl
yoncebcozeo1,
eo2,
eo3ar
e
poi
nting
#si
nglememoryspace.

#nolongerint
erestedt omai nt
ainobjecteo1
pri
nt(
"nolongerinterestedtomaintainobjecteo3:")
deleo3# Her etheGCwi l
lnotcal
l Dest
ructorforceful
lybcozst
il
leo1andeo2
point
ingtosamememor yspace.
ti
me.sleep(
5)
pri
nt(
"nolongerinterestedtomaintainobjecteo1:")
deleo1# Her etheGCwi l
lnotcal
l Dest
ructorforceful
lybcozst
il
leo2poi
nti
ngto
samememor yspace.
ti
me.sleep(
5)
pri
nt(
"nolongerinterestedtomaintainobjecteo2:")
eo2=None# Her et heGCwi ll
callDestr
uctorforcefull
y
ti
me.sleep(
5)
pri
nt(
"Program executionended:")
Dat
aEncapsul
ati
onandDat
aAbst
ract
ion

Dat
aEncapsul
ati
on:

=>DataEncapsul ati
onisoneoft hedistinctfeatur
eofOOPs
=>ThePur poseofDat aEncapsulati
oni sthat"Tohi detheconf
identi
alInf
ormationfrom
Ext
ernal Programmers/User s".
=>ThePr ocessofHi di
ng/secur i
ngt heconf i
denti
alInfor
mati
onfrom external
Pr ogr
ammer
s
/
Un-AuthorizedUsersiscal
ledDat aEncapsul ati
on.
=>Theconf identi
alI
nformati
onr epresent sDataMember sandMet hods.
=>InPythonPr ogramming,wecanappl yDat aEncasulati
onat2places.Theyare
a)AtDat aMemberLev el.
b)AtMet hodLev el
.

=>Toimpl
ementDat
aEncapsul
ati
on,
inPythonProgr
ammi
ng,
TheDat
aMember
sand
MethodsMustBepr
ecededwit
h_ _(Eqv
.Pr iv
ate)

=>Sy
ntax1:(
Dat
aEncapsul
ati
onatDat
aMemberLev
el)

__Dat
aMember Name1=Val ue1
__Dat
aMember Name2=Val ue2
-
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
-
__Dat
aMember Name-n=Value-n
=>Syntax2:(
Dat
aEncapsul
ati
onatMethodLev el
):
--
--
--
--
--
---
--
def__MethodName( self
, l
istofformalparamsi
fany
):
-
--
--
---
--
---
--
--
--
--
---
---
---
---
--
--
--
---
--
--
Blockofst atement s
-
---
--
---
--
--
---
---
---
---
--
--
--
--
--
---
--
--
--
--
-

DataAbstr
action
=>TheProcessofret
ri
evingorext
racti
ngEssent
ial
det
ail
s(Dat
aMember
sormet
hod)
wit
houtconsider
ingHiddenDeati
lsiscal
l
edDataAbstr
acti
on.

Example1: -
--
--
--
--
--
Dat aEncapsul at i
onatDat aMemberLev el
#Others1.py
fr
om Accounti mpor tAccount
ao=Account ()
pri
nt("
-"
* 50)
#pri
nt("AccountNumber ={ }
".f
ormat (ao.acno) )NotPossi bletoaccess
pri
nt("
AccountHol derName={ }"
.format (ao. cname) )
#pri
nt("AccountHol derBal ={}
".f
ormat (ao. bal))NotPossi bletoaccess
pri
nt("
AccountHol derBr anchName={ }".for mat(ao.bname) )
#pri
nt("AccountHol derPi n={}
".f
or mat(ao. pin))NotPossi bl etoaccess
pri
nt("
-"
* 50)
****
**********
*****
* *
****** *
************
* *** **
* *
*******
***** *
#Others1.py#---
--
---
---
--
---
----
--
DataAbst r
act ionatDat aMemberLev el
fr
om Accounti mpor tAccount
ao=Account ()
pri
nt("
-"
* 50)
#pri
nt("AccountNumber ={ }
".f
ormat (ao.acno) )NotPossi bletoaccess
pri
nt("
AccountHol derName={ }"
.format (ao. cname) )
#pri
nt("AccountHol derBal ={}
".f
ormat (ao. bal))NotPossi bletoaccess
pri
nt("
AccountHol derBr anchName={ }".for mat(ao.bname) )
#pri
nt("AccountHol derPi n={}
".f
or mat(ao. pin))NotPossi bl etoaccess
pri
nt("
-"
* 50)
--
--
--
--
---
---
---
--
--
--
--
--
--
---
--
---
--
----
--
---
--
---
---
---
--
----
-----
--
---
--
--
---
--
--
--
----
---
Example2: -
--
--
--
--
--
Dat aEncapsul at i
onatDat aMet hodLev el
--
--
--
--
---
---
---
--
--
#SavingsAccount .
py -
--
--
-FileNameandTr eatedasModul eName
cl
assSAccount :
def__getSAccount (
self):#Met hodi sEncapsul ated
self
.acno=10
self
.cname=" Rossum"
self
.bal=4.5
self
.bname=" SBI"
self
.pin=4567

***
**********
*****
*****
*** *
*****
*****
*****
****
****
***
** *
*****
****
#Others2.py--
--
--
--
--
--
--
--
--DataAbstracti
onatDataMet hodLev el
fr
om Sav i
ngsAccountimpor tSAccount
ao=SAccount ()
#ao.getSAccount()-
--
--
NotPossi bl
et oaccessbcozmet hodishidden/capsul
ated
pri
nt("
-"
* 50)
#pri
nt("
AccountNumber ={}
".
format(
ao.acno))
#NotPossi bl
et oaccess
#pri
nt("
AccountHol derName={ }"
.format(ao.cname) )
#pri
nt("
AccountHol derBal ={
}".
format (
ao.bal))#NotPossi bletoaccess
#pri
nt("
AccountHol derBr anchName={ }"
.format (ao.
bname))
#pri
nt("
AccountHol derPin={ }
".
format (
ao.pin))#NotPossi bl
et oaccess
pri
nt(
"-
"*50)
--
--
--
--
--
--
--
---
--
--
--
--
---
--
--
--
---
--
----
--
--
--
--
----
--
---
--
--
--
---
--
----
---
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
-
#Account.py-
--
--
-Fil
eNameandTr eatedasModul eName
cl
assAccount :
def__ini
t__(sel
f):
self.
__acno=10#Encapsul ated
self.
cname=" Rossum"
self.
__bal=4.5 #Encapsulated
self.
bname=" SBI "
self.
__pin=4567 #Encapsul at
ed

#Others1.
py
fr
om AccountimportAccount
ao=Account(
)
pri
nt(
"-
"*50)
#pri
nt(
"AccountNumber={}"
.f
ormat(
ao.acno) )NotPossi
bletoaccess
pri
nt(
"AccountHol
derName={ }"
.f
ormat(ao.cname))
#pri
nt(
"AccountHol
derBal={}"
.f
ormat(
ao. bal
))NotPossibletoaccess
pri
nt(
"AccountHol
derBranchName={ }
".format(ao.
bname))
#pri
nt(
"AccountHol
derPin={}"
.f
ormat(
ao. pi
n))NotPossi
bletoaccess
pri
nt(
"-
"*50)

#SavingsAccount.py -
--
--
-FileNameandTr eatedasModul eName
cl
assSAccount :
def__getSAccount (
self
):#Met hodi sEncapsul ated
sel f
.acno=10
sel f
.cname=" Rossum"
sel f
.bal=4.5
sel f
.bname=" SBI"
sel f
.pin=4567
#Others2.py
fr
om Sav i
ngsAccountimpor tSAccount
ao=SAccount ()
#ao.getSAccount()-
---
-NotPossi bletoaccessbcozmet hodishidden/capsulat
ed
pri
nt("
-"
* 50)
#pri
nt("AccountNumber ={ }
".
format(ao.acno)) #NotPossi bletoaccess
#pri
nt("AccountHol derName={ }"
.f
ormat (ao.cname) )
#pri
nt("AccountHol derBal ={}
".
format(ao.bal))#NotPossi bletoaccess
#pri
nt("AccountHol derBr anchName={ }"
.format (
ao.bname) )
#pri
nt("AccountHol derPi n={}
".
format(ao.pin))#NotPossi bletoaccess
pri
nt("
-"
* 50)
#Sampl e.py
cl
assSampl e:
def__
ini
t__(self
) :
sel f
.__a=10
sel f
.b=20
pr i
nt("
Val ofai nconst r
uct or={
}".
format(self
.__
a))##Validtoaccess
pr i
nt("
Val ofbi nconst r
uct or={
}".
format(self
.b)
)
defget
values(
self
):
pri
nt(
"Valofai
nget
val
ues(
)={
}".
for
mat
(sel
f.
__a)
)#Val
i
dtoaccess
pri
nt(
"Valofbi
nget
val
ues(
)={
}".
for
mat
(sel
f.
b))

#mainpr ogram
s=Sampl e(
)
s.
getvalues()
#pri
nt(s.a,
s.
b)Inv
ali
dtoaccess

I
nher
it
ance

I
ndex:
=>PurposeofI nheri
tance
=>Defi
niti
onofI nheri
tance
=>Memor yManagementi nInheri
tance
=>AdvantagesofI nheri
tance
=>TypesOfI nheri
tances
1)SingleInheri
tance
2)Mul t
iLev elI
nherit
ance
3)HierarchicalI
nherit
ance
4)Mul t
ipleInheri
tance
5)Hy bri
dInherit
ance
=>SyntaxforInheri
tance.
=>Programmi ngExampl es

I
nher
it
ance
=>Inheri
tanceisoneofdisti
nctf
eaturesofOOPs
=>Thepur poseofI
nheri
tanceisthat"Tobuil
dRe-
usabl
eAppl
i
cat
ionsi
nPy
thon
ObjectOri
entedProgr
ammi ng".

=>Defi
nit
ionofInheritance:
=>TheProcessobt ainingDat amember s,MethodsandConst r
uctors(Featur
es)of
oneclassintoanot hercl assiscalledInher
it
ance.
=>Theclasswhichi sgi vi
ngDat amember s,MethodsandConst r
uctors(Features)is
cal
ledSuperorBaseorPar entClass.
=>TheClasswhi chist aki
ngDat amember s,Met hodsandConstructor
s(Features)
i
scall
edSuborDer i
v edorChi l
dCl ass.
=>TheInheri
tanceconceptal waysf ol
lowsLogicalMemor yManagement .Thi
s
Memor yManagementsay sthat"Nei therwewr i
teSourceCodenorTakesPhy sical
Memor ySpace" .

Advant
agesofI
nheri
tance:
=>Whenwedevelopanyinheri
tancebasedappli
cati
on,wegett
hefoll
owing
advant
ages.
1.Appl i
cati
onDev el
opmentTimei sLess
2.Applicat
ionMemor ySpaceisLess
3.Applicat
ionExecuti
ontimeisFast/Less
4.Applicat
ionPerfor
manceisenhanced( I
mpr
oved)
5.Redundancy( Dupl
icat
ion)ofthecodeismi
nimized.

Ty
pesofI
nher
it
ances

=>Ty pesofInheri
tanceisapat ternormodel whichmakesust ounderst
and,
howt
he
featuresareinher
itedf r
om basecl assintoder
ivedclasses.
=>InPy thonProgrammi ng,wehav e5t ypesofInher
it
ances.Theyare
1)SingleInherit
ance
2)Mul ti
Level I
nher it
ance
3)Hierarchi
cal I
nher it
ance
4)Mul ti
pleInherit
ance
5)Hy bri
dInheritance
_
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___

_
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
___
I
nher
it
ingt
hef
eat
uresofBaseCl
assi
ntoDer
ivedCl
ass

=>ToI nheritt
hef eaturesofBasecl assi ntoDer ivedCl ass,weuset hef oll
owing
Syntax:
class<cl ass-name- 1>:
-
--
----
--
--
--
----
---
--
---
--
--
--
--
----
--
--
---
--
- --
--
---
class<cl ass-name- 2>:
-
--
----
--
--
--
----
---
--
---
--
--
--
--
----
--
--
---
--
- --
--
---
class<cl ass-name- n>:
-
--
----
--
--
--
----
---
--
---
--
--
--
--
----
--
--
---
--
- --
--
---
class<cl ass-name- n+1>( class-name- 1,cl
ass-name- 2,
..
..
,cl
ass-
name- n>:
-
--
----
--
--
--
----
---
--
---
----
--
----
---
--
---
---
--
--
--
----
--
--
---
--
- --
--
---
--
---
--
----
--
--
----
-
Explanation:
=><classname- 1><cl assname- 2>..
..
..
...<classname- n>r epresentsNameofBase
Classes
=><classname- n+1>r epr esentsder iv
edcl assname.
=>Whenwedev elopanyI nheritanceBasedAppl i
cat i
on, I
tisalwaysr ecommendedt o
createanobj ectofBot t
om Mostder i
v edCl assbcozI tinheri
tsallfeaturesofBase
ClassandI ntermedi ateBaseCl asses.
=>ForEv eryClassi nPy thon,ther eexistani mplicitpre-defi
nedsupercl asscalled
"object"bcozobjectcl asspr ovidesGar bageCol l
ect i
onf aci
li
ty.

#I
nhpr
og1.py
cl
assC1:
deffun1(sel
f)
:
pri
nt(
"C1-
-f
un1(
)")
deff
un3(self
):
pri
nt(
"C1-
Fun3(
)")

cl
assC2( C1)
:
deffun2(
self
):
pri
nt(
"C2-
-f
un2(
)")
#mai nprogram
o2=C2( )
o2.fun2()
o2.fun1()
o2.fun3()
#Inhprog2.py
cl
assC1:
deffun1(sel
f)
:
pr
int(
"C1-
-f
un1(
)")
deff un3(self
):
pr
int(
"C1-
Fun3(
)")
cl
assC2(C1):
deffun2(self
):
pri
nt(
"C2--fun2()"
)
sel
f.f
un1( )#herewear ecall
ingbasecl
assMet
hodsf
rom der
ivedcl
ass
methods
sel
f.f
un3( )#herewear ecall
ingbasecl
assMet
hodsf
rom der
ivedcl
ass
methods

#mai nprogram
o2=C2( )
o2.fun2()
#Uni v
ersit
y--
--
-->Coll
ege----
->Student
#Inhprog3.py
cl
assUni v:
defget univ
det (
self):
sel
f.uname=i nput("
EnterUniv er
sityName: ")
sel
f.ul
oc=i nput (
"EnterUniversit
yLocat i
on:")
defdispunivdet(self)
:
pri
nt("
-"*50)
pri
nt("
\tUni v
er sit
ydetail
s:"
)
pri
nt("
-"*50)
pri
nt("
Uni versityName: {
}".
for
mat (sel
f.uname) )
pri
nt("
Uni versityLocati
on:{}
".
format (
self.
uloc))
pri
nt("
-"*50)

cl
assCol
lege(
Univ):
def get
coll
det (
self)
:
sel
f.cname=input("
Ent erCollegeName: ")
sel
f.cl
oc=input(
"EnterCol legeLocat i
on:")
def di
spcoll
det (
self)
:
pri
nt("
-"*
50)
pri
nt("
\tColl
egeDetai l
s:"
)
pri
nt("
-"*
50)
pri
nt("
CollegeName: {}".
for
mat (sel
f.cname) )
pri
nt("
CollegeLocation:{}
".
format (
self.
cloc))
pri
nt("
-"*
50)

cl
assSt
udent(
College):
defgetstuddet(self)
:
self
.sno=int(i
nput(
"Ent
erStudentNumber :
"))
self
.sname=i nput(
"Ent
erStudentName: "
)
self
.crs=input(
"Ent
erStudentCourse:
")
defdi
spstuddet (
self):
pri
nt("
-"*50)
pri
nt("
\ t
StudentDetail
s:"
)
pri
nt("
-"*50)
pri
nt("
St udentNumber :
{}
".f
ormat(
self
.sno))
pr
int
("
StudentName:{
}".
format(
self
.sname))
pr
int
("
StudentCour
se:{
}".
format(
self
.crs)
)
pr
int
("
-"
*50)

#mai nprogram
s=Student()
s.
getstuddet()
s.
getcoll
det()
s.
getunivdet()
s.
dispunivdet(
)
s.
dispcoll
det()
s.
dispstuddet()

#Univ.
py --
--
Fil
eNameandact sasmodul e
cl
assUni v :
defget univdet(self)
:
self
.uname=i nput("
Ent erUni versi
tyName: ")
self
.uloc=input ("
EnterUni versityLocat i
on:")
defdispunivdet (
self):
pri
nt("-"
*50)
pri
nt("\tUniversit
ydet ail
s:")
pri
nt("-"
*50)
pri
nt("UniversityName: {}
".
format (
self.uname) )
pri
nt("UniversityLocat i
on:{}"
.for
mat (self.
uloc))
pri
nt("-"
*50)
#Coll
ege. py-
--
fil
enameandact sasmodul e
fr
om Uni vimpor tUniv
cl
assCol lege(Univ):
def getcolldet(self)
:
self
.cname=i nput("
Ent erCollegeName: ")
self
.cloc=input (
"EnterCol legeLocat ion:")
def dispcolldet(self)
:
pri
nt("-"
*50)
pri
nt("\tColl
egeDet ail
s:")
pri
nt("-"
*50)
pri
nt("CollegeName: {}".
format (
self.
cname) )
pri
nt("CollegeLocat i
on:{}"
.f
ormat (sel
f.cloc))
pri
nt("-"
*50)
#Student.py--
--
fi
lenameandact sasmodul ename
fr
om Col l
egei mpor tCol l
ege
cl
assSt udent(College):
defget studdet(self):
self
.sno=int (
input("EnterStudentNumber :"
))
self
.sname=i nput("
Ent erStudentName: "
)
self
.crs=input (
"EnterSt udentCour se:")
self
.getcol l
det()
self
.getuni v
det ()

defdi
spst
uddet
(sel
f)
:
sel
f.di
spunivdet
()
sel
f.di
spcoll
det(
)
pri
nt("
-"
*50)
pri
nt("
\tSt
udentDetail
s:"
)
pri
nt("
-"
*50)
pri
nt("
StudentNumber :
{}".
for
mat(self
.sno))
pri
nt("
StudentName: {
}".
format(
self
.sname))
pri
nt("
StudentCourse:{
}".
format(
self
.crs)
)
pri
nt("
-"
*50)
#mai nprogram
#studcoll
univ.
py
fr
om Studentimpor
tSt
udent
s=Student()
s.
getstuddet()
s.
dispstuddet(
)

Pol
ymor
phi
sm i
nPy
thon

=>Pol
ymorphi
sm i
soneofthedist
inctfeatur
esofOOPs
=>Thepur
poseofPol
ymorphism isthat"Eff
ici
entUt
il
izat
ionMemor
ySpacee(
OR)
LessMemoryspacei
sachiev
ed".

=>Def
.ofPol
ymor
phi
sm:

=>ThePr ocessofRepr esent i


ng" OneFor minmul tipl
eFor ms"i scall
ed
Poly
mor phi
sm.
=>ThePol ymorphism Principl
ei simplement ed(Bri
ngi ntoacti
on)byUsing"Method
Overr
iding"featur
eofal lOOPr ogr ammi ngLanguages.
=>I
nThedef ini
ti
onofpol ymor phism,"OneFor m"r epresents"Origi
nalMethod"and
multi
plef or
msr epresentsOv erri
ddenMet hods.
=>A"For m"isnothingbutexi stenceofaMet hod.ifthemet hodi sexi
sti
nginbase
cl
asst henitiscall
ed" Or
iginalMet hod(onef orm)"andi fthemet hodexi
sti
ngderiv
ed
cl
asst henitiscall
ed" Overri
ddenMet hod(multipl
eFor ms) "
.

Met
hodOv
err
idi
ngi
nPy
thon

=>MethodOv er
ri
ding=MethodHeadi ngissame+Met hodBodyi
sDi f
fer
ent
(OR)
=>Theprocessofre-def
ini
ngtheoriginalmethodofbasecl
assi
ntovari
ousder
ived
cl
assesforperf
ormingdi f
fer
entoper at
ionsi
scall
edMethodOver
ridi
ng.
=>TouseMethodOv er
ri
dingi
npyt
honprogram wemustappl
yInheri
tancePr
inci
ple.
=>MethodOv
erri
dingusedfori
mplement
ingPolymor
phi
sm Pri
ncipl
e.

Examples:
#methodover
ex1.py
cl
assCircl
e:
defdraw(sel
f)
:#ori
ginal
Met hod
pr
int
("
Drawi
ngCircl
e")

cl
assRect
(Cir
cle)
:
defdraw(sel
f)
: #ov er
riddenMet
hod
pri
nt(
"Drawi
ngRect :
")
super(
).
draw()

cl
assSquar
e(Rect)
:
defdraw(self
):#over
riddenMet
hod
pri
nt(
"Drawi
ngSquare:
")
super(
).
draw()

#mainprogr
am
so=Squar
e()
so.
draw()

#t
eacher
.py
cl
assTeacher
:
def r
eadsub(self
):
print
("Teacheradv
isest
oread2hour
s")

cl
assLazySt
udent (
Teacher)
:
defreadsub(self
):
pr
int
("Lazy
St udentneverr
eadatal
l"
)
cl
assPerf
ectStudent(
Teacher ):
defreadsub(self
):
pr
int
("PerfectStudent2hr
sreadi
ngandpr
act
ici
ng"
)

l
s=Lazy Student(
)
l
s.readsub()
ps=Per f
ectStudent
()
ps.
r eadsub()

Numberofappr
oachestocal
lori
ginal
met
hodsf
rom
Overri
ddenmethods

=>Wehavetwoapprochest
ocallor
igi
nalmethod/construct
orsofbasecl
assf
rom
over
ri
ddenmethod/constr
uct
orsofderi
vedclass.Theyare
1)Byusing super()
2)ByusingClassName
1)Byusing super(
):
=>super(
)isoneofthepr e-
defi
nedfunct
ion,whi
chisusedf
orcall
i
ngsupercl
ass
ori
ginal
met hod/construct
orfrom ov
err
iddenmethod/const
ruct
orsofder
ived
cl
ass.

Sy
ntax1:
- super
().
met
hodname(
li
stofv
aluesi
fany
)

Sy
ntax2:
- super
().
__i
nit
__(
li
stofv
aluesi
fany
)

=>wit
hsuper(
)weareabl
etocal
lonl
yimmedi
atebasecl
assmet
hodbutunablet
o
cal
lSpeci
fi
edmethodofbaseCl
ass.Todot
hiswemustusecl
assnameappr
oach.

2)ByusingCl
assName:
=>Byusi
ngClassNameappr oach,
wecancallanybaseclassmethod/const
ruct
or
namefrom t
hecontextofderi
vedclassmet
hod/constructornames.

Sy
ntax1:
- Cl
assName.
methodname(sel
f,l
i
stofval
uesifany
)
Sy
ntax2:
- Cl
assName.
__i
nit
__(
sel
f,l
i
stofvaluesi
fany)

PROGRAMS:
#pol
yex1.py
cl
assCircl
e(object):
defdraw( sel
f)
:#Or i
ginalMet hod
pri
nt(
"DrawingCi rcl
e--Circl
eCl ass")
#super(
).draw()--
---
--
----
--
--i
nvali
d,bcozobjectcl
assdoesnot
cont
aindraw()
cl
assRect(Cir
cle):
defdraw( sel
f)
:#Ov err
iddenMet hod
pri
nt(
"Drawing--Rect--RectClass")
super(
).
dr aw()#wi lldraw( )ofCircl
eClassfrom draw()ofRect
cl
ass
cl
assSquare(Rect ):
defdraw( self
):#Ov err
iddenMet hod
pri
nt(
"Drawing--Squar e--
SquareCl ass"
)
super(
).
dr aw()#wi lldraw( )ofRectClassfrom draw()ofSquar
e
cl
ass

#mainprogr
am
s=Squar
e()
s.
draw()

#WAPpr ogram whichwi l


lcalculat
eareaofdif
ferentf
igur
esbyusi
ngcl
assesand
obj
ectswithpolymorphism
#pl
oyex2.py
cl
assCircl
e:
defarea(sel
f):
#or iginalmethod
self
.r
=float(
input("
EnterRadi
ous:"
))
ac=3.
14*sel
f.
r**
2
pri
nt(
"Ar
eaofCircl
e={
}".
for
mat
(ac)
)

cl
assRect
(Cir
cle)
:
defarea(
self)
:#ov erriddenmet hod
self
.l
=fl
oat (
input("
EnterLength:")
)
self
.b=fl
oat(input(
"EnterBreadth:
"))
ar=sel
f.
l*self.b
pri
nt("
AreaofRect ={
}".
format(ar)
)
super()
.area()

cl
assSquar
e(Rect):
defarea(sel
f):#overri
ddenmethod
super()
.ar
ea()
self
.s=f
loat(
input
("
EnterSide:
")
)
sa=self
.s**
2
pri
nt("
AreaofSquare={}"
.f
ormat(sa)
)

#mainpr ogr
am
s=Square()
s.
area()

#WAPpr ogram whichwi l


l calculat
ear eaofdif
ferentf
igur
esbyusi
ngcl
assesand
obj
ectswithpolymorphism
#pol
yex3.py
cl
assCircl
e:
defarea(sel
f):#or iginalmet hod
self
.r
=float (
input("EnterRadi
ous:"
))
ac=3.14* self.
r**2
pri
nt("
Ar eaofCi r
cle={}"
.f
ormat(
ac))

cl
assRect
:
defar
ea(
self)
:#or i
ginalmethod
self
.l
=fl
oat(i
nput("
EnterLength:")
)
self
.b=fl
oat(
input(
"EnterBreadth:
"))
ar=sel
f.
l*sel
f.b
pri
nt("
AreaofRect ={
}".
format(ar)
)

cl
assSquar
e(Rect,
Ci r
cle):#Mul ti
pleInherit
ance
defarea(self)
: #ov er
riddenmet hod
pri
nt (
"--
---
--
---
--
---
--
--
---
--
----
--
--
--
--
--
--
--
--
-"
)
self.
s=float(i
nput("EnterSide:"
))
sa=sel f
.s**2
pri
nt (
"AreaofSquar e={}".
for
mat (
sa))
pri
nt (
"--
---
--
---
--
---
--
--
---
--
----
--
--
--
--
--
--
--
--
-"
)
Circl
e.area(self)#cal l
ingarea()ofCir
clefr
om Square
Rect.area(self
)#cal li
ngar ea()ofRectfrom Squar
e

#mainprogr
am
s=Squar
e()
s.
area(
)

#WAPpr ogram whichwil


l calculat
ear eaofdif
ferentf
igur
esbyusi
ngcl
assesand
obj
ectswithpolymorphi
sm
#pol
yex4.py
cl
assCircl
e:
defarea(sel
f,
r)
:#or iginalmet hod
ac=3.
14* r*
*2
pri
nt(
"AreaofCi r
cle={}"
.f
ormat(
ac))

cl
assSquar
e:
defar
ea(sel
f,
s):#ori
ginalmethod
pri
nt(
"-
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-"
)
sa=s**
2
pri
nt(
"AreaofSquare={}
".
for
mat (
sa))
pri
nt(
"-
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-"
)

cl
assRect
(Square,Cir
cle):#mul t
ipl
eInheri
tance
defarea(self
,l
,b):#overr
iddenmet hod
ar=l*b
print("
AreaofRect ={
}".
for
mat (
ar)
)
super ().
area(
12)
Circle.ar
ea(sel
f,
1.5)

#mai nprogram
l
=float(
input("
EnterLengt
h:")
)
b=float
(input
("EnterBr
eadth:
"))
r=Rect(
)
r.
area(l
,b)

#WAPpr ogram whichwil


l calculat
ear eaofdif
ferentf
igur
esbyusi
ngcl
assesand
obj
ectswithpolymorphi
sm
#pol
yex5.py
cl
assCircl
e:
defarea(sel
f,
r)
:#or iginalmet hod
ac=3.
14* r*
*2
pri
nt(
"AreaofCi r
cle={}"
.f
ormat(
ac))

cl
assSquar
e:
defar
ea(sel
f,
s):#ori
ginalmethod
pri
nt(
"-
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-"
)
sa=s**
2
pri
nt(
"AreaofSquare={}
".
for
mat (
sa))
pri
nt(
"-
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-"
)

cl
assRect
(Square,Cir
cle)
: #mult
ipl
eInheri
tance
defarea(self
,l
,
b):#overr
iddenmet hod
ar=l*b
print(
"AreaofRect={
}".
format(ar
))
super (
).
area(
fl
oat(i
nput("
EnterSide:
")
))
Ci
rcl
e.ar
ea(
sel
f,
fl
oat
(i
nput
("
Ent
erRadi
ous:
")
))

#mai nprogram
l
=float(
input("
EnterLengt
h:")
)
b=float
(input
("EnterBr
eadth:
"))
r=Rect(
)
r.
area(l
,b)

#pol
yex6.py-
--
--
--
withconstr
uct
or
cl
assC1:
def__i
nit
__(
self)
:#Origi
nal
Construct
or
pri
nt(
"C1--
def
aul
tConst
ructor
")

cl
assC2(C1)
:
def__i
nit
__(sel
f):#Ov err
iddenConstr
uctor
pri
nt("
C2--defaul
t-
-const
ruct
or"
)
super(
).__
init
__()

cl
assC3(C2)
:
def__i
nit
__(sel
f):#Ov err
iddenConstr
uctor
pri
nt("
C3--defaul
t-
-const
ruct
or"
)
super(
).__
init
__()

#mainprogram
o3=C3(
)
#pol
yex7.py-
--
--
--
withconstr
uct
or
cl
assC1:
def__i
nit
__(
self)
:#Origi
nal
Construct
or
pri
nt(
"C1--
def
aul
tConst
ructor
")

cl
assC2(C1)
:
def__i
nit
__(
self)
:#Ov er
ri
ddenConstr
uctor
pri
nt(
"C2--
def
ault
--
const
ruct
or"
)

cl
assC3(C2)
:
def__i
nit
__(
self)
:#Ov erri
ddenConstr
uctor
pri
nt(
"C3--
defaul
t-
-const
ruct
or"
)
C1.__
ini
t__
(self
)
C2.__
ini
t__
(self
)

#mainprogram
o3=C3(
)
#pol
yex8.py-
--
--
--
withconstruct
or
cl
assC1:
def__i
nit
__(
self,
a):#Or i
ginal
Const
ructor
pri
nt(
"C1--
defaul
tConstr
uctoranda={
}"
.f
ormat
(a)
)

cl
assC2:
def_
_ini
t__
(sel
f,
b):#Or
igi
nal
Const
ruct
or
pr
int
("
C2-
-def
aul
t-
-const
ruct
orandb={
}"
.f
ormat
(b)
)

cl
assC3(C2,
C1):
def__i
nit
__(
self)
:#Ov erri
ddenConstr
uctor
pri
nt(
"C3--
default
--
const
ruct
or"
)
C1.__
ini
t__
(self
,10)
C2.__
ini
t__
(self
,20)

#mainprogr
am
o3=C3(
)

#hybr
idi
nh.
py
cl
assC1:
def x(
self)
:
pri
nt("C1--x(
)")
def __
init
__(self
):
pri
nt("C1--const"
)

cl
assC2(C1)
:
def x(
self)
:
pri
nt("C2--x(
)")
def __
init
__(self
):
pri
nt("C2--const"
)

cl
assC3(C1)
:
def x(
self)
:
pri
nt("C3--x(
)")
def __
init
__(self
):
pri
nt("C3--const"
)

cl
assC4(C2,
C3):
def __
ini
t__
(sel
f)
:
C1.
__i
nit
__(
sel
f)
C2.
__i
nit
__(
sel
f)
C3.
__i
nit
__(
sel
f)

pr
int(
"C4-
-const"
)
def x(
self
):
pr
int(
"C4-
-x(
)")
C1.x(
sel
f)
C2.x(
sel
f)
C3.x(
sel
f)

o4=C4()
pri
nt(
"-
--
--
--
--
--
--
--
--
--
--
--
--
--
-"
)
o4.
x()
gener
atori
npy
thon
=>gener at orisoneoft hefuncti
on
=>Thegener atorfunct i
onalway scont ainsy i
eldkey word
=>Ifthef unct i
oncont ai
nsreturnst atementt heni tiscall
edNor malFuncti
on
=>Ifthef unct i
oncont ai
nsy i
eldkey wor dtheni tiscalledgenerat
or
=>Sy ntax:
def functi
on_ name( start,
stop,step):
--
--
--
--
---
--
--
-----
---
---
---
---
--
--
---
-
---
--
--
-----
----
---
--
---
--
--
----
---
--
---
yiel
dv alue
---
--
--
-----
----
=>The' yield'keywor disusedf orgi v
ingt hev aluebackt ofuncti
oncallf
rom f
unct
ion
def i
nit
ionandcont inuethefunct ionexecut i
onunt ilcondit
ionbecomesf al
se.
#genex1. py
defkv rrange( l,
u) :
whi l
e(l<=u):
yi
eldl
l
=l+1
#mai npr ogr am
kr=kvrrange( 10,21)
print(
"typeofkr =",
type(kr)
)
fori i
nkr :
print(
i)
#genex2. py
defkv rrange( l,
u,s):
whi l
e(l
<=u) :
yieldl
l=l+s
#mai nprogr am
kr=kvrr
ange( 10,21,2)
print
("t
ypeofkr =",
type(
kr))
foriinkr:
print(
i)
#genex3. py
i
mpor tsy s
defkv rr
ange( l,
u,s):
i
f (
l>u):
pr i
nt(
"I
nvalidInput
")
sy s.
exit
()
else:
whi l
e(l
<=u) :
yieldl
l=l+s

#mai npr ogram


l
b=i nt(input("Ent erLowerBoundValue:
")
)
ub=i nt(input("Ent erupperBoundVal
ue:
"))
s=int (
input (
"Ent erSt epValue:"
))
kr=kv rrange(lb,ub, s)
print("
=" *50)
whi l
e(Tr ue):
tr
y:
pri
nt(next(
kr)
)
exceptSt opIt
erati
on:
pri
nt("="
*50)
break
Regul
arExpr
essi
ons

I
ndex
=>PurposeofRegularExpressi ons
=>Defi
niti
onofRegularExpressi ons
=>Appli
cationofRegularExpression.
=>Modul eNamef orRegularExpr essi
ons(
re)
=>Pre-
Def i
nedFuncti
onof" re"Modul e
a)fi
nditer(
)
b)start(
)
c)stop
d)group()
e)fi
ndall(
)
f)search()
...
.etc
=>Programmi ngExamples

=>Progr
ammer -Def
inedCharacterCl
asses
=>Pre-
Defi
nedCharacterClasses
=>Quanti
fi
ersinRegularExpressi
on.
=>Progr
ammi ngExampl es

=>Pr
ogr
amsi
nRgeul
arExpr
essi
ons

Regul
arExpr
essi
ons
=>Regul
arExpressi
onsconceptisonePr ogrammingLanguageIndependentConcept
.
=>Herewear el
earni
ngRegularExpressi
onswi thPyt
honSy nt
axes.
=>ThepurposeofRegul
arExpressionsisthat"ToEval
uateorValidat
etheDat a".

=>Defi
nit
ionofRegularExpressi
on:
=>ARegularExpressi
onisoneoft heStr
ingPatt
ern(Combinat
ionofAl
phabet
s,
Digi
tsandSpecialSymbols)whichisusedtosearchorf
indormatchwitht
hegiv
en
dataandobtai
nsdesi r
edResult.

Appli
cati
onsofRegularExpr
essi
ons:
=>Regul
arExpressi
onsareusedinDev elopmentofEdi tors/I DEs
=>Regul
arExpressi
onsusedinOper ati
ngSy stem development
=>Regul
arExpressi
onsusedinMi cr
oCont roll
erAppl i
cati
on
=>Regul
arExpressi
onsusedinElectroni
cCi r
cui t
s
=>Regul
arExpressi
onsusedinProtocolsdev elopment.
=>Regul
arExpressi
onsusedinLanguageCompi ler
s/Interpreter
sandExecut
ion
Envir
onments
=>Regul
arExpressi
onsusedinPat t
ernMat chingSer v
ice..
..
etc

===============================================================

Pr
e-def
inedFunct
ionsi
nremodul
e
=>Todealwi
thdealt
hepr ogramminginRegul
arExpressi
ons,wemustuseapr
e-
defi
nedmodulecal
l
ed" r
e".
=>The'r
e'modul
econtai
nst hefol
l
owingessent
ialFuncti
ons.

1)fi
ndi
ter
():
Synt
ax:
- v ar
name=r
e.f
indi
ter
("
sear
ch-
pat
ter
n",
"Gi
vendat
a")
=>herevarnameisanobjectoft
ype<class,
'Cal
l
able_I
tet
aror'
>
=>Thisfuncti
onisusedforsear
chingthe"sear
chpatter
n"ingivendatai
ter
ati
vel
y
anditret
urnstableofentr
ieswhichcontai
nsstar
tindex,endindexandmatched
val
uebasedont hesearchpatt
ern.

2)group():
=>Thisfuncti
onisusedobtaini
ngmat chedval
uebythef
indI
ter
()
=>Thisfuncti
onpresenti
nmat chclassofremodul
e
Synt
ax:- v arname=matchtabobj
.
gr oup(
)

3)start
():
=>Thisfuncti
onisusedobt ai
ningstart
ingi
ndexofmat
chedv
alue
=>Thisfuncti
onpresentinmatchclassofremodule
Synt
ax: v ar
name=mat chobj.
star
t()

4)end(
):
=>Thi
sfuncti
onisusedobt ai
ningendindex+1ofmatchedv
alue
=>Thi
sfuncti
onpresentinmatchclassofremodule
Synt
ax: v ar
name=mat chobj.
end(
)

5)search():
Syntax:- v arname=re.search("sear ch-patter n"
,"
Gi vendat a")
=>herev arnamei sanobj ectof<cl ass, '
re.mat ch'>
=>Thisfunct ionisusedf orsearchi ngt hesear chpat ter
ni ngi vendataforf
ir
st
occurrence/mat chonlybutnotf orot heroccur rences.
=>i
ft hesear chpatternfoundi ngi v endat at heni treturnsanobj ectofmatchclass
whichcont ainsmat chedv alueandst artandendi ndexv aluesanditindi
cat
es
searchissuccessf ul.
=>i
ft hesear chpatternnotfoundi ngi vendat atheni treturnsNonewhi chi
stype
<cl
ass, "
NoneTy pe">andi ti
ndicatessear chisun- successf ul
6)fi
ndall()
:
Syntax:- v arname=re.fi
ndall
("sear ch-pat t
er n",
"Gi v
endat a" )
=>her evarnamei sanobj ectof<cl ass, '
li
st '
>

=>Thi
sfunct
ionisusedforsear
chingthesearchpatt
erninent i
regi
vendataandf
ind
al
loccurr
ences/mat chesanditret
urnsallt
hemat chedvaluesint
heform an
obj
ect<cl
ass,
'l
i
st'
>butnotretur
ningStar
tandEndI ndexValues.

Pr
ogr
ams:
#RegExpr 1.
py
#Q)f i
ndt hewor d"Python"andno.ofti
mesr epeat
ed---f
indall
()
i
mpor tre
gi
vendat a="
PythonisanOOPl angandPy thonisalsoFunctionalProgr
ammi
ng
Lang."
sp="Python"
mat=re.fi
ndall
(sp,
givendata)#mati svar
iableofty
pe<class,'l
ist
'>
pri
nt("
No.ofoccur encesof'{}'
={}
".
format(
sp,l
en(mat))
)
#RegExpr 2.py
#Q)f indt hewor d" Python"andno. ofti
mesr epeat
ed- -
fi
nditer(
)
i
mpor tr e
givendat a="Pythoni sanOOPl angandPy t honisalsoFunctionalProgr
ammi
ng
Lang."
sp="Py t
hon"
mat =re.
f i
ndi t
er(sp,giv
endat a)
pri
nt("typeofmat =",
type(mat))# typeofmat =<class'cal
lable_i
ter
ator
'>
pri
nt("--
----
--
---
--
--
----
---
--
---
--
---
--
--
--
--
--
---
---
--
-"
)
pri
nt("Mat chingResul t
s:")
pri
nt("--
----
--
---
--
--
----
---
--
---
--
---
--
--
--
--
--
---
---
--
-"
)
form inmat :#her e'm' i
sanobj ectof<cl ass'r
e.Match'>
print
("\nStartIndex={}EndI ndex ={}
Value={}".format (
m. start(
),
m.end(),
m. group( )
))
pri
nt("--
----
--
---
--
--
----
---
--
---
--
---
--
--
--
--
--
---
---
--
-"
)

""
"
E:
\KVR- PYTHON- 9AM\ REGULAREXPRESSI
ONS>pyRegExpr
2.py
ty
peofmat =<cl
ass' call
able_i
ter
ator
'>
-
---
--
--
--
---
--
--
--
--
--
--
---
--
--
---
--
--
---
---
--
--
--
MatchingResults:
-
---
--
--
--
---
--
--
--
--
--
--
---
--
--
---
--
--
---
---
--
--
--

St
artI
ndex
=0EndI
ndex=6 Val
ue=Py
thon

St
artI
ndex=26EndI ndex=32 Value=Py
thon
-
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--

"
""

#RegExpr 3.py
#Q)f indt hewor d"Py thon"andno. ofti
mesr epeat
ed- -
fi
ndit
er(
)
i
mpor tr e
givendata=" Pythoni sanOOPl angandPy t honisalsoFuncti
onalPr
ogr
ammi
ng
Lang."
sp="py t
hon" .
ti
tl
e()
noc=0
mat =re.
findi t
er(sp,
givendat a)#mati sv ariabl
eofty pe<cl
ass,
'l
i
st'
>
pri
nt("--
--
----
---
---
--
---
--
---
---
--
---
--
--
---
--
--
--
---
--
-"
)
pri
nt("Mat chingResul t
s:")
pri
nt("--
--
----
---
---
--
---
--
---
---
--
---
--
--
---
--
--
--
---
--
-"
)
form inmat :#her e'm' i
sanobj ectof<cl ass'r
e.Match'>
pr int(
"\nStartIndex={}EndI ndex ={}
Value={}".format (
m. start(
),
m. end(
),
m. group( )
))
noc=noc+1
pri
nt("---
---
--
----
--
---
--
---
-----
---
---
---
--
---
--
--
---
--
-")
pri
nt("NumberofOccur encesof' {
}'
={}".f
ormat (sp,noc))
pri
nt("---
---
--
----
--
---
--
---
-----
---
---
---
--
---
--
--
---
--
-")
#RegExpr 4.py
#Q)f i
ndt hewor d" Py thon"andno. oftimesr epeat ed- -
fi
ndi
ter
()
i
mpor tre
gi
vendat a="Jav aisanOOPl angandPy thonisal soFunct i
onalPr
ogrammingLang
andPy thoni susedi nAI .
"
sp="lang1"
mat =re.sear ch(sp,gi
v endat a)
pri
nt("typeofmat =",
ty pe(mat ))#her emati sanobj ectof<cl
ass'
re.
Match'
>ifmatch
occur sot heritreturns<cl ass,"NoneTy pe">
i
f(mat !=None) :
print("
\nSear chi sSucessf ul")
print("
StartIndex={ }andEndI ndex ={
}and
Value={ }"
.format (mat .start(
),mat.end(),mat.group()))
el
se:
print("
\nSear chi sUn- Sucessf ul")
print("
'
{}'doesnotexi stsingivendat a".f
or mat (
sp))
Pr
ogr
ammer
-Def
inedchar
act
ercl
assesi
nRegul
arExpr
essi
on

=>Progr ammer -
Definedcharactercl
assesdefi
nedorprepar
edbyPyt
hon
Programmer sfor
buildingSearchPat ter
nanditisusedtosearchorf
indormatchwi
thgi
vendat
a
andobt ainsdesir
edr esul
t.
=>Progr ammer -
Definedcharactercl
assesaregiv
enbell
ow.
=>Syntaxf orProgrammer -Def
inedcharact
ercl
asses.

[
Sear
chPat
ter
n]

1.[abc]--
---
---
--
---
--
->Sear chesf orei ther'a'or'b'or'c'only.
2.[^abc]--
---
--
---
--
--
->Sear chesf orall except'a'or'b'or'c'
3.[a-z]-
--
---
--
---
--
---
->Sear chesf oral llowercaseal phabet sonly
4.[^a-z]-
--
---
--
---
--
--
->Sear chesf orallexceptl owercaseal phabets.
5.[A-Z]--
---
--
---
--
--
---
>Sear chesf orall uppercaseal phabetsonly
6.[^A-Z]-
----
--
---
--
--
-->Sear chesf oral lexceptuppercaseal phabets
7.[0-9]-
---
---
--
---
--
--
-->sear chesf oral ldigit
sonl y
8.[^0-9]-
---
--
---
--
--
---
->sear chesf orallexceptdi gits.
9.[A-Za-z]--
--
---
--
--
--->sear chesf oral ll
oweranduppercaseal phabetsonly
10.[^A-Za-z]-
--
---
--
---
->sear chesf orallexceptl oweranduppercaseal phabet
s.
11.[A-Za-z0-9]-
--
--
---->sear chesf oral l
loweranduppercaseal phabetsanddi
git
s
12.[^A-Za-z0-9]-
--
---
-->sear chesf oral lspeci
al symbol s
(exceptl oweranduppercaseal phabet
sanddi git
s)

#RegExpr 5.
py
#Thi
spr ogram sear
chesforei
ther'
a'or'
b'or'
c'onl
y
i
mportre
mat=re.
findit
er(
"[
abc]
","
cWaBT#6AT&3pk@1LH8bJ" )
pr
int
("="
* 50)
form i
nmat:
pri
nt(
"st
arti
ndex:
{}EndI
ndex
:{}Val
ue:
{}
".
for
mat
(m.
star
t()
,m.
end(
),
m.gr
oup(
)))
pri
nt(
"="
*50)

""
"
E:
\ KVR-PYTHON-9AM\ REGULAREXPRESSI ONS>pyRegExpr5.
py
==================================================
starti
ndex:0 EndIndex:
1Value:c
starti
ndex:2 EndIndex:
3Value:a
starti
ndex:18 EndIndex:
19Value:b
==================================================
""
"

#RegExpr 6.
py
#Thisprogram searchesforal
lexceptei
ther'
a'or'
b'or'c'
i
mpor tre
mat=re.f
indit
er(
"[
^abc]","
cWaBT#6AT&3pk@1LH8bJ" )
pri
nt(
"="*50)
form inmat :
pri
nt("
star
tindex:{
}EndIndex:{
}Value:{
}".
format(
m.st
art
(),
m.end(
),
m.gr
oup(
)))
pri
nt(
"="*50)

""
"
E:
\ KVR-PYTHON-9AM\ REGULAREXPRESSI ONS>pyRegExpr6.
py
==================================================
starti
ndex:1 EndIndex:
2Value:W
starti
ndex:3 EndIndex:
4Value:B
starti
ndex:4 EndIndex:
5Value:T
starti
ndex:5 EndIndex:
6Value:#
starti
ndex:6 EndIndex:
7Value:6
starti
ndex:7 EndIndex:
8Value:A
starti
ndex:8 EndIndex:
9Value:T
starti
ndex:9 EndIndex:
10Value:&
starti
ndex:10 EndIndex:
11Value:3
starti
ndex:11 EndIndex:
12Value:p
starti
ndex:12 EndIndex:
13Value:k
starti
ndex:13 EndIndex:
14Value:@
starti
ndex:14 EndIndex:
15Value:1
starti
ndex:15 EndIndex:
16Value:L
starti
ndex:16 EndIndex:
17Value:H
starti
ndex:17 EndIndex:
18Value:8
starti
ndex:19 EndIndex:
20Value:J
==================================================

#RegExpr
7.py
#Thi
sprogram sear
chesf
oral
ll
oweral
phabet
s
i
mportre
mat=re.
fi
ndi
ter
("[
a-z]","cWaBT#6AT&3pk@1LH8bJ"
)
pri
nt(
"="
*50)
form i
nmat:
pri
nt(
"st
ar tindex:
{}EndIndex:
{}Val
ue:
{}
".
for
mat
(m.
star
t()
,m.
end(
),
m.gr
oup(
)))
pri
nt(
"="
*50)

#RegExpr 8.
py
#Thisprogram searchesforal
lexceptl
owercasealphabet
s
i
mpor tre
mat=re.f
indit
er(
"[
^a-z]
","cWaBT#6AT&3pk@1LH8bJ")
pri
nt(
"="*50)
form inmat :
pri
nt("
star
tindex:{
}EndIndex:
{}Value:
{}
".
format(
m.st
art
(),
m.end(
),
m.gr
oup(
)))
pri
nt(
"="*50)

#RegExpr 9.
py
#Thisprogram searchesforal
lUppercaseal
phabets
i
mpor tre
mat=re.f
indit
er(
"[
A-Z]","
cWaBT#6AT&3pk@1LH8bJ")
pri
nt(
"="*50)
form inmat :
pri
nt("
star
tindex:{
}EndIndex:
{}Val
ue:{
}".
for
mat
(m.
star
t()
,m.
end(
),
m.gr
oup(
)))
pri
nt(
"="*50)

#RegExpr 10.py
#Thisprogr am searchesforal
lexceptUppercasealphabet
s
i
mpor tre
mat=re.f
inditer(
"[
^A-Z]","
cWaBT#6AT&3pk@1LH8bJ" )
pri
nt(
"="*50)
form inmat :
print("
star
tindex:{
}EndIndex:
{}Value:
{}
".
format(m.st
art
(),
m.end(
),
m.gr
oup(
)))
pri
nt(
"="*50)

#RegExpr 11.py
#Thisprogr am searchesforal
ldi
git
s
i
mpor tre
mat=re.f
inditer(
"[
0-9]","
cWaBT#6AT&3pk@1LH8bJ")
pri
nt(
"="*50)
form inmat :
print("
star
tindex:{
}EndIndex
:{}Val
ue:
{}
".
format
(m.
star
t()
,m.
end(
),
m.gr
oup(
)))
pri
nt(
"="*50)

#RegExpr 12.py
#Thi
spr ogr am sear
chesforal
lexceptdi
git
s
i
mportre
mat=re.
finditer
("[
^0-
9]",
"cWaBT#6AT&3pk@1LH8bJ"
)
pri
nt(
"="
*50)
form i
nmat:
pri
nt(
"st
arti
ndex:
{}EndI
ndex
:{}Val
ue:
{}
".
for
mat
(m.
star
t()
,m.
end(
),
m.gr
oup(
)))
pri
nt(
"="
*50)

#RegExpr 13.py
#Thisprogr am searchesforall
loweranduppercaseal
phabets
i
mpor tre
mat=re.f
inditer(
"[
A-Za-z]
","cWaBT#6AT&3pk@1LH8bJ")
pri
nt(
"="*50)
form inmat :
print("
star
tindex:{
}EndI ndex
:{}Val
ue:
{}"
.f
ormat
(m.star
t()
,m.
end(
),
m.gr
oup(
)))
pri
nt(
"="*50)

#RegExpr 14.py
#Thisprogr am searchesforallexceptl
oweranduppercasealphabets
i
mpor tre
mat=re.f
inditer(
"[
^A-Za-z]
","cWaBT#6AT&3pk@1LH8bJ" )
pri
nt(
"="*50)
form inmat :
print("
star
tindex:{
}EndI ndex:
{}Value:
{}
".
for
mat (
m.star
t()
,m.end(
),
m.gr
oup(
)))
pri
nt(
"="*50)

#RegExpr 15.py
#Thispr ogr am searchesforalll
oweranduppercaseal
phabetsanddigit
sonly(except
speci
al sy mbol s)
i
mpor tre
mat=re.finditer("
[A-
Za-z0-
9]","
cWaBT#6AT&3pk@1LH8bJ")
pri
nt(
"="* 50)
form inmat :
print("
star
tindex:{
}EndI ndex
:{}Val
ue:
{}"
.f
ormat
(m.star
t()
,m.end(
),
m.group()
))
pri
nt(
"="* 50)

#RegExpr 16.py
#Thisprogr am searchesforal
lspecial
symbol
s(exceptal
phabet
sanddi gi
ts)
i
mpor tre
mat=re.f
inditer(
"[
^A-Za-z0-
9]",
"$cWaBT#6A木 T&3pk@1LH8bJ" )
pri
nt(
"="*50)
form inmat :
print("
star
tindex:{
}EndI ndex:
{}Val
ue:
{}
".
for
mat(m.st
art
(),
m.end(),
m.gr
oup(
)))
pri
nt(
"="*50)
Quant
if
ier
sinRegul
arExpr
essi
ons

=>Quanti
fi
ersi
nRegul
arExpressi
onsareusedforsearchi
ngnumberofoccur
rences
ofthespeci
fi
edval
ue(al
phabetsordi
git
sorspeci al
symbols)usedi
nsear
chpatter
n
tosear
chinthegiv
endataandobtai
nsdesiredresul
t.

1)k--
--
--
--
---
--
--
--
-->Searchesexactl
yonek
2)k+-
--
--
---
--
--
--
--
-->searchesforonekormor
ek's
3)k*-
---
--
--
--
--
---
--
->Searcheszerokoronekormorek'
s
4)k?-
--
--
--
--
---
--
--
->searcheszerokoronek
5).---
--
--
--
---
--
--
-->searchesforall

#RegExpr 23.py
#Thisprogr am Se archesexact l
yonek
i
mpor tre
mat=re.f
inditer(
"k","kvkkvkkkv
kv")
pri
nt(
"="*50)
form inmat :
print("
startindex:
{}EndI ndex
:{}Val
ue:
{}
".
for
mat
(m.
star
t()
,m.
end(
),
m.gr
oup(
)))
pri
nt(
"="*50)

""
"
E:
\ KVR-PYTHON-9AM\REGULAREXPRESSI ONS>pyRegExpr23.py
==================================================
starti
ndex:0 EndI
ndex:1Value:k
starti
ndex:2 EndI
ndex:3Value:k
starti
ndex:3 EndI
ndex:4Value:k
starti
ndex:5 EndI
ndex:6Value:k
starti
ndex:6 EndI
ndex:7Value:k
starti
ndex:7 EndI
ndex:8Value:k
star
tindex:
9 EndIndex:10Value:k
=================================================="
""

#RegExpr 24.py
#Thisprogr am k+meanssear chingonekormorek's
i
mpor tre
mat=re.f
inditer(
"k+","
kvkkvkkkvkv"
)
pri
nt(
"="*50)
form inmat :
print("
star
tindex:
{}EndI ndex:
{}Val
ue:
{}
".
format
(m.
star
t()
,m.
end(
),
m.gr
oup(
)))
pri
nt(
"="*50)

""
"
E:
\ KVR-PYTHON-9AM\REGULAREXPRESSI ONS>pyRegExpr24.py
==================================================
starti
ndex:0 EndI
ndex:1Value:k
starti
ndex:2 EndI
ndex:4Value:kk
starti
ndex:5 EndI
ndex:8Value:kkk
starti
ndex:9 EndI
ndex:10Value:k
=================================================="
""

#RegExpr 25.py
#Thisprogr am k*meanssearchingzer
okoronekormorek'
s
i
mpor tre
mat=re.f
inditer(
"k*","
kvkkv
kkkvkv"
)
pri
nt(
"="*50)
form inmat :
print("
starti
ndex:
{}EndIndex:
{}Val
ue:
{}
".
for
mat
(m.
star
t()
,m.
end(
),
m.gr
oup(
)))
pri
nt(
"="*50)

""
"
E:
\ KVR-PYTHON-9AM\ REGULAREXPRESSI ONS>pyRegExpr25.py
==================================================
starti
ndex:0 EndIndex:
1Value:k
starti
ndex:1 EndIndex:
1Value:
starti
ndex:2 EndIndex:
4Value:kk
starti
ndex:4 EndIndex:
4Value:
starti
ndex:5 EndIndex:
8Value:kkk
starti
ndex:8 EndIndex:
8Value:
starti
ndex:9 EndIndex:
10Value:k
starti
ndex:10 EndIndex:
10Value:
starti
ndex:11 EndIndex:
11Value:
=================================================="
""

#RegExpr 25.py
#Thisprogr am k?meanssear chingzer
okoronekonly.
i
mpor tre
mat=re.f
inditer(
"k?","
kvkkvkkkvkv"
)
pri
nt(
"="*50)
form inmat :
print("
starti
ndex:
{}EndI ndex:
{}Val
ue:
{}
".
for
mat(
m.st
art
(),
m.end(
),
m.gr
oup(
)))
pri
nt(
"="*50)
""
"
E:
\ KVR-PYTHON-9AM\ REGULAREXPRESSI ONS>pyRegExpr26.py
==================================================
starti
ndex:0 EndIndex:
1Value:k
starti
ndex:1 EndIndex:
1Value:
starti
ndex:2 EndIndex:
3Value:k
starti
ndex:3 EndIndex:
4Value:k
starti
ndex:4 EndIndex:
4Value:
starti
ndex:5 EndIndex:
6Value:k
starti
ndex:6 EndIndex:
7Value:k
starti
ndex:7 EndIndex:
8Value:k
starti
ndex:8 EndIndex:
8Value:
starti
ndex:9 EndIndex:
10Value:k
starti
ndex:10 EndIndex:
10Value:
starti
ndex:11 EndIndex:
11Value:
=================================================="
""

#RegExpr 27.py
#Thisprogr am forsearchesall(
".
"meanssearchi
ngall)
i
mpor tre
mat=re.f
inditer(
".
","kvkkvkkkv
kv"
)
pri
nt(
"="*50)
form inmat :
print("
star
tindex:{}EndIndex
:{}Val
ue:{
}".
for
mat(
m.st
art
(),
m.end(
),
m.gr
oup(
)))
pri
nt(
"="*50)

""
"
E:
\ KVR-PYTHON-9AM\ REGULAREXPRESSI ONS>pyRegExpr27.py
==================================================
starti
ndex:0 EndIndex:
1Value:k
starti
ndex:1 EndIndex:
2Value:v
starti
ndex:2 EndIndex:
3Value:k
starti
ndex:3 EndIndex:
4Value:k
starti
ndex:4 EndIndex:
5Value:v
starti
ndex:5 EndIndex:
6Value:k
starti
ndex:6 EndIndex:
7Value:k
starti
ndex:7 EndIndex:
8Value:k
starti
ndex:8 EndIndex:
9Value:v
starti
ndex:9 EndIndex:
10Value:k
starti
ndex:10 EndIndex:
11Value:v
=================================================="
""
Pr
e-Def
inedchar
act
ercl
assesi
nRegul
arExpr
essi
on

=>Pr e-
Defi
nedchar actercl
assesdefi
nedalreadyinPy t
honSoft
wareandused
Pythonprogrammer sf orbui
ldi
ngSearchPatternsanditi
susedtosear
chorfi
ndor
mat chwit
hgi v
endat aandobt ai
nsdesir
edresult.
=>Sy nt
axforPr e-
Definedcharact
ercl
asses.
\Pr
e-Defi
nedChar act
erCl
ass
=>Pr e-
Defi
nedchar actercl
assesaregivenbell
ow.

1)\
s--
--
--
--
---
>Searchesforspacechar acteronl
y
2)\
S--
--
--
--
---
>Searchesforallexceptspacechar act
er
3)\
w---
--
--
---
>searchesforawor dcharacter(Or)[A-Za-
z0-
9]
4)\
W---
--
---
>searchesforspecialsymbols(exceptwor dcharact
er)OR[
^A-
Za-
z0-
9]
5)\
d--
--
--
--
>searchesfordigi
tsonl y or[0-9]
6)\
D--
--
---
->Searchesforal
lexceptdigitsor[^0-9]

Not
e:
\
d{2}-
--
--
--
Searchestwodigi
tno.
\
d{1,
5}-
--
--
--
--
--
>Sear
chesforal
lonet
ofi
vedi
gitnumber

#RegExpr 17.py
#Thisprogr am searchesforspacechar
acter
i
mpor tre
mat=re.f
inditer(
"\s","
$cWaBT#6AT&3pk@1LH8bJ" )
pri
nt(
"="*50)
form inmat :
print("
starti
ndex:{
}EndI ndex
:{}Val
ue:
{}
".
format
(m.
star
t()
,m.
end(
),
m.gr
oup(
)))
pr
int
("
="*
50)

"""
E:\KVR- PYTHON- 9AM\ REGULAREXPRESSI ONS>pyRegExpr
17.py
==================================================
startindex:4 EndI ndex: 5Value: (space)
startindex:15 EndI ndex:16Value: (space)
==================================================" "
"
#RegExpr 18.py
#Thispr ogr am searchesf oral
lexceptspacecharacter
i
mpor tre
mat =re.fi
nditer(
"\S","$cWaBT#6AT&3pk@1LH8bJ" )
print(
"="*50)
form i nmat :
print("
startindex:{
}EndI ndex
:{}Value:
{}"
.f
ormat
(m.star
t()
,m.
end(
),
m.gr
oup(
)))
print(
"="*50)

#RegExpr 19.py
#Thisprogr am searchesforal
lwor
dcharact
er
i
mpor tre
mat=re.f
inditer(
"\w","$cWaBT#6AT-&3pk@1LH8bJ" )
pri
nt(
"="*50)
form inmat :
print("
star
tindex:{
}EndIndex:
{}Value:
{}
".
format
(m.
star
t()
,m.
end(
),
m.gr
oup(
)))
pri
nt(
"="*50)

#RegExpr 20.py
#Thisprogr am searchesforal
lsepcialsymbhol
sexceptwordchar
acter
i
mpor tre
mat=re.f
inditer(
"\W", "
$cWaBT#6AT- &3pk@1LH8bJ")
pri
nt(
"="*50)
form inmat :
print("
star
tindex:{
}EndI ndex :
{}Val
ue:
{}
".
format
(m.st
art
(),
m.end(
),
m.gr
oup(
)))
pri
nt(
"="*50)

#RegExpr 21.py
#Thisprogr am searchi
ngforal
ldi
git
s
i
mpor tre
mat=re.f
inditer(
"\d","
$cWaBT#6AT-&3pk@1LH8bJ")
pri
nt(
"="*50)
form inmat :
print("
starti
ndex:
{}EndI
ndex:{
}Val
ue:
{}"
.f
ormat
(m.
star
t()
,m.
end(
),
m.gr
oup(
)))
pri
nt(
"="*50)

#RegExpr 22.py
#Thisprogr am searchingf
oral
lexceptdigi
ts
i
mpor tre
mat=re.f
inditer(
"\D","$cWaBT#6AT-&3pk@1LH8bJ")
pri
nt(
"="*50)
form inmat :
print("
star
tindex:
{}EndIndex:
{}Value:
{}
".
for
mat
(m.
star
t()
,m.
end(
),
m.gr
oup(
)))
pri
nt(
"="*50)
#reguex23.py
#\d{2}
---
---
--
--
->Sear
chesf ortwodigitnumber
i
mpor tre
mat=re.f
indit
er("
\d{2}
",
"poo16&rit
u19w22")
pri
nt("
*"*50)
form inmat :
pri
nt("
start
:{}end:{
}v alue:
{}
".
format(m.
star
t()
,m.
end(
),
m.gr
oup(
)))
pri
nt("
*"*50)

""
"
****
** *
***
***
***
*** *
* *
***
***
***
***
***
***
***
***
***
*
star
t:3end:5value:16
star
t:10end:12v alue:
19
star
t:13end:15v alue:
22
****
** *
***
***
***
*** *
* *
***
***
***
***
***
***
***
***
***
*
""
"

#reguex24.py
#\d{1,
5}---
--
--
--
--
>Searchesf orallonetofiv
edigitnumber
i
mpor tre
mat=re.f
indit
er("
\d{1,
5}"
,"6poo16&6r i
tu19w2022")
pri
nt("
*"*50)
form inmat :
pri
nt("
start:
{}end:{
}v alue:{
}".
format(m.st
art
(),
m.end(
),
m.gr
oup(
)))
pri
nt("
*"*50)

""
"
****
** *
***
***
***
*** *
* *
***
***
***
***
***
***
***
***
***
*
star
t:0end:1value:6
star
t:4end:6value:16
star
t:7end:8value:6
star
t:12end:14v alue:
19
star
t:15end:19v alue:
2022
****
** *
***
***
***
*** *
* *
***
***
***
***
***
***
***
***
***
*
""
"

extractnamesoft hestudent swhi charepresenti


nt hegiventext
#namesex1. py
i
mpor tre
studdata=" Pranavisstudent, AnkitisCEO, Sant
hoshi ssoft
war eeng,Aj
ayisreasear
ch
student, Rossum isadev eloperandMal l
eshisateacherandKur uvaisdataengand
Mani kant aisscienti
standUmeshi sav er
ygoodst udent.
"
namesl ist=re.
findi
ter(
"[
A- Z][a-z]
+" ,
studdata)
print(
"--
---
---
--
---
--
--
--
---
--
--
--
----
----
---
--
--
--
--
---
")
print(
"NamesofSt udents:"
)
print(
"--
---
---
--
---
--
--
--
---
--
--
--
----
----
---
--
--
--
--
---
")
fornainnameslist:
pr
int
(na.group()
)
pri
nt(
"-
---
--
--
--
--
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
")

#WAPwhi chwi llextractnamesoft hestudentswhicharepresenti


nthegiventext
#namesex2. py
i
mpor tre
studdata=" Pr anavi sstudent, Anki
tisCEO, Sant
hoshissoftwareeng,Aj
ayisreasear
ch
student, Rossum i sadev eloperandMal l
eshisateacherandKur uv
aisdataengand
Mani kant aissci entistandUmeshi sav erygoodstudent
."
namesl ist=re.findall
( "
[A-
Z][
a-z]+",studdata)
print
("--
---
----
--
- -
--
--
---
----
--
--
--
--
---
--
---
--
--
--
----
")
print
("NamesofSt udent si
nAscendi ngOrder:
")
print
("--
---
----
--
- -
--
--
---
----
--
--
--
--
---
--
---
--
--
--
----
")
namesl ist.sor t
()
fornamei nnamesl ist:
pri
nt (
name)
print
("--
---
----
--
- -
--
--
---
----
--
--
--
--
---
--
---
--
--
--
----
")

#WAPwhi chwi llextractnamesoft hestudentsandtheirmarkswhicharepresenti


nt he
givent extand
#namesmar ksex1.py
i
mpor tre
studdat a="Pranavi sstudentgotmar ks60, Anki
tisCEO marks99, Sant
hoshissoftware
engandwhosemar ks65, Ajayi sr easearchstudentandmarks67, Rossum i
sadev eloper
gotmar ks35andMal leshisat eachergot60andKur uvai
sdataengandgot77and
Mani kantai sscientistgot88andUmeshi sav er
ygoodstudentgot79."
namesl i
st=re.
findit
er ("
[A-Z][
a-z]+",
st uddata)#RegExprf orNames
print(
"---
--
---
--
---
--
--
---
----
--
---
---
--
--
---
")
print(
"Namesofst udent s:"
)
print(
"---
--
---
--
---
--
--
---
----
--
---
---
--
--
---
")
fornamei nnamesl ist:
print(
"\t{}
".format(name. group()))
print(
"---
--
---
--
---
--
--
---
----
--
---
---
--
--
---
")
mar kslist
=re.fi
nditer("\
d{2}" ,
studdat a)
print(
"Mar ksofst udent s:"
)
print(
"---
--
---
--
---
--
--
---
----
--
---
---
--
--
---
")
formar ksinmar kslist:
print(
"\t{}
".format(mar ks. group())
)
print(
"---
--
---
--
---
--
--
---
----
--
---
---
--
--
---
")

#WAPwhi chwi llextr


actnamesoft hestudentsandtheirmarkswhicharepresenti
nt he
gi
v ent extand
#namesmar ksex2.py
i
mpor tre
studdat a="Pranavisst udentgotmar ks60, Ankiti
sCEO mar ks99, Sant
hoshissoftware
engandwhosemar ks65, Ajayisr easearchstudentandmarks67, Rossum i
sadev eloper
gotmar ks35andMal l
eshi sat eachergot60andKur uvai
sdataengandgot77and
Mani kantai sscienti
stgot88andUmeshi sav erygoodstudentgot79."
namesl i
st=re.
findall
("
[A-Z][
a- z]+"
,studdata)#RegExprf orNames
mar kslist
=re.fi
ndall(
"\d{2}",studdata)
print(
"---
--
---
--
---
--
--
---
--
--
---
---
--
----
---
--
---
---
--
--
--
--
---
-"
)
pri
nt("
NameofSt udent\t
\tMarksofstudents:
")
pri
nt("
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
-")
fornames,marksinzip(
namesl i
st,
marksli
st)
:
pr
int
("\
t{}
\t\
t{}
".f
ormat(names,marks))
pri
nt("
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
")

#WAPwhi chwil
lreadt het extdat afrom fi
lewhi chcont ai
nsmul ti
plestudentnamesandt
he
marksandextr
actnamesandmar ksf r
om t hrgivenfil
e
#namesmarksex3.py
i
mportre
tr
y:
wit
hopen( "D:\\ampt \\st
udinfo.data","
r"
)asf p:
fi
ledata=fp.read()
namesl ist=re.f
indall
("
[A-Z][a-
z]+",
fi
ledata)#RegExprf orNames
mar ksli
st=re.fi
ndall(
"\d{2}",f
il
edata)##RegExprf orMarks
print(
"--
---
---
--
---
--
--
---
--
--
---
---
---
--
--
---
--
--
---
--
--
---
--
--
-")
print(
"NameofSt udent\t\tMarksofst udents:
")
print(
"--
---
---
--
---
--
--
---
--
--
---
---
---
--
--
---
--
--
---
--
--
---
--
--
-")
fornames, marksi nzip(namesl i
st,
mar ksli
st)
:
print(
"\t{
}\t\
t{}
" .
format(names, marks))
print(
"--
---
---
--
---
--
--
---
--
--
---
---
---
--
--
--"
)

exceptFi
l
eNotFoundErr
or:
pri
nt(
"Fi
ledoesnotexi
sts"
)

#emai lswi t
hnames. py
i
mpor tre
text="Rossum mai li
disr ossum_ 12_ psf@psf .
com ,Ritchemail i
disrit
che_
c@bel
l
labs.
co.
in,
Gosl i
ngmai lidisgosling_ 1_j
ava@sun. net.organdTr avisemailidis
travi
s_ numpy @numpy .organdKv rmail i
diskv r1.
jav
a@gmai l.com ."
namesl i
st=re.fi
ndall
("
[A-Z][a-
z]+",
text)#RegExprf orNames
mai l
slist=re.f
indall
("
\S+@\ S+",
text)#RegExprf ormai l-
idext
raction
print(
"---
---
---
--
---
--
--
--
--
--
--
---
----
--
--
--
--
---
---
---
--
---
--
--"
)
print(
"NameofSt udent\t\tMail
sofst udent s:
")
print(
"---
---
---
--
---
--
--
--
--
--
--
---
----
--
--
--
--
---
---
---
--
---
--
--"
)
fornames, mai l
sinzip(namesl i
st,mailsl
ist)
:
pri
nt("\
t{}
\t\
t{}"
.format(names, mai l
s))
print(
"---
---
---
--
---
--
--
--
--
--
--
---
----
--
--
--
")

#wr i
teapy thonprogram whichwi ll
extr
actemailid'sfrom t
hegivent
ext
#emai lveri.
py
i
mpor tre
text
=" Rossum mai lidisrossum_ 12_psf
@psf .
com , r
itchemaili
disri
tche_
c@bel
l
labs.
co.
in,
Goslingmai li
disgosl i
[email protected].
organdTr av i
semaili
dis
trav
is_ numpy @numpy .
organdkv rmaili
diskv r
1.java@gmai l
.
com ."
emai l
s=r e.f
indal
l(
"\S+@\ S+",
text)
formai linemai l
s:
pr
int(
"\t
{}"
.f
ormat (
mail))
#mobilenumberval
idati
on.py
i
mpor tre
whil
e(True)
:
mno=input(
"Enterurmobi lenumber:
")
#12345678ab
i
f(l
en(
mno) ==10):
result
=re.search("
\d{10}
",
mno)
if(
result
!=None) :
pri
nt("
UrMobi l
eNumberisVali
d")
break
else:
pri
nt("
Mobi l
eNumbershouldnotcontai
nAl
phabet
s/speci
al
sy
mbol s")
el
se:
print
("MobileNumbermustcont ai
n10di gi
ts:
")

Mul
tiThr
eadi
ngi
nPy
thon
I
ndex
=>PurposeofMul t
i Threadi
ng
=>TypesofAppl ications
=>Defi
nitionofThr ead
=>PurposeofThr ead
=>Modul eNameRequi r
edForMul t
iThreading
--
>thr
eading<---
-ModuleName
*Variabl
esNames
*FunctionNames
*Threadclass
*LockCl ass
=>Programmi ngExampl es
=>Synchr oni
zat
ionconcepti nPython
=>DeadLocksi nPy thon
=>AvoidingDeadLocks
=>Programmi ngExampl es

Mul
tiThr
eadi
ngi
nPy
thon

=>ThepurposeofMul tiThreadingis"ToprovideConcurr
entExecuti
on"
=>Theconcur rentexecuti
oni snothi
ngbutSimul t
aneousorParal
lelExecuti
on.
=>TheAdv antageofConcur r
entExecuti
onisthatalwaystakesLessExecutionTi
me.
=>I
nt hecontextofPr ogrammi ngLanguages,wehav e2typesofLanguages.They
are
a)ProcessBasedAppl icat
ions
b)ThreadBasedAppl i
cati
ons.
a)ProcessBasedAppl i
cati
ons:
=>ProcessBasedAppl i
cati
onsexecut i
onenv i
ronmentcontai
nsSingleThread
=>Pr
ocessBasedAppli
cat
ionsprovi
desSequential
Executi
on
=>Pr
ocessBasedAppli
cat
ionsTakesMor eExecuti
onTime
=>Pr
ocessBasedAppli
cat
ionsaretr
eatedasHeav yWeightAppl
i
cat
ion.
Exampl
es:C,CPP..
.et
c

b)ThreadBasedAppl i
cat
ions.
=>ThreadBasedAppl icat
ionsarethosewhoseexecut i
onenv i
ronmentcont
ains
Singl
eThr ead
(bydefault
)andallowsuscr eat
eMul ti
pleThreadsprogrammatical
ly
.
=>ThreadBasedAppl icat
ionsprovi
desSequent i
alExecuti
on(bydefaul
t)al
so
provi
des
ConcurrentExecuti
onpr ogr
amaticall
y.
=>ThreadBasedAppl icat
ionsTakesLessExecut i
onTime
=>ThreadBasedAppl icat
ionsaretreat
edasLi ghtWeightAppli
cat
ions.
Examples:Py t
hon,Java.C#.Net..
.etc
#Thr
eadDemo1. py
i
mportthreadi
ng
pr
int
("
==========================" )
pr
int
("
defaultNameoft hread=",
threadi
ng.curr
ent
_thr
ead()
.name)#Mai
nThr
ead
pr
int
("
NumberThr eadsar eacti
ve=",thr
eading.
act
ive_
count(
))#1
pr
int
("
==========================" )
pr
int
("
Thisismypy thonpr ogr
am" )
pr
int
("
ThisisMul t
iThreading"
)

#Thr
eadDemo2. py
i
mportthreadi
ng
def fun1()
:
print
("
iam f
rom f
un1(
)-
--executedby:
",
threading.cur
rent
_thread(
).name)
def fun2()
:
print
("
iam f
rom f
un2(
)-
-executedby:"
,t
hreading.curr
ent_t
hread()
.name)
def fun3()
:
print
("
iam f
rom f
un3(
)-
-executedby:"
,t
hreading.curr
ent_t
hread()
.name)
def fun4()
:
print
("
iam f
rom f
un4(
)-
-executedby:"
,t
hreading.curr
ent_t
hread()
.name)

#mainprogr am
pri
nt(
"MainPr ogram Execut i
onSt
arted:"
)
tname=threading.cur
rent_thr
ead(
).
name
pri
nt(
"Nameofmai nthreadinmainprogram=",
tname)
pri
nt(
"-
"*50)
fun1(
)
pri
nt(
"maint hr
eadcamet omainprogram goi
ngtofun2(
)")
fun2(
)
pri
nt(
"maint hr
eadcamet omainprogram goi
ngtofun3(
)")
fun3(
)
pri
nt(
"maint hr
eadcamet omainprogram goi
ngtofun4(
)")
fun4(
)
pri
nt(
"-
"*50)
pri
nt(
"MainPr ogram Execut i
onst
oped:")
#nonthr
eadspr ogram. py
i
mpor tt
hreading,time
defsquar es(l
st):
print
("Nameoft hreadexecut i
ngsquares()=",
threading.current
_thread()
.name)
forvalinlst:
pri
nt(
"squar e(
{})={}
".
format
(val,
val**2))
ti
me.sleep(1)
defcubes( l
st):
print
("Nameoft hreadexecut i
ngcubes()=",
threading.current_t
hread().
name)
forvalinlst:
pri
nt(
"cubes( {
})={}"
.f
ormat(
val,
val**3))
ti
me.sleep(1)
#mainprogr am
bt=t
ime.ti
me( )
pri
nt(
"MainPr ogram Execut ionStarted:"
)
tname=threading.curr
ent_thread()
.name
pri
nt(
"Nameofmai nthreadi nmainpr ogram=",
tname)

print
("
-"
*50)
l
st=[2,
5,6,
3,8,
9]
print
("
maint hreadcamet omai nprogram goi
ngt
osquares()
")
squares(l
st)
print
("
maint hreadcamet omai nprogram goi
ngt
ocubes()"
)
cubes(l
st)
print
("
MainPr ogr
am Executi
onSt oped:"
)
#findexecutionofthisnon-t
hreadingprogram
et=ti
me.ti
me( )
print
("
\Execut i
ontime={}
".
format(et-
bt))

#wit
hthr
eadsprogram.py
i
mportthreadi
ng,t
ime
defsquares(l
st)
:
print
("
Nameoft hr eadexecuti
ngsquares(
)="
,t
hreadi
ng.
cur
rent
_thr
ead(
).
name)#
Thr
ead-1
forvali
nlst:
pri
nt(
"square({
})={
}".
for
mat(v
al,v
al*
*2))
ti
me.sleep(1)

defcubes(l
st)
:
pri
nt("
Nameoft hr eadexecuti
ngcubes(
)="
,t
hreadi
ng.
cur
rent
_thr
ead(
).
name)#
Thr
ead-2
forvali
nlst:
pri
nt(
"cubes({}
)={}
".
format
(val
,
val
**3))
ti
me.sleep(1)

#mainprogr am
bt=t
ime.ti
me( )
pri
nt(
"MainPr ogram ExecutionSt
art
ed:")
tname=threading.cur
rent_t
hread(
).
name
pri
nt(
"Nameofmai nthreadinmainprogram="
,t
name)#Mai
nThr
ead
pri
nt(
"-
"*50)
l
st=[2,5,6,
3,8,
9]
t1=threading.
Thread( t
arget=squares,args=(lst
,))#her
et1isanobjectofThread
class--
Therad-1
t2=threading.
Thread( t
arget=cubes,args=(lst,
))#heret2i
sanobjectofThread
t1.st
art()
t2.st
art()
t1.j
oin()
t2.j
oin()
print
("MainPr ogr
am Execut ionCompl eted:")
#findexecut i
onoft hisnon-threadingpr ogram
et=ti
me. ti
me()
print
("\Executi
ontime={ }"
.f
ormat (et-
bt))

I
ntr
oduct
iont
oThr
eadBasedAppl
i
cat
ions

=>Thepur poseofmultit
hreadingisthat"
ToprovideConcurrent/Simult
aneous
execut
ion/Par al
lel
Execution"
.
=>ConcurrentExecuti
onisnot hi
ngbutexecuti
ngt heoperat
ionsall
atonce.
=>Theadv antageofConcurrentexecuti
onisthattogetlessexecut
iontime.
=>IfaPythonPr ogr
am containsmult
iplet
hreadstheniti
scal l
edMultiThreadi
ng
program.

=>Def.oft
hread:
=>Afl
owofCont roli
scall
edthread.
=>Thepurposeofthr
eadisthat"ToPer
for
m cer
tai
noper
ati
onwhosel
ogi
c
dev
elopedinFuncti
ons/Methodsconcurr
entl
y.
"

=>Bydef aultEveryPy t
honcont ainsSi ngleThreadandwhosenamei s"MainThread"
andItprov i
desSequent i
alExecut i
on.
=>Programmat ical
ly,I
naPy t
honPr ogr am wecancr eat emulti
plesub/Chi l
d
t
hreadsandwhosepur posei sthat"Toexecut eoper ati
onswhosel ogiciswr i
tt
en
i
nFunct i
ons/Met hodsConcur rently".
=>HencePr ogrammat icall
yaPy thonPr ogram t
wot y pesofThr eads.Theyar e
a)Mai nThread
b)Sub/Chi l
dThr eads
=>MainThr eadi screated/Initi
atedbyPVM whenpr ogr am executi
onst art
sandt he
rol
eofmai nThreadi stoexecut emai npr ogram stat
ement sandMoni torthe
exeucti
onst at
usofSubt hreads.
=>TheSub/Chi ldThreadsal waysexecut esoperati
onswhosel ogiciswr i
tt
eni n
Functi
ons/Met hodsConcur rentl
y" .

Modul
eRequi
redf
orDev
elopi
ngThr
eadBasedAppl
i
cat
ions

=>ThemodulenameRequi
redf
orDev
elopi
ngThr
eadBasedAppl
i
cat
ionsi
s
"t
hreadi
ng"
.
=>Beforedevelopi
ngt
hreadbasedappli
cat
ions,wemustimport"t
hreadi
ng"modul
e.
=>Weknowt hatamodulei
sacollect
ionofVari
abl
eNames, Funct
ionNamesand
Class
Names.
=>Here"thr
eading"modul
econtai
nsthefoll
owingVar
iabl
eNames, Functi
onNames
andclassnames.

Modul
eName:t
hreadi
ng

Funct
ionNames:
1)cur
rent_
thr
ead()
--
--Syntax
:threadi
ng.
cur
rent_t
hread(
)
2)act
ive_
count(
)-
--
--
-syntax: t
hreadi
ng.
act
ive_
count()

ClassName- 1: Thr ead--


--useofThr eadclassistocreatesubthread(
s)
1)Thread(t
arget
,args)- t1=t hreadi
ng.Thr
ead(t
arget=funcname,ar
gs=())
2)start(
)-
--
usedf ordispatching/sendi ngsubthreadstotarget
edFunction
Sy ntax:
-subt hr
eadobj.
start
()

3)set
Name(
str
)-
--
sett
ingtheuser-f
ri
endlynametothethread-
-depr
ecat
edon-
-
"name" Synt
ax:-subthread.set
Name("
User-Fr
eindl
yName")
(
OR)
subt
hread.name=User
-Fr
eindl
yName

4)get
Name(
)-
--
-get
tingthethr
eadname- --
--
--
-deprecar
edon"
name"
Sy
nt ax:
-subthread.getName( )
(OR)
subthread.name

5)i
s_al
i
ve(
)-
--
Ret
urnsTr
ueprovi
dedthr
eadisrunningother
wiseFal
se
Sy
ntax:
-subthr
eadobj.
is_al
i
ve()

6)j
oin()
--
--
Iti
susedformaki
ngt hesubthreadst oj
oinwi
thmai
nthr
eadaf
ter
completeexecut
ionofsubt
hreads
Sy
ntax:-subt
hread.j
oin()

7)run(self):
-Itisoneoft henul lbodymethodofThr eadcl assoft
hreadi
ngmodule
I
tisuseddef ini
ngl ogicofPy thonprogr
am whi chisexecutedbySubthread.
Thismet hodisaut omat i
call
ycalledbystart(
).
Exampl e:
cl
asscl assname( threading.Thread):
def r un(self)
:
--
--
---
---
--
--
--
--
----
--
--
---
Blockofst mt s-
-executedbysubt hreads
--
---
---
--
--
--
--
----
--
---
--
--
#mai nprogr am
obj=classname( )
obj
.
star
t()#her
est
art
()i
sint
ernal
l
ycal
l
ingr
un(
)of<cl
assname>

Cl
assName-
2: Lock

1)acqui
re(
)
2)rel
ease(
)

==============================================================
Numberofappr
oachest
odev
elopt
hreadbasedappl
i
cat
ions
==============================================================
=>I
nPy thon,wecant hr
eadbasedappli
cationsin3approaches.Theyare
1)ByUsi ngFuncti
onalAppr
oach
2)ByUsi ngSubClassofThreadclassofthreadi
ngmodul e(withOOPsand
I
nherit
ance)
3)ByUsi ngNon-SubClassofThreadclassofthreadi
ngmodul e(withOOPswit
hout
I
nherit
ance)

1)ByUsingFunct i
onalApproach
tep-
1:impor tthr
eadingmodul e
Step-
2:Def ineaFunctionwithLogi
cwhi
chisexecutedbySubThr
ead
Step-
3:cr eatesubthread
Step-
4:dispatchorsendt hesubthr
eadt
othetargetfunct
ion.

Examples:
#Fir
stApproachEx1.py
i
mpor tt
hreading#st ep-1
defhell
o(s):#st ep-2
pri
nt("
-"*
50)
pri
nt("
\nThisFunct i
onexecutedbySubThr eadandWhoseName
i
s:{
}".
for
mat (t
hreading.curr
ent_
thread()
.name))
pri
nt("
Hi,{
}wel cometothreadi
ng".f
ormat
(s))
pri
nt("
-"*
50)

#mainprogram
t=t
hreadi
ng.Thr
ead(
tar
get
=hel
l
o,ar
gs=(
"pooj
a-kav
ya"
,))# st
ep-
3
t.
star
t()# st
ep-
4

2)ByUsingSubClassofThr
eadclassoft
hreadi
ngmodul
e(wi
thOOPsand
I
nheri
tance)
Step-
1:importt
hreadi
ng
Step-
2:ChoosetheProgr
ammer-Defi
nedClass
St
ep-3:ThePr ogrammer -
def i
nedclassmustinheritfr
om Threadcl
assoft
hreadi
ng
module.
St
ep-4:creat
eanobj ectofPr ogrammer -
defi
nedclass
St
ep-5:callt
hest art
()w.r.ttheobjectofProgrammer -
def
inedclass
object
.start(
)
Her estart(
)internall
ycall
ingrun()ofProgrammer-defi
ndcl
ass

Examples:
SecondAppr oachEx1.py
i
mpor tthreadi
ng #st ep-1
# st ep-2 step-3
cl
assSampl e(t
hreading.Thread)
:
defrun(self)
:#st ep-4
print(
"\nNameofsubt hread="
,t
hreadi
ng.
cur
rent
_thr
ead(
).
name)
print(
"iam from r
un(
)")

#mai nprogr
am
pri
nt("
Defaul
tNameoft hr
ead=",
threading.
current_t
hread(
).
name)#Mai
nThr
ead
#createasubthread
t1=Sample()
t1.
name=" OOPS"
pri
nt("
Issubthreadal
iv
ebeforestart=",
t1.
is_
aliv
e())
#False
t1.
start
()#step-5
pri
nt("
Issubthreadal
iv
eafterst
art=",t
1.i
s_al
ive()
)#True

3)ByUsingNon-
SubCl
assofThr
eadcl
assoft
hreadi
ngmodul
e(wi
thOOPswi
thout
I
nheri
tance)

St
ep1:i
mpor tthr
eading
St
ep-2:
Chooset hePr ogr
ammer -Defi
nedClass
St
ep-3:
DefineProgrammer -defi
nedmet hodinsideofProgr
ammer
-Def
inedCl
ass
St
ep-4:
Createanobj ectProgrammer-defi
nedclass
St
ep-5:
createsubthreadw. r.
tThreadclassofthreadi
ngmodul
e
St
ep-6:
Callthestar
t()upont hesubthreadobject

Examples:
#Thi
rdApproachEx1. py
i
mportthreadi
ng#st ep-
1
cl
assTest: #St ep-2
def hel
lo(self,
s):#step-3
print("
\nNameofsubt hr
ead="
,t
hreadi
ng.cur
rent
_thr
ead(
).
name)
print("
Hell
o,{},
GoodMor ning"
.f
ormat(s)
)
print("
Iam fr
om hello(
)ofTestClass"
)
print("
herehell
o()execut
edbysubt hr
ead")

#mai nprogram
t=Test(
)# Cr eat
eanobjectProgr
ammer-
defi
nedclass-
-step-
4
subth=threadi
ng.Thr
ead(
target
=t.
hel
l
o,ar
gs=(("
Rossum" ,
)))# #cr
eat
esubt
hread-
-
Step-5
subth.star t(
)# #st ep-6
#subt hreadsdemo. py
i
mpor tthr eading
deff un1( ):
pr i
nt(
"Hi")
deff un2( s):
pr i
nt(
"Hi,",
s)
#mai npr ogr am
pri
nt (
"Def aultNameoft hread=",threading.
current
_thread().
name)#Mai nThr ead
t1=threadi ng.Thread( t
arget=fun1)#her et1iscall
edsubt hread
t2=threadi ng.Thread( t
arget=fun2, args=("
Rossum" ,
))#her et2iscal
ledsubt hread
pri
nt (
"Def aultNameofsubt hread=" ,t1.
name)#Thr ead-1
pri
nt (
"def aultNameofsubt hread=" ,t2.
name)#Thr ead-2
#assignUser -
FreindlyNamet othesubt hreads
t1.name=" Rossum" # t 1.setName( "
Rossum" )
--
--isdeprecatedt
oanat tr
ibute
"name"
t2.name=" Rit
che" # t 2.setName( "
Rit
che")-
--
-i
sdepr ecatedtoanatt
ribute
"name"
pri
nt (
"Nameofsubt hr
ead=" ,t1.
name)
pri
nt (
"Nameofsubt hr
ead=" ,t2.
name)

#subt hreadsst atus. py


i
mpor tthr eading,
time
deff un1( ):
pr i
nt(
"Hi")
ti
me. sleep( 5)
ef f un2( s) :
pr i
nt(
"Hi,",s)
ti
me. sleep( 7)
#mai npr ogr am
pri
nt ("Def aultNameoft hread=",threadi ng.
current_thread().name)#Mai nThr ead
t1=thr eadi ng.Thread( t
arget=fun1)#her et1iscal l
edsubt hread
t2=thr eadi ng.Thread( t
arget=fun2, args=( "
Rossum" ,
) )#her et 2iscal ledsubt hread
pri
nt ("Def aultNameofsubt hread=" ,t1.name)#Thr ead-1
pri
nt ("def aultNameofsubt hread=" ,t2.name)#Thr ead-2
#assi gnUser -
Freindl yNamet othesubt hreads
t1.name=" Rossum" # t 1.setName( "Rossum" )--
--isdeprecat edt oanat tr
ibute
"name"
t2.name=" Rit
che" # t 2.setName( "Rit
che")--
--i
sdepr ecat edtoanat tr
ibute
"name"
pri
nt ("Nameofsubt hr
ead=" ,t1.
name)
pri
nt ("Nameofsubt hr
ead=" ,t2.
name)
pri
nt ("\nNumberoft hr
eadsact i
vebef orest ar
t()
=" ,
threading.activ
e_ count())
pri
nt ("Execut ionst at usofsubt hreadt 1bef or
est art()
=",t
1.is_ al
ive())#False
pri
nt ("Execut ionst at usofsubt hreadt 2bef or
est art()
=",t
2.is_ al
ive()
)#Fal se
t1.star t
()
t2.star t
()
pri
nt ("\nNumberoft hr
eadsact i
veaf t
erst art(
)=",
threading.act i
ve_count (
))
pri
nt ("Execut ionst at usofsubt hreadt 1afterstart(
) =",
t1.i
s_ ali
ve())#Tr ue
pri
nt ("Execut ionst at usofsubt hreadt 2afterstart(
) =",
t2.i
s_ ali
ve())#Tr ue
#subthr
eadsacti
vecount
.py
i
mpor tt
hreadi
ng,t
ime
deffun1()
:
pri
nt(
"Hi
")
ti
me.sl
eep(5)
deffun2(s):
pri
nt(
"Hi
,",
s)
ti
me.sl
eep(7)

#mai nprogram
pri
nt ("
DefaultNameoft hread=",threading.
current_
thread().name)#Mai nThr ead
t1=threading.Thread(t
arget=fun1)#her et1iscall
edsubt hread
t2=threading.Thread(t
arget=fun2, args=("
Rossum" ,))#her et 2iscalledsubt hread
pri
nt ("
DefaultNameofsubt hread=" ,t1.
name)#Thr ead-1
pri
nt ("
defaultNameofsubt hread=" ,t2.
name)#Thr ead-2
#assi gnUser -
Freindl
yNamet othesubt hreads
t1.name=" Rossum" # t 1.setName( "
Rossum" )-
--
-isdeprecat edtoanat tr
ibute
"name"
t2.name=" Rit
che" # t 2.setName( "
Rit
che")-
--
-i
sdepr ecat edtoanat tr
ibute
"name"
pri
nt ("
Nameofsubt hr
ead=" ,t1.
name)
pri
nt ("
Nameofsubt hr
ead=" ,t2.
name)
pri
nt ("
\nNumberoft hr
eadsact i
vebef or
est ar
t()
=",
threading.activ
e_count())
t1.start
()
t2.start
()
pri
nt ("
\nNumberoft hr
eadsact i
veaf t
erstart(
)="
,t
hreading.act i
ve_count(
))

#subthr
eadsjoin.
py
i
mpor tt
hreading,
ti
me
deffun1()
:
pri
nt("
Hi")
ti
me.sleep(10)

deff
un2(
s):
pri
nt(
"Hi
,",
s)
ti
me.sl
eep(12)

#mai nprogr am
pri
nt (
"DefaultNameoft hread=",threading.
current
_thread().
name)#Mai nThr ead
t1=threading.Thread(
tar
get=fun1)#her et1iscall
edsubt hread
t2=threading.Thread(
tar
get=fun2, args=("
Rossum" ,
))#her et2iscal
ledsubt hread
pri
nt (
"DefaultNameofsubt hread=" ,t1.
name)#Thr ead-1
pri
nt (
"defaultNameofsubt hread=" ,t2.
name)#Thr ead-2
#assignUser -
Freindl
yNamet othesubt hreads
t1.name=" Rossum" # t 1.setName( "
Rossum" )
--
--isdeprecatedt
oanat tr
ibute
"name"
t2.name=" Rit
che" # t 2.setName( "
Rit
che")-
--
-i
sdepr ecatedtoanatt
ribute
"name"
pri
nt("
Nameofsubt hread=",t
1.name)
pri
nt("
Nameofsubt hread=",t
2.name)
pri
nt("
\nNumberoft hreadsact i
vebeforest ar
t()
=",t
hr eading.activ
e_ count()
)#1
pri
nt("
Execut
ionst atusofsubt hr
eadt 1beforestart (
)=",t1.
is_alive())#False
pri
nt("
Execut
ionst atusofsubt hr
eadt 2beforestart (
)=",t2.
is_alive())#False
t1.
start
()
t2.
start
()
pri
nt("
\nNumberoft hreadsact i
veafterstart(
)=",
threading.activ
e_ count())#3
pri
nt("
Execut
ionst atusofsubt hr
eadt 1afterstart(
)=" ,t
1.i
s_alive())#Tr ue
pri
nt("
Execut
ionst atusofsubt hr
eadt 2afterstart(
)=" ,t
2.i
s_alive())#Tr ue
#maket heMai nThreadt owaituntilsubthreadsj oin.
t1.
joi
n()
t2.
joi
n()
pri
nt("
\nLi
ne-33:Numberoft hreadsactiveaf t
ercompl eti
onof
exec=",
thr
eading.activ
e_ count
())#1
pri
nt("
Execut
ionst atusofsubt hr
eadt 1aftercompl et i
onofexec=" ,t1.
is_al
ive(
))#
False
pri
nt("
Execut
ionst atusofsubt hr
eadt 2aftercompl et i
onofexec=" ,t2.
is_al
ive(
))#
False

#SecondAppr oachEx1. py
i
mpor tthreadi
ng #st ep-1
# st ep-2 step-3
cl
assSampl e(
threading.Thread)
:
defrun(self)
:#st ep-4
print(
"\nNameofsubt hread="
,t
hreadi
ng.
cur
rent
_thr
ead(
).
name)
print(
"iam from r
un(
)")

#mai nprogr
am
pri
nt("
Defaul
tNameoft hr
ead=",
threading.
current_t
hread(
).
name)#Mai
nThr
ead
#createasubthread
t1=Sample()
t1.
name=" OOPS"
pri
nt("
Issubthr
eadaliv
ebeforestart=",
t1.
is_
aliv
e())
#False
t1.
start
()
pri
nt("
Issubthr
eadaliv
eafterst
art=",t
1.i
s_al
ive()
)#True

#wri
teat hr
eadbasedappl i
cati
onwhi chwi ll
generateamul
ti
pli
cati
ont
abl
efora
gi
vennumberbyusi ngthreadswi t
hoopappr oach.
#SecondApproachEx2.py
i
mpor tt
hreadi
ng,ti
me
cl
assMul Tabl
e(t
hreading.Thread):
defrun(self)
:#ov erri
dingther un()
self.
n=int(
input(
"Enteranumber :"
))
if
(self.
n<=0):
pri
nt("
{}isi
nv ali
dnumber :
".
for
mat
(sel
f.n)
)
else:
pri
nt("
-"*
50)
pri
nt(
"Mul Tablefor{}
".
for
mat(sel
f.
n))
pri
nt(
"-
"*50)
forii
nrange(1,11):
print
("\
t{}x{}={}
".
for
mat(sel
f.
n,i
,
sel
f.
n*i
))
ti
me. sl
eep(1)
pri
nt(
"-
"*50)

#mainprogr
am
mt=MulTabl
e()#cr
eat
ingsubt
hread
mt.
star
t()

#ThirdAppr oachEx1. py
i
mpor tt hreading#st ep-
1
classTest : #Step-2
def hell
o(self,
s):#step-3
print("
\nNameofsubt hr
ead=",
thr
eading.cur
rent
_thr
ead(
).
name)
print("
Hell
o, {
},GoodMor ni
ng".
for
mat (
s))
print("
Iam from hel
lo(
)ofTestClass")
print("
herehello(
)executedbysubthread")
#mai npr ogram
t=Test()# Cr eat
eanobj ectProgrammer -
defi
nedclass-
-step-
4
subth=thr eadi
ng.Thread(target=t.
hel
l
o,args=(("
Rossum" ,
)))# #creat
esubthr
ead-
-
Step-5
subth.start()# #step- 6

#ThirdAppr oachEx2. py
i
mpor tt hreading#st ep-1
i
mpor tt i
me
classRoohi : #St ep- 2
deftable(self,
n):#st ep-3
if(n<=0):
pri
nt("
{}isinvali
di nput:
".
format(n))
else:
pri
nt("
="*50)
pri
nt("
Mul Tablef or:{}
".
format(n))
pri
nt("
="*50)
forii
nr ange(1,11):
pri
nt("
\t{}x{}={ }
".
format(n,
i,
n*i
))
ti
me.sleep(1)
pri
nt("
="*50)
#mai npr ogram
R=Roohi ()#Cr eateanobj ectProgrammer -
def i
nedclass--st
ep-4
t1=threading.Thread(target=R.t
able,args=((int(
input(
"Enteranumber:"
)),
)))#
createsubt hr
ead--Step-5
t1.st
art()#st ep-6
#EvenOddFi r
stAppar ch.py--
--
--
-Funct ionalApproach
i
mpor tt
ime, t
hreadi ng
defevennumber s(n):
print
("="*50)
tn=threadi ng.current_
thread( ).name
#pr i
nt("NameofSubThr ead={ }"
.f
ormat(t
n))
if
(n<=0) :
print("
{}isinvali
di nput :
".
format(
n))
else:
fori i
nr ange(2,n+1,2):
pri
nt("\
tEv enNumbergener atedby{}
={}
".
for
mat
(tn,
i
))
ti
me. sl
eep( 1)
print
("="*50)
defoddnumber s(n):
print
("="*50)
tname=t hreading.current_thread().name
#pr i
nt("NameofSubThr ead={ }"
.f
ormat(t
name) )
if
(n<=0) :
print("
{}isinvali
di nput :
".
format(
n))
else:
fori i
nr ange(1,n+1,2):
pri
nt("\
tOddNumbergener atedby{}={}
".
for
mat
(t
name,i
))
ti
me. sl
eep( 1)
print
("="*50)

#mainpr ogram
ont
=threading.
Thr
ead(t
arget
=oddnumbers,args=((
50,)
))#Creati
ngsubthread-1
ent
=threading.
Thr
ead(t
arget
=evennumbers,args=(
(50,
)))#Creat
ingsubthread-
2
#di
splatchthesubthr
eads
ont
.st
art()
ent
.st
art()

#EvenOddSecondAppar ch.py -
--
--
--OOPsAppr oachwi thI
nheri
tance
i
mpor tthreadi
ng
i
mpor tti
me
cl
assEv enNumber (
threading.Thread):
defsetnumber (self,
n):
self.
n=n
def run(
sel f
):
print(
"="*
50)
tn=threading.current_
thread( )
.name
i
f(self.
n<=0) :
print("
{}isinval
idinput :
".f
ormat
(sel
f.n)
)
else:
fori i
nr ange(2,
self.n+1,2):
pri
nt("
\tEvenNumbergener at
edby
{}
={}
".f
ormat (t
n,i
))
ti
me.sleep(1)
pr
int
("
="*
50)

cl
assOddNumber (t
hreading.Thread) :
defsetnumber (self,
n):
self.
n=n
def r
un(sel f
):
print(
"="*
50)
tn=threading.current_
thread()
.name
i
f(self.
n<=0) :
print
( "
{}isinval
idinput:
".f
ormat
(sel
f.
n))
else:
foriinr ange(1,
self.
n+1,2):
pri
nt("
\tOddNumbergeneratedby
{}
={}
".
for
mat(
tn,
i))
ti
me.sleep(
1)
print(
"="*
50)

#mai npr ogram


#creat etwosubt hreads
ent=Ev enNumber ()
ont=OddNumber (
)
#sett hev al
ueforsubt hr
eads
ent.
set number (
50)
ont.setnumber (
50)
#dipat chthethreads
ont.start(
)
ent.
st art
()

#EvenOddThi rdApparch.py--
---
--OOPsAppr oachwithoutI
nher
itance
i
mpor tthreadi
ng
i
mpor tti
me
cl
assEv enNumber :
def evennums( self,
n):
print
("="*
50)
tn=thr
eadi ng.current_
thread().
name
if
(n<=0):
print
( "
{}isinval
idinput:
".
format(
n))
else:
foriinr ange(2,
n+1,2):
pri
nt("
\tEvenNumbergeneratedby
{}
={}
".f
ormat (t
n,i
))
ti
me.sleep(1)
print
("="*
50)

cl
assOddNumber :
def oddnums( self
,n)
:
pri
nt("
="*50)
tn=thr
eading.curr
ent_
thr
ead()
.name
i
f(n<=0):
pri
nt("
{}i
sinval
i
dinput:
".
for
mat
(n)
)
el
se:
f
ori
inr
ange(
1,n+1,
2):
pr
int
("
\tOddNumbergener
atedby
{
}={
}"
.f
ormat
(tn,
i
))
t
ime.
sleep(
1)
pr
int
("
="*
50)

#mai nprogram
otn=OddNumber ()
ent=EvenNumber ()
#createsubt hreads
st1=thr
eading.Thr ead(
tar
get
=otn.
oddnums,args=((
40,)
))
st2=thr
eading.Thr ead(
tar
get
=ent.
evennums,args=(
(40,
)))
#dispatchthethr eads
st1.
start(
)
st2.
start(
)

Sy
nchronizat
ioninMult
iThreadi
ng
(OR)
Locki
ngconceptinThreadi
ng

=>Whenmul tiplethreadsar eoper ati


ng/wor kingont hesamer esour
ce(funct i
on/
method)thenbydef aultwegetdeadl ockresul t/raceconditi
on/wr ongr esult/non
-t
hreadsaf etyresult.
=>Toov ercomet hisdeadl ockpr oblems,wemustappl ytheconceptSynchr onizati
on
concept.
=>Theadv ant ageofsy nchr oni
zationconcepti sthattoav oi
ddeadl ockresultand
provi
desThr eadSaf etyResul t
.
=>InPythonPr ogrammi ng, wecanobt ai
nsynchr onizat
ionconceptbyusi ngl ocking
andun-lockingconcept .
=>Stepsforimpl ementingSy nchronizati
onConcept :
1)obtai
n/cr eateanobj ectofLockcl ass,whichi spresentinthreadi
ngmodul e.
Syntax:
- l
ockobj=threading.Lock()

2)Toobt aint
helockont hesharabl
eresource,wemustuseacqui
re(
)
Syntax: l
ockobj
.acqui
re()
Oncecurrentobjectacquir
ethelock,
otherobject
sar
emadewai tunt
ilcur
rentobj
ect
rel
easest hel
ock.

3)Toun- l
ockt heshar abler esource/curr
entobject,wemustuser elease(
)
Syntax: l
ockobj .
release()
Oncecur rentobjectreleasest helock, ot
herobjectsareper
mittedintosharabl
e
resource.Thi sprocessofacqui ri
ngt hereleasi
ngt hel
ockwill
becont i
nuedunti
lal
l
theobj ectscompl etedt heirexecution.
#APr ogr am forshowi ngI nconsistentResult(or)non-
thr
eadsaf et
yr esul
tin
threadingpr ogram
#nonlocki ngFunctional.py
i
mpor tti
me
i
mpor tthreading
defmul
table(n)
:
print(
"NameofSubThr eadi nmul t
able()
=",
thr
eading.
cur
rent
_thr
ead(
).
name)
i
f(n<=0):
pri
nt(
"{}isinvali
di nput"
.f
ormat (
n))
else:
pri
nt(
"-
"* 50)
pri
nt(
"Mul t
ablefor{ }
".
format(n))
pri
nt(
"-
"* 50)
forii
nr ange(1,11):
pri
nt("
\t{}x{}={ }
".
format(n,
i
,n*
i))
ti
me.sleep(1)
pri
nt(
"-
"* 50)

#mai nprogram
t1=t
hreading.Thr
ead(
tar
get
=mul
tabl
e,
args=(
(6,
)))
t2=t
hreading.Thr
ead(
tar
get
=mul
tabl
e,
args=(
(16,
)))
t3=t
hreading.Thr
ead(
tar
get
=mul
tabl
e,
args=(
(19,
)))
t4=t
hreading.Thr
ead(
tar
get
=mul
tabl
e,
args=(
(14,
)))
t1.
start
()
t2.
start
()
t3.
start
()
t4.
start
()

#APr ogr am f orshowi ngI nconsistentResul t(or)non-t


hreadsafetyr
esul
tin
threadingpr ogram
#lockingFunct ional.
py
i
mpor tti
me
i
mpor tthreadi ng
defmul table(n):
L.acqui r
e() #obt ai
nt helock--Step-2
print("
NameofSubThr eadi nmul table()="
,t
hreading.
cur
rent
_thr
ead(
).
name)
i
f(n<=0) :
pri
nt(
"{}isinvali
di nput".
format (n)
)
else:
pri
nt(
"-
"* 50)
pri
nt(
"Mul t
ablefor{ }
".
format (n))
pri
nt(
"-
"* 50)
forii
nr ange(1,11):
pri
nt("\
t{}x{}={ }".
format (
n,i
,n*
i))
ti
me.sleep(1)
pri
nt(
"-
"* 50)
L.release()#releaset helock--Step-3

#mai nprogr am
#createanobj ectofLockofthr
eadi
ngmodul e--
Step-
1
L=threading.Lock()#hereLisanobjectofLockclass
t1=threading.Thr
ead(tar
get
=multabl
e,ar
gs=((
-6,
)))
t2=threading.Thr
ead(tar
get
=multabl
e,ar
gs=((
16,)
))
t3=threading.Thr
ead(tar
get
=multabl
e,ar
gs=((
-19,
)))
t4=threading.Thr
ead(tar
get
=multabl
e,ar
gs=((
14,)
))
t
1.st
art
()
t
2.st
art
()
t
3.st
art
()
t
4.st
art
()

#APr ogram forshowi ngI nconsi


st antResul t(or)non-threadsafetyresulti
n
threadingpr ogram
#NonLocki ngOopswi thI
nh. py
i
mpor tthreading,ti
me
classMul Table(
threadi ng.Thread):
defset val
ue( self,
n):
self.
n=n
defrun(self):
print("
NameofSubThr eadi n
run()=",
threading.cur r
ent _t
hread().
name)
i
f(self.n<=0):
pri
nt(
"{}isinvali
di nput".f
ormat (sel
f.
n))
else:
pri
nt(
"-"
* 50)
pri
nt(
"Mul t
ablefor{ }"
.format(self.
n))
pri
nt(
"-"
* 50)
forii
nr ange(1,11):
pri
nt("
\t{}x{ }={}".
format (
self
.n,
i,
self
.n*i
))
ti
me.sleep(1)
pri
nt(
"-"
* 50)

#mai nprogram
t1=MulTable()
t2=MulTable()
t3=MulTable()
t4=MulTable()
#setthev al
uestothesubt
hreads
t1.
setvalue(
3)
t2.
setvalue(
14)
t3.
setvalue(
20)
t4.
setvalue(
-13)
#dispatchthethr
eads
t1.
start
()
t2.
start
()
t3.
start
()
t4.
start
()

#APr ogr am forshowi ngInconsi


stantResul
t(or
)non-
thr
eadsaf
etyr
esul
tin
threadingpr ogram
#Locki ngOopswi thInh.
py
i
mpor tthreading,
time
classMul Tabl
e(threading.
Thread)
:
defset v
alue(self
,n)
:
self.
n=n
defr un(self):
L.acquir
e()#st ep-2
print(
"NameofSubThr eadi n
run()
=" ,
threadi ng.cur r
ent_t
hread().
name)
if
(self.
n<=0):
pri
nt("
{}isinvali
di nput"
.f
ormat(sel
f.
n))
else:
pri
nt("
-"*50)
pri
nt("
Mul t
ablefor{ }
".
format(
self.
n))
pri
nt("
-"*50)
forii
nr ange(1,11):
pri
nt("
\t{}x{}={ }
".
for
mat (
self
.n,
i
,sel
f.
n*i
))
ti
me.sleep(1)
pri
nt("
-"*50)
L.rel
ease()#step- 3
#mai npr ogr am
L=threadi ng.Lock( )#St ep-1
t1=Mul Tabl e()
t2=Mul Tabl e()
t3=Mul Tabl e()
t4=Mul Tabl e()
#sett hev aluest ot hesubt hreads
t1.
setv alue(3)
t2.
setv alue(14)
t3.
setv alue(20)
t4.
setv alue(-13)
#dispat cht het hreads
t1.
star t
()
t2.
star t
()
t3.
star t
()
t4.
star t
()

#APr ogram forshowi ngI nconsistantResult(or


)non-threadsafetyr
esul
tin
threadingpr ogram
#NonLocki ngOopswi thoutInhex.
py
i
mpor tthreading,ti
me
classMul Table:
def__ini
t__ (
self):
self.
n=i nt(
input("
EnteraNumberf orMul Table:
")
)
deftable(self):
print("
NameofSubThr eadin
run()=",
threading.cur r
ent _t
hread().
name)
i
f(self.n<=0):
pri
nt("
{}isinvali
dinput".
for
mat (sel
f.
n))
else:
pri
nt("
-"*
50)
pri
nt("
Mul t
ablefor{}"
.f
ormat(self.
n))
pri
nt("
-"*
50)
forii
nrange(1,
11):
pri
nt(
"\t
{}x{}={
}"
.f
ormat
(sel
f.
n,i
,
sel
f.
n*i
))
ti
me.sl
eep(1)
pri
nt(
"-
"*50)

#mai nprogram
t1=MulTable()
t2=MulTable()
t3=MulTable()
t4=MulTable()
#createsubt hreads
st1=thr
eading.Thread(
tar
get
=t1.
tabl
e)
st2=thr
eading.Thread(
tar
get
=t2.
tabl
e)
st3=thr
eading.Thread(
tar
get
=t3.
tabl
e)
st4=thr
eading.Thread(
tar
get
=t4.
tabl
e)

#di
spatchthet
hreads
st
1.st
art(
)
st
2.st
art(
)
st
3.st
art(
)
st
4.st
art(
)

#APr ogram forshowi ngI nconsi st antResul t(or)non-threadsafetyresulti


n
threadingpr ogram
#Locki ngOopswi thout Inhex1. py
i
mpor tthreading,ti
me
classMul Table:
@classmet hod
defget l
ock( cls):
cls.KVR=t hreading. Lock( )#cr eati
ngal ockont henameof" KVR"
--
-
Step-1
def__ini
t__ (
self):
self.n=int(input("Ent eraNumberf orMul Table:
"))
deftable(self):
Mul Tabl e.KVR. acqui re()#St ep-2
print("
NameofSubThr eadi n
run()=",
threading.cur r
ent _thread( ).
name)
i
f(sel f
.n<=0) :
pr i
nt("{}isinv ali
di nput "
.f
ormat (sel
f.
n))
else:
pr i
nt("-
"* 50)
pr i
nt("Mul tablefor{ }".
format(self.
n))
pr i
nt("-
"* 50)
fori inr ange( 1,11):
print("
\t{}x{ }={ }
".
format (
self
.n,
i,
self
.n*i
))
ti
me. sleep( 1)
pr i
nt("-
"* 50)
Mul Tabl e.KVR. release( )#St ep-3
#mai npr ogram
Mul Table.getl
ock( )#Cal l
ingCl assLev elMet hod
t1=MulTable()
t2=MulTable()
t3=MulTable()
t4=MulTable()
#createsubthr eads
st1=thr
eading.Thr ead(
tar
get
=t1.
tabl
e)
st2=thr
eading.Thr ead(
tar
get
=t2.
tabl
e)
st3=thr
eading.Thr ead(
tar
get
=t3.
tabl
e)
st4=thr
eading.Thr ead(
tar
get
=t4.
tabl
e)
#dispatchthethr eads
st1.
start(
)
st2.
start(
)
st3.
start(
)
st4.
start(
)

NumPy
I
ntr
oduct
iont
oNumpy
:

=>NumpystandsforNumericalPyt
hon.
=>Numpyisoneoft hepr
e-defi
nedthi
rdpartymodule/Libraryandnumpymodul
eis
notapre-
defi
nedmoduleinPy t
honLanguage.
=>Tousenumpyasapar tofourpythonprogram,
wemusti nstal
lnumpy
moduleexpli
ci
tl
ybyusingat ool
call
edpipanditpresentin

(
C:\
User
s\nar
eshi
t\
AppDat
a\Local
\Pr
ogr
ams\
Pyt
hon\
Pyt
hon39\
Scr
ipt
s)

=>Sy
ntaxf
ori
nst
all
i
nganymodul e:
pi
p i nst
all modul
e-name

=>Exampl
e:I
nstal
lnumpymodule
pipinst
allnumpy

=>TouseNumPyaspar
tofourprogr
am,wemustimportNumPymodule.
=>Anumpymodul
eisacol
lect
ionofVar
iabl
es,
Funct
ionsandCl
asses.

Hi
stor
yofNumpy
:

=> NumPy was dev el


oped by study
ing existi
ng module cal
led "Numer
ic
Li
brar
y"(
ori
ginfordevel
opmentofnumpymodule)
=>TheNumericLibr
arywasdevel
opedbyJIM HUNGUNI AN
=>TheNumericLibr
arywasnotabl
etosolvecompl exmathscal
cul
ati
ons.
=>numpymodul edevel
opedbyTRAVISOLIPHANT
=>numpyModul edevel
opedint
heyear2005
=>numpyModul edevel
opedinCandPYTHONl anguages.
Adv
ant
agesofusi
ngNumPy

NeedofNumPy
:

=>Withtherevolut
ionofdat ascience,dataanaly si
sli
brari
esl
ikeNumPy ,SciPy,Scikit
,
Pandas,etc.hav eseenal otofgr owt h.Wi t
hamucheasi ersy nt
axt hanot her
programminglanguages, pythonisthefirstchoicelanguagef
orthedatasci ent
ist
.
=>NumPypr ovidesaconv enientandef f
icientwayt ohandlet
hev astamountofdat a.
NumPyi salsov er
yconv eni
entwi thMat r
ixOper ati
onsanddat ar
eshaping.NumPyi s
fastwhichmakesi treasonabletowor kwi thalargesetofdata.

Theadv
ant
agesofNumpyPr
ogr
ammi
ngar
e:

1)Wi thNumpyPr ogrammi ng,wecandealwi thArrays such1-D,2- D andMulti


DimensionalAr r
ay s.
2)NumPymai nt
ai nsmi nimal memor y
:
3)Numpypr ovidesFasti nPer formingOper ati
onsbecauseinternal
lyitsdat ais
avail
ableatsameaddr ess.
4)NumPyper formsar ray-
or i
entedcomput ing.
5)Iteff
icient
lyimpl ement st hemul t
idimensionalar
rays.
6)Itperformssci enti
ficcomput at
ions.
7)Iti
scapabl eofper f
or mingr eshapingthedat astor
edinmulti
dimensionalarr
ays.
8)NumPypr ov i
des Manyi n-
builtfuncti
ons forVar i
ous ComplexMat hemati
cal
Operati
onssuchasst ati
stical,fi
nancial
,tr
igonomet r
icOper
ati
onset c.

Py
thonTr
adi
ti
onal
ListVSNumPyModul
e

Si
mil
ari
ti
esofpy
thonTr
adi
ti
onal
ListVSNumPyModul
e:

=>Anobjectoflistusedt ostoremul ti
pleval
uesofsamet ypeordifferenttypeand
botht
ypes( uni
que+dupl icat
es)insingl
eobject .
=>I
nNumPyPr ogrammi ng,thedat aisorganizedint heobj
ectof"ndarray"
,whichis
oneofthepr e-
defi
nedcl assinnumpymodul e.Henceanobj ectofndarraycanst or
e
sametypeordi f
ferentty
peandbot ht ypes(unique+dupli
cat
es)insingleobject.
=>Theobjectsofndarrayandl i
staremut abl
e( changescantakespl
ace)

Di
ff
erencesbet
weenPy
thonTr
adi
ti
onal
Listandndar
rayobj
ectofNumpyModul
e:

=>Anobj ectofl istcont ai


nsbothhomogeneousandhet er ogeneousv alueswhereas
anobj ectofndar rayofnumpycanst oreonlysimilart
ypeofv alues(evenwest ore
di
fferentv alues,int ernall
ytheyar etreatedassi milart
y pebyt reati
ngal lval
uesof
ty
pe" obj ect") .
=>Ont heobj ectofl ist,wecan'tperform Vect orOperat
ions.wher easont heobject
ofndar ray, wecanper form Vectorbasedoper ati
ons.
=>Inl argesampl ingofdat a,Listbasedappl i
cati
onst akesmor ememor yspace
wher endar r
ayobj ectt akeslessmemor yspace.
=>Listbasedappl icationsar enotefficient becauseli
stobj ectv al
uest akesmor e
ti
met oextractorretri
eve(theyareavai
labl
eatdi f
ferentAddr
ess)whereas numpy
basedapplicati
onsar eeff
ici
entbecauseofndar rayobjectval
uestakeslesst
ot i
me
toextr
actorr et
ri
eve(theyareavai
labl
eatsameAddr ess).
=>Li
stobjectcan'tperfor
m complexmat hematicaloperati
onswhereasanobj ectof
ndarr
aycanper form complexmathematicaloperati
ons.

ndar
ray

=>ndr
rayisoneofthepr e-
def i
nedcl
asspr
esentinnumpymodul
e.
=>Thepurposeofndarrayclassandwhoseisthat"Tost
oret
hedatai
nent
ir
enumpy
progr
ammi nginthefor
m Ar ray.
"
=>Anobjectofndarr
aycanbecr eat
edi
n7way s.

1.array(
)
2.arange()
3.zeros()
4.ones()
5.ful
l()
6.eye()
7.i
dent i
ty(
)

Numberofappr
oachest
ocr
eat
eanobj
ectofndar
ray

=>I
nnumpypr
ogrammi ng,wehav
e7appr
oachest
ocr
eat
eanobj
ectofndar
ray
.
Theyar
e
1.array(
)
2.arange()
3.zeros()
4.ones()
5.ful
l()
6.eye()
7.i
dent i
ty(
)

1)ar
ray
():

=>ThisFunct
ioni
susedforconv
ert
ingTradi
ti
onalPythonObj
ect
sint
ondr
rayobj
ect
.
=>Syntax:
- var
name=numpy.
array
(Object,
dty
pe)
Herev arnamei sanobjectof<class,
ndar
ray
>
herear r
ay()ispre-
defi
nedf uncti
onofnumpymodul
eusedforconv
erti
ngTradit
ional
PythonObj ectsint
ondrrayobject.
objectrepresentsanyTradi
tionalPyt
honObject
s
dtyper epresentsanynumpydat atypesuchasi
nt8,
i
nt16,
int
32,
fl
oat16,fl
oat32,
fl
oat64,..
..
etc

Exampl
es:

>>>impor tnumpyasnp
>>>l1=[10,20,30, 40,50,60]
>>>print(l
1,type( l
1))---
--
---
--
----
---
[10,20,30,40,50,60]<class'l
ist
'>
>>>a=np. array(l1)
>>>print(a,
type( a))--
---
---
--
---
---[
102030405060]<cl ass'numpy .
ndarray'
>
>>>t=(10,20,30,40, 50,60,70)
>>>print(t,
type(t))--
---
---
--
---
-(10,20, 30,40,50,60,70)<class't
uple'
>
>>>a=np. array(t)
>>>print(a,
type( a))--
---
---
--
---
-[10203040506070]<cl ass'numpy .
ndarr
ay'
>
>>>d1={ 10:1.2,20:4.5,30:6.7}
>>>a=np. array(d1)
>>>a---
-array({10: 1.2,20: 4.5,30: 6.7}
,dtype=obj
ect)
--
--
--
--
--
---
----
--
---
---
----
---
---
---
--
---
----
--
---
--
---
--
--
--
--
---
--
--
--
--
--
--
--
--
---
>>>t=(10,20,30,40, 50,60)
>>>a=np. array(t)
>>>a---
---
---
--
---array([10,20, 30,40, 50,60]
)
>>>a.ndim- -
---
-----
--1
>>>a.dtype----
---
---dtype('
int32')
>>>a.shape- --
---
----
---
(6,)
>>>b=a. r
eshape( 3,2)
>>>c=a.reshape( 2,3)

>>>b-
--
--
--
--
--
--
-
ar
ray
([[
10,20],
[
30,40],
[
50,60]]
)
>>>c
arr
ay (
[[
10, 20,30],
[40,50, 60]]
)
>>>pri
nt(b,
type(b))
[
[1020]
[3040]
[5060] ]<cl
ass'
numpy.ndar
ray
'>
>>>d=a.r
eshape( 3,
3) -
--
--
--Val
ueEr
ror
:cannotr
eshapear
rayofsi
ze6i
ntoshape(
3,3)

>>>t1=(
(10,
20),(
30,40))
>>>pri
nt(
t1,
type(t
1))-
--
--
---
--
--
--
((10,
20)
,(30,
40)
)<cl
ass'
tupl
e'
>
>>>a=np.ar
ray(
t1)
>>>a
arr
ay([
[10,20],
[30,40]]
)
>>>a.ndim---
---
--
--2
>>>a.shape----
--
---
-(2,2)
--
--
--
--
--
---
--
--
--
----
--
---
---
---
--
--
--
--
--
---
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
-
>>>t1=(((10,20,15),(
30,40,
25)),
((50,60,
18),
(70,
80,35)))
>>>print
(t1,
type( t
1) )
((
(10,20,15),(30, 40,25)),
((50,60,18),(
70,80,35))
)<class'
tupl
e'>
>>>a=np.array(t1)
>>>print
(a)-
----
--
---
--
[
[[102015]
[304025] ]

[[506018]
[708035] ]
]
>>>a.ndim---
--
---
--3
>>>a.shape---
--
-(2, 2,3)
>>>b=a.reshape( 4,3)
>>>b---
--
---
--
--
---
array([
[10,20,15],
[30,40,25],
[50,60,18],
[70,80,35]]
)
>>>c=a.reshape(3, 4)
>>>c---
--
---
--
--
--
---
arr
ay ([[
10, 20,15,30],
[40,25, 50,60],
[18,70, 80,35]]
)

>>>d=a.r
eshape(3,
2,2)
>>>d--
--
--
--
--
--
ar
ray([
[[
10,20],
[
15,30]]
,

[
[40,
25]
,
[50,
60]
],

[
[18,
70]
,
[80,
35]
]]
)
>>>d[0]
--
--
--
--
--
arr
ay([
[10,20],
[15,30]]
)
>>>d[1]
--
--
--
-
arr
ay([
[40,25],
[50,60]]
)
>>>d[2]
--
--
--
arr
ay([
[18,70],
[80,35]]
)
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--

2.ar
ange(
):
-
--
---
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
---
--
---
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
Syntax1:
-v arname=numpy .
arange(Value)
Syntax2:
-v arname=numpy .
arange(Start
,St
op)
Syntax3:
-v arname=numpy .
arange(Start
,St
op,St
ep)
=>Herevarnameisanobj ectof<class,ndarr
ay>

=>Sy nt
ax-1cr eatesanobjectofndarr
aywi t
ht hevaluesfr
om 0t oval
ue-1
=>Sy nt
ax-2cr eatesanobjectofndarr
aywi t
ht hevaluesfr
om Startt
oStop-1
=>Sy nt
ax-3cr eatesanobj ectofndarraywi t
ht hev al
uesfrom Startt
oSt op-
1wi t
h
equal
Inter
valofVal ue-st
ep
=>arange()alway screat
eanobj ectofndarrayin1-DarrayonlybutnotPossibl
eto
createdirectly2-DandMul t
iDimesionalArrays.
=>Tocr eate2- DandMul t
iDimesionalArrays,wemustuser eshape()

Exampl es:
--
--
--
--
--
----
---
>>>impor tnumpyasnp
>>>a=np. arange( 10)
>>>a---
----
---
-array([0, 1,2,3,4, 5,6, 7, 8,9])
>>>a.ndim- --
-----
1
>>>a=np. arange( 50, 62)
>>>print(a,type(a)) -
--[
505152535455565758596061]<cl ass'numpy.ndarr
ay'
>
>>>a.ndim- --
---1
>>>a=np. arange( 10, 23,2)
>>>a---
--array([10, 12, 14,16, 18, 20, 22])
>>>a=np. arange( 10, 22,2)
>>>a---
----
-array (
[10, 12, 14,16, 18, 20] )
>>>b=a. reshape( 2, 3)
>>>c=a. r
eshape( 3,2)
>>>b---
--
ar ray([[
10, 12,14],
[16,18, 20]])
>>>c
ar ray([[
10, 12],
[14,16] ,
[18,20] ]
)
>>>b.ndim- --
---2
>>>c.ndim- --
----2
>>>b.shape- ---
-(2, 3)
>>>c.shape- ---
-(3,2)
>>>l1=[[[10,20] ,
[30, 40]]
,[[
15, 25],
[35,45] ]]
>>>l1--
---
----
-[
[[10, 20] ,[
30, 40]],[
[15, 25], [
35,45]
]]
>>>a=np. arange( l1) --
---
--
--
-Ty peError: unsupport
edoper
andt
ype(s)for-
:'
li
st'and'i
nt'

3.zer
os(
):

=>Thi
sFunct
ioni
susedf
orbui
l
dingZEROmat
ri
xei
therwi
th1-
Dor2-
Dorn-
D
=>Sy
ntax:v
arname=numpy
.zer
os(
shape,
dty
pe)

=>HereShapecanbe1-D(
numberofZer
os)or2-
D(Rows,
Col
s)orn-
D(Numberof
Matri
ces,
NumberofRows,
NumberofCol
umns)

#zeromatri
cdemonst rati
on
#zm.py
i
mpor tnumpyasnp
m,n=int
(i
nput(
"EnterNumberofRows: ")
),i
nt(
input
("
Ent
erNumberofCol
umns:
")
)
i
f(m<=0)or(n<=0):
pri
nt(
"I
nvalidDimensions:
")
el
se:
zm=np.zeros((m,n)
,dty
pe=int
)
pri
nt(
zm)

Examples:
--
--
--
--
--
--
--
--
---
-
>>>importnumpyasnp
>>>a=np.zeros(12)
>>>a--
--
--
---
--
array (
[0.,
0.,0.
,0.,
0.,0.
,0.
,0.,
0.,
0.,
0.,
0.]
)
>>>a=np.zeros(12,dtype=i
nt)
>>>a--
--
--
---
--
-array([0,
0,0,0,0,0,0,
0,0,0,0,
0])
>>>a.r
eshape( 3,4)
ar
ray([
[0,
0,0,0]
,
[0,
0,0,0]
,
[0,
0,0,0]
])

>>>a.
reshape(
2,6)
arr
ay([
[0,
0,0,0,
0,0],
[0,
0,0,0,
0,0]]
)
>>>a.
reshape(
2,3,2)
arr
ay([
[[
0,0]
,
[
0,0]
,
[
0,0]
],

[
[0,
0],
[0,
0],
[0,
0]]
])

>>>a.r
eshape(
2,2,
2,
2)-
--
--
-Val
ueEr
ror
:cannotr
eshapear
rayofsi
ze12i
ntoshape
(2,
2,
2,
2)

>>>i
mportnumpyasnp
>>>a=np.
zer
os(
(3,
3),
dty
pe=int
)
>>>a
arr
ay([
[0,
0,0],
[0,
0,0],
[0,
0,0]]
)
>>>a=np.
zer
os(
(2,
3))
>>>a
arr
ay (
[[
0., 0.
,0.]
,
[0.,0.,0.]
])
>>>a=np.
zer
os(
(2,
3),
int)
>>>a
arr
ay (
[[
0, 0,0],
[0,0,0] ]
)
>>>a=np.
zer
os(
(3,
2,
3) ,
dtype=int)
>>>a
arr
ay (
[[
[0, 0,0]
,
[0,0,0]]
,

[
[0,
0,0]
,
[0,
0,0]
],

[
[0,
0,0]
,
[0,
0,0]
]]
)
>>>pr
int
(a,
type(
a))
[
[[
000]
[
000]
]

[
[000]
[000]
]

[
[000]
[000]]
] <class'numpy.ndar
ray'
>
-
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
4.ones(
)

=>ThisFunct
ionisusedforbuil
dingONEsmat r
ixei
therwi
th1-
Dor2-
Dorn-
D
=>Syntax:varname=numpy.ones(shape,
dty
pe)

=>HereShapecanbe1-D(
numberofZer
os)or2-
D(Rows,
Col
s)orn-
D(Numberof
Matri
ces,
NumberofRows,
NumberofCol
umns)

Examples:
>>>i
mpor tnumpyasnp
>>>a=np.ones(10)
>>>pri
nt(a,
type(a)
) -
--
---
--
--
[1.1.1.1.1.1.1.1.1.1.
]<cl
ass'
numpy.
ndar
ray
'>
>>>a=np.ones(10,dtype=int
)
>>>pri
nt(a,
type(a)
) -
--
---
--
--
---
[1111111111]<cl ass'
numpy.
ndar
ray'
>
>>>a.
shape----
--
---
--(
10,)
>>>a.
shape=( 5,
2)
>>>a
arr
ay (
[[
1,1],
[1,1],
[1,1],
[1,1],
[1,1]]
)
>>>a.
ndim- -
--
---
--
--
--- 2
>>>a.
shape----
--
---
---(5, 2)
>>>a.
shape=( 2,
5)
>>>a
arr
ay (
[[
1, 1,1, 1, 1]
,
[1,1,1, 1,1] ])
>>>a.
shape----
--
---
----
--
-----
--(
2,5)
>>>
>>>a=np.ones((3,
4) ,
dty pe=int)
>>>a
array([[1,1,1,1]
,
[1, 1,1,1]
,
[1, 1,1,1]
])
>>>a=np.ones((4,
3) ,
dty pe=int)
>>>pri
nt(a,
type(a))
[
[111]
[111]
[111]
[111]]<cl
ass'
numpy
.ndar
ray
'>
>>>a.
shape----
--
---
-(4,3)
>>>a.
shape=( 3,
2,2)
>>>a
array([[[1,1]
,
[
1,1]
],

[
[1,
1],
[1,
1]]
,

[[
1,1],
[1,
1]]
])
>>>a=np.
ones(
(4,
3,
3),
dty
pe=int
)
>>>a
arr
ay(
[[[
1,1,1]
,
[
1,1,1]
,
[
1,1,1]
],

[
[1,
1,1]
,
[1,
1,1]
,
[1,
1,1]
],

[
[1,
1,1]
,
[1,
1,1]
,
[1,
1,1]
],

[
[1,
1,1]
,
[1,
1,1]
,
[1,
1,1]
]]
)

>>>a[
0][0][0]
--
--
--
--
--
-1
>>>a[
0,0,0]--
--
--
--
--
-1
>>>a[
0][0,0]-
--
--
--
--
--
-1
================================================================
5)ful
l(
)

=>Thisisfuncti
onisusedf orbuil
dingamat rixbyspecif
yingfi
l
lvalueeit
her1-
Dor2-
Dorn- D
=>Syntax:-
v
arname=numpy .f
ull
(shape,
fi
ll
_val
ue,
dtype)
=>varnamei sanobjectof<class,
numpy .ndarray
>
=>HereShapecanbe1- D(
numberofZer os)or2- D(Rows,Col
s)orn- D(Numberof
Matri
ces,NumberofRows, NumberofCol umns)
=>fi
ll
_valuecanbeanynumberofpr ogr
ammerchoi ce

Examples:
--
--
--
--
--
--
---
--
--
>>>a=np.full
(3,
1)
>>>a---
--
--
--
array([1,1,1])
>>>pri
nt(t
ype(a))--
--
---
-<cl
ass,
numpy.
ndar
ray
>
>>>a=np.full
(6,
8)
>>>a---
--
--
--
---
-ar
r ay(
[8,8,8,8,
8,8]
)
>>>a.shape=(3,2)
>>>a
array([
[8,8],
[
8,8] ,
[
8,8] ]
)
>>>a=np.full
(6,
9)

>>>a=np.f
ull
((
3,3,
3),
7)
>>>a
ar
ray(
[[
[7,7,7]
,
[
7,7,7]
,
[
7,7,7]
],

[
[7,
7,7]
,
[7,
7,7]
,
[7,
7,7]
],

[[
7,7,7]
,
[
7,7,7],
[
7,7,7]]
])
================================================================
6.ey
e()
:

=>Thisfunct
ioni susedforbui
ldi
ngI dent
it
ymat r
ixorunitmat
ri
x.
=>Syntax:
-v ar name=numpy .
eye(N,M=None,K=0,
dtype)
=>HereNr epresent snumberofr ows
=>HereM repr esent snumberofCol umns
=>I
fwedon' tr epresentM val
uet henNv al
uewillbetakenM val
uesandpr
epar
ed
QuareUnitMat rix.
=>HereKr epresent sPr i
ncipl ediagonalelement.ifk=0theni
talway
spoi
ntspr
inci
ple
diagonal
=>Ifk=-1,-
2,-
3...
-nr epresent sBel l
owPr inci
plediagonalel
ements.
=>Ifk=1,2,3.
..-
nr epresent sAbov ePri
nci pl
ediagonalel
ements.
--
---
--
--
--
---
---
--
---
--
Exampl es:
--
---
--
--
--
---
---
--
---
--
>>>impor tnumpyasnp
>>>#v arname=numpy .
eye( N,M=None, K=0,dtype
>>>a=np. eye(3)
>>>pr i
nt(a,t
ype(a) )
[[
1.0.0.]
[0.1.0.]
[0.0.1.]]<class' numpy .
ndar ray'
>
>>>a=np. eye(3,dtype=int)
>>>pr i
nt(a,t
ype(a) )
[[
100]
[010]
[001] ]<class'numpy .ndar ray'>
>>>a=np. eye(3,4,dtype=int)
>>>pr i
nt(a,t
ype(a) )
[[
1000]
[0100]
[0010] ]<class' numpy .ndar ray'
>
>>>a=np. eye(3,4,dtype=int)
>>>pr i
nt(a,t
ype(a) )
[[
1000]
[0100]
[0010] ]<class' numpy .ndar ray'
>
>>>a=np. eye(5,6,dtype=int)
>>>pr i
nt(a,t
ype(a) )
[[
100000]
[010000]
[001000]
[000100]
[000010] ]<cl ass'numpy .ndarray'
>
>>>a=np. eye(3,4,k=-1,
dty pe=int)
>>>pr i
nt(a,t
ype(a) )
[[
0000]
[1000]
[0100] ]<class' numpy .ndar ray'
>
>>>a=np. eye(5,6,k=-1,
dty pe=int)
>>>pr i
nt(a,t
ype(a) )
[[
000000]
[100000]
[010000]
[001000]
[000100] ]<cl ass'numpy .ndarray'
>
>>>a=np. eye(3,4,k=-2,
dty pe=int)
>>>a=np. eye(5,6,k=-2,
dty pe=int)
>>>pri
nt(
a,t
ype(
a) )
[[
000000]
[000000]
[100000]
[010000]
[001000] ]<class'numpy.
ndarr
ay'
>
>>>a=np.
eye(5,
6,k=-
3,dt
ype=i
nt)
>>>pri
nt(
a,t
ype(
a) )
[[
000000]
[000000]
[000000]
[100000]
[010000] ]<class'numpy.
ndarr
ay'
>

>>>a=np.eye(5,
6,k=-
4, dt
ype=int)
>>>pri
nt(a,
type(
a) )
[[
000000]
[000000]
[000000]
[000000]
[100000] ]<class'numpy .ndarr
ay'
>
>>>a=np.eye(5,
6,k=1,dtype=i
nt)
>>>pri
nt(a,
type(
a) )
[[
010000]
[001000]
[000100]
[000010]
[000001] ]<class'numpy .ndarr
ay'
>
>>>a=np.eye(5,
6,k=2,dtype=i
nt)
>>>pri
nt(a,
type(
a) )
[[
001000]
[000100]
[000010]
[000001]
[000000] ]<class'numpy .ndarr
ay'
>
>>>a=np.eye(5,
6,k=3,dtype=i
nt)
>>>pri
nt(a,
type(
a) )
[[
000100]
[000010]
[000001]
[000000]
[000000] ]<class'numpy .ndarr
ay'
>
==========================================================
7)identi
ty(
):

=>ThisfunctionalwaysbulidIdenti
tyorunitmat
ri
x
=>Syntax:-varname=numpy .
ident
it
y(N,dt
ype)
=>HereNr epresent
sEi t
herwecant akeRowsorCol
umnsandPVM t
akesasNXN
Matri
x( SquareMat r
ix-
-UnitorIdent
ity
)
Examples:
>>>i
mpor tnumpyasnp
>>>a=np.ident
it
y(3,dtype=i
nt )
>>>pri
nt(a,t
ype(
a))---
--
---
--
--
-
[[100]
[010]
[001] ]<class'
numpy .
ndar
ray'
>
>>>a=np.ident
it
y(5,dtype=i
nt )
>>>pri
nt(a,t
ype(
a))
[
[10000]
[01000]
[00100]
[00010]
[00001] ]<cl
ass'numpy
.ndar
ray
'>

===============================================================
NumPy -
-Arit
hmeticOperat
ions
===============================================================
=>Ontheobjectsofndarray ,
wecanappl yallt
ypesofAr i
thmeti
cOperator
s.
=>To perform Ar i
thmetic Oper ati
ons on the obj ects of ndar
ray i
n numpy
progr
ammi ng,weuset hef ol
lowi
ngf unct
ions.
a)add()
b)subtract()
c)multi
ply (
)
d)dot()
e)divi
de()
f)f
loor_divi
de()
g)mod( )
h)power ()
=>All
thearit
hmeticFunctioncanal sobeperformedw. r.
tAri
thmeti
cOperator
s.

a)add(
):

Syntax:
-v arname=numpy .
add(ndar
rayobj
1,ndar
ray
obj2)
=>Thisf unct i
oni susedforaddingel
ementsofndarrayobj
1,ndar
ray
obj
2andr
esul
t
canbedi splayed
Exampl es:
--
--
--
---
--
---
---
>>>l1=[[10, 20],[30,
40]]
>>>l2=[[1,2],
[3,4]]
>>>a=np. ar
ray( l
1)
>>>b=np. ar
ray( l
2)
>>>a
ar r
ay (
[[10,20],
[
30, 40]]
)
>>>b
ar r
ay (
[[1,2],
[
3, 4]]
)
>>>c=np. add( a,b)
>>>c
array([[
11, 22],
[
33, 44]])
--
--
--
--
--
--
--
----
--
---
----
-----
--
---
---
--
----
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
-
>>>x=np. array([[
1, 2,
3] ,
[
4,5,6]])
>>>x
array([[
1,2, 3],
[4,5,6]])
>>>y=np.array([4,4,4])
>>>y
array([4,4,4])
>>>z=x+y
>>>z
array (
[[5,6,7] ,
[8,9, 10]])
>>>z=np.add( x,y)
>>>z
array (
[[5,6,7] ,
[8,9, 10]])
>>>x
array (
[[1, 2,3],
[4, 5,6] ]
)
>>>k=np.array( [
[2,3],[
4,5]]
)
>>>k
array (
[[2, 3],
[4, 5]])
>>>kvr=np.add( x,k)---
-ValueEr r
or:operandscouldnotbebroadcastt
ogether
--
--
--
--
--
--
--
----
--
---
----
-----
--
---
---
--
----
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
>>>l1=[[
10,20],[30,40]]
>>>l2=[[
1,2],
[3,4]]
>>>a=np.array (l
1)
>>>b=np.array (l
2)
>>>a
array([[
10, 20],
[30,40] ]
)
>>>b
array([[
1,2],
[3,4]])
>>>c=a+b#weusedoper ator+insteadofadd()
>>>c
array (
[[11, 22],
[33, 44] ]
)

b)subt
ract
()

Syntax:
-v ar
name=numpy.
subt
ract(ndar
rayobj
1,ndar
ray
obj
2)
=>Thisfunct
ionisusedf
orsubtracti
ngelementsofndarr
ayobj
1,ndar
ray
obj
2and
resul
tcanbedispl
ayed

Exampl
es:
--
--
--
--
--
---
--
---
>>>l1=[[
10, 20],[
30,40]
]
>>>l2=[[
1,2],[3,
4]]
>>>a=np.ar ray(l1)
>>>b=np.ar ray(l2)
>>>a
arr
ay([
[10, 20] ,
[30,40] ]
)
>>>b
arr
ay([
[1,2],
[3,4]]
)
>>>c=np.subt r
act(a,
b)
>>>c
arr
ay([
[9, 18] ,
[27,36] ]
)
--
--
--
--
--
---
--
-----
---
--
---
--
--
--
-
>>>d=a-b #weusedoper at
or-i
nst
eadofsubt
ract
()
>>>d
arr
ay([
[9, 18] ,
[27,36] ]
)

c)mul t
iply(
):
--
--
--
---
--
---
--
--
--
---
Syntax:
-v arname=numpy.
mult
ipl
y(ndar
rayobj
1,ndar
ray
obj
2)
=>Thisf uncti
onisusedforper
for
mi ngelement-
wisemult
ipl
i
cat
ionofndar
ray
obj
1,
ndarrayobj2andresul
tcanbedi
splayed

Examples:
>>>l1=[[
1,2],
[3,
4]]
>>>l2=[[
5,6],
[4,
3]]
>>>a=np.array(l
1)
>>>b=np.array(l
2)
>>>a
arr
ay([
[1,2],
[3,4]]
)
>>>b
arr
ay([
[5,6],
[4,3]]
)
>>>c=np.mul ti
ply(
a,b)
>>>c
arr
ay([
[5, 12],
[12,12]])
--
--
--
--
--
---
--
---
--
---
--
--
--
--
---
--
--
--
--
---
--
>>>e=a*b #weusedoper ator*i
nst
eadofmul
ti
ply
()
>>>e
arr
ay([
[5, 12],
[12,12]])
--
--
--
--
--
---
--
---
--
---
--
--
--
--
---
--
--
--
--
d)dot()
=>Toper
for
m Mat
ri
xMul
ti
pli
cat
ion,
weusedot
()

Sy
ntax:
-var
name=numpy
.dot
(ndar
ray
obj
1,ndar
ray
obj
2)

=>Thisf uncti
oni susedf orper
for
mingact
ualmat
ri
xmul
ti
pli
cat
ionofndar
ray
obj
1,
ndarrayobj2andr esul
tcanbedi
spl
ayed
Examples:
--
--
--
--
---
---
--
-
Examples:
>>>l1=[[1,
2],
[3,4]]
>>>l2=[[5,
6],
[4,3]]
>>>a=np. arr
ay (l
1)
>>>b=np. arr
ay (l
2)
>>>a
arr
ay ([
[1,2],
[3, 4]
])
>>>b
arr
ay ([
[5,6],
[4, 3]
])
>>>d=np. dot(a,b)
>>>d
arr
ay ([
[13,12],
[31, 30]]
)

e)di
vide(
)
Synt
ax:-v ar
name=numpy.div
ide(ndarray1,
ndarr
y2)
=>Thi
sf unct
ion i
s used forper forming element
-wi
se di
vi
sion ofndar
ray
obj
1,
ndarr
ayobj
2andresul
tcanbedi splayed

>>>l1=[
[10,
20],[
30,40]]
>>>l2=[
[1,
2],
[3,
4]]
>>>a=np.ar
ray(l1)
>>>b=np.ar
ray(l2)
>>>a
arr
ay (
[[
10, 20],
[30, 40]]
)
>>>b
arr
ay (
[[
1, 2]
,
[3,4]])
>>>c=np.di
vide(a,b)
>>>c
arr
ay (
[[
10. ,
10.],
[10.,10.]]
)
--
--
--
--
--
--
--
--
--
--
---
--
----
--
--
---
--
--
--
--
--
---
--
--
--
--
--
--
--
>>>d=a/b #weusedoper ator/inst
eadofdi
vi
de(
)
>>>d
arr
ay (
[[
10. ,
10.],
[10.,10.]]
)
f
)fl
oor
_di
vi
de(
)

Syntax:
-v arname=numpy .
fl
oor_divi
de(ndarray
1,ndarry
2)
=>Thisf uncti
oni susedf orperformingel ement-wisefloordi
vi
sionofndar
ray
obj
1,
ndarrayobj2andr esultcanbedi splayed
>>>l1=[[10,
20],[
30, 40]]
>>>l2=[[1,
2],
[3,
4]]
>>>a=np. arr
ay(l1)
>>>b=np. arr
ay(l2)
>>>a
arr
ay (
[[
10, 20],
[30, 40] ]
)
>>>b
arr
ay (
[[
1, 2],
[3,4]])
>>>c=np. fl
oor_div i
de(a,b)
>>>c
arr
ay (
[[
10, 10],
[10, 10] ]
)
--
--
--
---
--
---
--
--
---
--
--
-----
---
---
--
--
--
--
--
--
--
---
--
---
---
--
>>>d=a/ /b #weusedoper at
or/ /insteadoffloor_
divi
de()
>>>d
arr
ay (
[[
10, 10],
[10, 10] ]
)

g)mod(
)

Syntax:
-v arname=numpy .
mod( ndarray1,ndarr
y2)
=>Thisf unctioni susedf orperformingel ement-wi
semodul odivi
sionofndar
ray
obj
1,
ndarrayobj2andr esultcanbedi splayed
--
--
--
---
--
----
---
--
Exampl es:
--
--
--
---
--
----
---
--
-
>>>l1=[[10,20],[30,40]]
>>>l2=[[1,2],
[3,
4] ]
>>>a=np. array(l1)
>>>b=np. array(l2)
>>>a
array (
[[10, 20],
[30, 40] ]
)
>>>b
array (
[[1,2],
[3,4] ]
)
>>>c=np. mod( a,b)
>>>c
array (
[[0.,0.]
,
[0.,0.]]
)
--
--
--
---
--
----
---
--
---
----
---
---
---
--
--
--
--
--
---
--
---
--
--
---
--
----
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
=>Wecanal sodowi thoperator%
>>>e=a%b
>>>e
ar
ray
([[
0,0]
,
[
0,0]
], dt
ype=i
nt32)

h)power ()
:
--
--
--
---
--
---
--
--
--
---
--
--
---
--
--
--
--
-
Syntax:
-v arname=numpy .power
(ndarray
1,ndar
ry2)
=>Thisf uncti
oni susedf orperformingelement-wi
seexponent
ialofndar
ray
obj
1,
ndarrayobj2andr esul
tcanbedisplayed

Examples:
>>>l1=[
[10,20],[30,40]]
>>>l2=[
[1,2],
[3,
4] ]
>>>a=np.array( l
1)
>>>b=np. ar
ray( l
2)
>>>a
ar r
ay (
[[10, 20],
[30, 40] ]
)
>>>b
ar r
ay (
[[1,2],
[3, 4]
])
>>>c=np.power (a,b)
>>>pri
nt(
c)
ar r
ay (
[[ 10, 400] ,
[27000, 2560000]]
,
--
--
--
--
--
--
--
----
--
---
----
---
---
---
--
--
--
--
>>>f=a**b #I nsteadofusi ngpower()wecanuse*
*oper
ator
>>>f
ar r
ay (
[[ 10, 400] ,
[27000, 2560000]]
, dt
ype=i
nt32)
================================================================
NumPy
--St
ati
sti
cal
Oper
ati
ons

=>Ontheobjectofndar r
ay,wecant hefol
lowi
ngStat
ist
ical
Oper
ati
ons.
a)amax( )
b)ami n()
c)mean( )
d)medi an()
e)var()
f)std()
=>Theseoperati
onwecanper f
orm ontheenti
rematri
xandwecanalsopef
orm on
col
umnwise( axi
s=0)andRowwi se(axi
s=1)
a)amax()
:(biggestvalue)

=>Thisfunct
ionsobtai
nsmaximum el
ementoftheenti
remat
ri
x.
=>Syntax1:
- v arname=numpy.
amax(ndar
ray
object
)

=>Sy
ntax2:
- v
arname=numpy
.amax(
ndar
ray
obj
ect
,axi
s=0)
--
->obt
ainsmax

=>Syntax3: - v arname=numpy .amax(ndarr


ay obj
ect,axi
s=1) -
--
>obt
ainsmax
Exampl es:
>>>l1=[[1,2,
3],[
4,2,
1],
[3,4,
2]]
>>>A=np. ar
ray(l
1)
>>>print(A)
[
[123]
[421]
[342] ]
>>>max=np. amax (
A)
>>>cmax=np. amax( A,axis=0)
>>>rmax =np.amax (A,axi
s=1)
>>>print("Maxel ement =",
max)--
---
--
--
--
Maxel eemnt=4
>>>print("ColumnMaxel eemnts=",
cmax)--
-ColumnMaxel eemnts=[443]
>>>print("RowMaxel eemnt s=",
rmax)--
-RowMaxel eemnt s=[344]
--
--
--
--
--
----
----
--
--
--
----
--
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
---
--
--
---
--
--
--
--
---
---
--
--
----
--
--
--
-
b)ami
n()
:(smal
l
estv
alue)

=>Thisfuncti
onsobt ai
nsminmum el
ementoftheenti
remat
ri
x.
=>Syntax1:
- v arname=numpy.
amin(
ndar
rayobj
ect)
=>obtainminel
ementofwhol
emat r
ix

=>Sy
ntax2:
- v arname=numpy.
amin(
ndarr
ayobject
,axi
s=0)
=>obtainsmi
nelementsonthebasi
scolumns.

=>Sy
ntax3:
- v arname=numpy.amin(
ndar
rayobj
ect,
axi
s=1)
=>obt
ainsminelementsonthebasisRows.

Exampl es:
>>>l1=[[1,
2,3],[
4,2,1],
[3,
4,2]]
>>>A=np. array(l
1)
>>>print(A)
[[
123]
[
421]
[
342] ]
>>>mi n=np.ami n( A)
>>>cmi n=np. ami n(A,axi
s=0)
>>>rmi n=np.ami n( A,
axis=1)
>>>print("
Mi neleemnt =",
min)--
-Minel
eemnt =1
>>>print("
Col umnMi neleemnts=",
cmin)-
--
ColumnMi neleemnts=[
121]
>>>print("
RowMi nel eemnts=",
rmin)-
--
RowMi neleemnts=[112]
--
--
--
--
--
----
--
--
----
--
----
----
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
-
c)mean( ):(
av erage)

=>Thi
sisusedf
orcalmeanofthetotalmatr
ixel
ements.
=>Thefor
mulaf
ormean=(sum ofal
lelementsofmatr
ix)
/total
numberofel
ement
s.
Synt
ax1:- var
name=numpy.mean(ndarr
ayobj
ect)
Synt
ax2:- var
name=numpy.mean(ndarr
ayobj
ect,
axi
s=0)-
--
>Columnwi
seMean
Synt
ax3:- var
name=numpy.mean(ndarr
ayobj
ect,
axi
s=1)-
--
>RowwiseMean

Exampl es:
>>>l1=[[1,
2,3],[
4,2,
1],[
3,4,2]
]
>>>A=np. array(l
1)
>>>print(A)
[
[123]
[421]
[342] ]
>>>m=np. mean( A)
>>>cm=np. mean( A,axis=0)
>>>rm=np. mean( A,axi
s=1)
>>>print("
Mean=" ,
m) --
---
---
-Mean=2. 4444444444444446
>>>print("
Col umnMean=" ,cm)--
--
-ColumnMean=[ 2.66666667 2.66666667 2.]
>>>print("
RowMean=" ,
rm) --
-RowMean=[2. 2.
33333333 3.]
--
--
--
--
--
----
--
--
----
--
----
--
---
--
---
---
---
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
d)medi an()
=>Thi
sisusedforcalcul
ati
ng/obtai
ningmedianofentir
emat r
ixel
ement s.
=>Medianisnothi
ngbutsor t
ingt
hegivendatainascendi
ngorderandsel ectmi
ddl
e
el
ement .
=>I
fthenumbersor tedelementsareoddt hencentre/mi ddleelementbecomes
median.
=>I
ft henumbersor tedelementsareev enthenselectcentre/mi ddle oftwo
el
ement s,
addthem anddivi
dedby2andt hatr
esultbecomesmedi an.

Sy
ntax1:
- v
arname=numpy
.medi
an(
ndar
ray
obj
ect
)

Sy
ntax2:
- v
arname=numpy
.medi
an(
ndar
ray
obj
ect
,axi
s=0)

Sy
ntax3:
- v
arname=numpy
.medi
an(
ndar
ray
obj
ect
,axi
s=1)

Exampl es:
--
--
--
--
--
----
--
--
--
>>>l1=[[1,
2,3],[
4,2,1]
,
[3,
4,2]]
>>>A=np. array(l
1)
>>>print(A)
[
[123]
[421]
[342]]
>>>md=np. medi an(A)
>>>cmd=np. medi an(A,
axis=0)
>>>rmd=np. medi an(A,
axis=1)
>>>print("
Medi an=" ,
md)---
-Median=2.0
>>>print("
Col umnMedi an=",
cmd) -
--
Col
umnMedian=[
3.2.2.]
>>>print("
RowMedi an=",
rmd)--
---
-RowMedian=[
2.2.3.]
>>>l1=[[2,
3],
[4,1]]
>>>A=np. array(l
1)
>>>print(A)
[
[23]
[41]]
>>>md=np. medi an(A)
>>>cmd=np. medi an(A,
axis=0)
>>>rmd=np. medi an(A,
axis=1)
>>>print("
Medi an=" ,
md)---
Median=2.5
>>>print("
Col umnMedi an=",
cmd) -
--
Col
umnMedian=[
3.2.]
>>>print("
RowMedi an=",
rmd)--
-RowMedian=[2.
52.
5]
================================================================
2
e)v
ar(
): (
mean-
xi)/t
otal
numberofel
ement
s

Vari
ance=sqr (
mean-xi)/totalnumberofelements
here'xi
'representseachelementofmat r
ix.
--
--
--
---
--
--
---
--
---
--
--
--
--
--
--
--
---
--
--
--
---
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
Syntax1:
- v arname=numpy .
var(
ndarrayobj
ect)

Sy
ntax2:
- v
arname=numpy
.var
(ndar
ray
obj
ect
,axi
s=0)
Syntax3:- v arname=numpy .
var(
ndarrayobj
ect,
axi
s=1)
--
--
--
---
--
---
--
--
----
--
----
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
Exampl es:
--
--
--
---
--
---
--
--
--
>>>l1=[[1,
2,3],
[4,2,
1],
[3,
4,2]
]
>>>A=np. array(l
1)
>>>print(A)
[[
123]
[
421]
[
342] ]

>>>vr
=np. v
ar (A)
>>>cvr=np.var(A,axi
s=0)
>>>rv
r=np.var (A,
axis=1)
>>>pri
nt("
Var iance=",
vr)
--
--
Variance=1.
1358024691358024
>>>pri
nt("
Col umnVar i
ance="
,cvr)
---
Col
umnVariance=[1.
555555560.
88888889

0.66666667]
>>>print
("RowVari
ance=",
rvr
)-
--
RowVar iance=[
0.666666671.555555560.66666667]
================================================================

f
)st
d()
:st
andar
ddev
iat
ion=sqr
t(v
ar)

Sy
ntax1:
- v
arname=numpy
.st
d(ndar
ray
obj
ect
)

Sy
ntax2:
- v
arname=numpy
.st
d(ndar
ray
obj
ect
,axi
s=0)

Syntax3:- v ar name=numpy .
std(ndarrayobj
ect,
axis=1)
--
--
--
---
--
---
--
--
----
------
---
--
--
--
--
--
--
--
--
--
--
--
---
--
--
----
--
--
--
--
--
--
--
--
---
Exampl es:
--
--
--
---
--
---
--
>>>l1=[[1,
2,3],[4,2,1]
,[
3,4,
2]]
>>>A=np. array (l
1)
>>>print(A)
[[
123]
[
421]
[
342] ]
>>>v r
=np. v
ar (A)
>>>cv r
=np. var(A, axi
s=0)
>>>rvr=np.var (A,axis=1)
>>>print("
Var iance=" ,v
r)-
--
Vari
ance=1. 1358024691358024
>>>print("
Col umnVar i
ance=",
cvr)
---
ColumnVar i
ance=[1.
555555560.
88888889

0.66666667]
>>>pr i
nt("
RowVar i
ance=",r
vr)
--
-RowVariance=[0.
666666671.555555560.
66666667]
--
---
--
---
--
--
--
--
---
---
---
--
--
----
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
>>>sd=np. std(A)
>>>csd=np. std(A,axis=0)
>>>r sd=np.std(A,
axis=1)
>>>pri
nt("st
d=",
sd)-
--
std=1.0657403385139377
>>>pri
nt("columnstd=",
csd)-
--col
umnst d=[1.
247219130.942809040.81649658]
>>>pri
nt("Rowstd=",
rsd)
--
Rowst d=[0.
816496581.247219130.81649658]
================================================================

==============================================================
NumPy
---
Basi
cIndexi
ng
==============================================================

=>Ifwewantt oaccessSi ngleelementof1D, 2DandN- Darrayswemustuset


he
conceptofBasi cIndexing.
--
--
--
--
--
----
--
---
---
---
--
--
--
---
---
--
---
---
--
--
---
--
--
---
---
--
--
--
=>Accessi ngSi ngleElement1D- Array:
--
--
--
--
--
----
--
---
---
---
--
--
--
---
---
--
---
---
--
--
---
--
--
---
---
--
--
--
-
=>Syntax:- ndar r
ayname[I ndex]
=>Here' i
ndex 'canbeei thereither+v eor-veindexing
Exampl es:
>>>a=np. array([
10,20,30,40,50,
60])
>>>a- ---
--
----
-arr
ay([10,20, 30,40,50, 60]
)
>>>a[0]--
----
--
---
10
>>>a[3]--
----
--
---
40
--
--
--
--
--
----
--
---
---
---
--
--
--
---
---
--
---
---
--
--
---
--
--
---
---
--
--
--
--
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
--
--
-

=>Accessi
ngsi
ngl
eEl
ementof2D:

=>Sy
ntax:
-ndar
ray
obj
[rowi
ndex
,col
umni
ndex
]

Exampl
es:
-

>>>i
mpor tnumpyasnp
>>>a=np.array(
[10,20,
30,40,
50,60]
)
>>>b=a.reshape(2,3)
>>>b---
--
---
--
-
ar
ray([[
10,20,30],
[40,50,60]]
)
>>>b[0,
0]--
---
--
--
--
10
>>>b[0,
1]--
---
--
--
--
20
>>>b[1,
2]--
---
--
--
60
================================================================

=>Accessi
ngsi
ngl
eEl
ementof3D:

Sy
ntax:
- ndar
ray
obj
[Indexofmat
ri
x,r
owi
ndex,
col
umni
ndex]
Exampl es:
>>>a=np. array([
10,20,30,
40,50,
60,70,
80]
)
>>>b=a. reshape(2,2,2)
>>>b----
----
--
--
array([
[[
10,20],
[
30,40]]
,
[[
50,60],
[
70,80]]
])
>>>b[0,0,0]-
---
--
--
--
-10
>>>b[-1,0,0]
---
--
--
--
50
>>>b[-2,1,1]
---
--
--
--
40
================================================================
NumPy I
ndexi
ngandSl
i
cingOper
ati
onsof1D,
2Dand3Dar
ray
================================================================
1DArraysSli
cing:

Sy
ntax:
-1dndr
ray
obj
[begi
n:end:
step]

Exampl
es:

>>>a=np.arr
ay([
10,20,30,40,
50,60,70])
>>>a--
--
--
---
--
-ar
ray([
10, 20,30,40, 50,60,70]
)
>>>a[:
:-
1]-
--
---
--
--
-arr
ay([70,60,50, 40,30,20,10])
>>>a[:
:]
--
--
--
---
--
array(
[10,20,30, 40,50,60,70])
--
--
--
--
--
--
--
--
--
---
--
--
---
--
--
--
---
--
---
--
--
--
----
---
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--

2DAr
ray
sSl
i
cing:

Sy
ntax:
-ndr
ray
obj [I,j]
her
e'i
'represent
sRowIndex
her
e'j
'represent
sCol
umnIndex

Sy
ntax:
- 2dndr
ray
obj
[sl
i
ce1,
sli
ce2]

Syntax:
- 2dndr r
ayobj[
begin:
end:step,begin:
end:st
ep]
-
--
---
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
---
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--

Examples:
>>>a=np.array([[
10,20,30],
[40,50,
60]
])
>>>a--
--
--
---
array([
[10,20, 30],
[40,50,60] ]
)
>>>a[
0,0]--
--
--10
>>>a[
0: ,0:
1]----
-
array([
[10],
[40]]
)
>>>a[
0: ,1:
2]----
--
array([
[20],
[50]]
)
>>>a[
1: ,:
]-
--
---array([
[40,50, 60]
])
===============================================================

3DAr
ray
sSl
i
cing

Sy
ntax:
- 3dndr
ray
obj
[i,
j
,k]

her
e'i
'represent sWhich2Dmat ri
x(Mat ri
xNumber --
>012345. .
..
..)
her
e'j
'represent swhichRowsi nt hat2Dmat ri
x
her
e'k'
r epresentswhi chColumnsi nthat2Dmat ri
x
(
OR)
Sy
ntax:
- 3dndr r
ay obj
[sli
ce1,sli
ce2,sl
ice3]
(
OR)
Sy
ntax:
- 3dndr r
ay obj
[begin:
end:step,
begi n:
end:
step,begi
n:end:
step]
(
mat
ri
x) (
row) (
col
umn)
Exampl
es:

>>>lst
=[[[1,
2,3],
[4,5,
6],
[7,
8,9]]
,
[[13,14,
15],
[
16,17,18],
[
19,20,
21]]]
>>>pri
nt(l
st)
[[
[1,
2,3],
[4,5,6],[7,8,9]]
,[
[13,14,15],
[16,17,18],[
19,20,21]
]]
>>>arr
2=np.array(lst
)
>>>pri
nt(arr
2)--
--
----
--
--
--
[[
[123]
[456]
[789] ]

[
[131415]
[161718]
[192021] ]]
>>>ar
r2.
ndim--
--
--
--
----
--
--
3
>>>ar
r2.
shape- -
--
---
--
--
-(2,3,3)
>>>ar
r2[
:,:,0:
1]-
--
---
--
---
---
-
array([
[[1],
[4],
[7]],

[
[13]
,
[16]
,
[19]
]]
)
>>>ar
r2[
:,
:
,:
1]-
--
--
-
ar
ray
([[
[1],
[4],
[7]]
,

[
[13],
[16],
[19]]]
)
>>>ar
r2[
:,0:
2,1:
3]-
--
--
---
array([
[[2,3],
[5,6] ]
,
[
[14,15],
[17,18]]
])
>>>ar
r2[
:,:
2,1:
]-
--
--
--
--
---
-
array(
[[
[2,3],
[5,6]],

[
[14,
15],
[17,
18]]
])
================================================================

==============================================================
NumPy
---
Adv
ancedI
ndexi
ng
==============================================================

=>Ifwewantt oaccessmul ti
pleelement s,whicharenotinorder( ar
bit
rar
yelements)
of1D,2DandN- Darray swemustuset heconceptofAdv ancedI ndexi
ng.
=>Ifwewantaccesst heelement sbasedonsomecondi ti
ont henwecan' tusebasic
i
ndexingandBasi cSl icingOper ati
ons.Tof ullfi
l
lsuchtypeofr equir
ementswemust
useadv ancedIndexing.
--
--
---
--
--
--
--
--
---
--
--
--
--
--
---
----
---
--
--
--
---
--
--
---
--
--
--
----
--
=>AccessingMul ti
pleAr bit
raryElement s---
1D:
--
--
---
--
--
--
--
--
---
--
--
--
--
--
---
----
---
--
--
--
---
--
--
---
--
--
--
----
--
-
=>Syntax:- ndarrayname[x]

=>Her
e'x'
canbeei
therndar
rayorl
i
stwhi
chr
epr
esent
srequi
redi
ndexesofar
bit
rar
y
el
ements.
Exampl
es:

>>>lst=[10,20,30,
40,50,60,70,80,90]
>>>a=np. array(l
st)
>>>print(a)--
--
---
--
---
--
--
[102030405060708090]
#access10 30and80el ement s
#herei ndexesof1030and80ar e027
>>>l
st=[0,2,
7]her e[0,
2,7]arei ndexesof1030and80
>>>indexes=np. array(l
st)#her elstconver
tedi
ntondar
rayobject
>>>print(i
ndexes) --
---
--
--
[027]
>>>print(a[
indexes] )
---
--
---
---
--
-[
103080]
(
OR)
>>>ind=[0,2,7]#pr epar ethel i
stofindexesofarbi
tr
ayelements(
10,
30,
80)ofndar
ray
andpasst ondar ray
>>>print(a[
ind])---
--
---
--
-[
103080]

Exampl
es:

Q1--
>Access203080101030
>>>lst
=[10,
20,30,
40,50,
60,
70,
80,
90]
>>>a=np.ar
ray(l
st)
>>>pri
nt(a)
--
--
---
--
--
--
--
-[
102030405060708090]
>>>ind=[1,
2,7,
0,0,
2]#[1,2,
7,0,
0,2]ar
etheindexesof203080101030
>>>print
(a[i
nd])-
--
--
--
--
--
--
---
[203080101030]
--
--
--
--
--
---
--
--
--
---
--
--
--
--
--
--
--
--
---
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-

=>Accessi
ngMul
ti
pleAr
bit
rar
yEl
ement
s--
-2D:

=>Sy
ntax:
-ndar
ray
obj
[[r
owi
ndexes]
,
[col
umni
ndexes]]

Examples:-
>>>i
mpor tnumpyasnp
>>>mat=np.ar
ray
([[
1,2,
3,
4],
[
5,6,
7,
8],
[
9,10,
11,
12]
,
[13,
14,
15,
16]])
>>>pri
nt(mat)

[
[1234]
[5678]
[9101112]
[13141516]
]

Q1)Accesst
hepr
inci
pledi
agnal
element
s161116

Ans:
- mat [[0,1,
2,3],
[
0,1,
2,3]]
=>Whent
heabov estatementi sex
ecuted,
ThePVM t
akesi
nter
nal
l
yas
mat[(0,0),
(1,1),(
2,2),
(3,
3)]
--
--
--
--16 1116

>>>mat
[[0,
1,
2,
3],
[
0,1,
2,
3]]
--
--
--
--
--
-ar
ray
([1,6,
11,
16]
)

Q2)Accesstheel
ement s614
Ans: mat [[1,
3],[
1,1]]
=>Whentheabovestatementi
sex
ecut
ed,
ThePVM t
akesi
nter
nal
l
yas
mat[(1,
1),
(3,
1)]

>>>mat[[
1,3]
,[
1,1]
]-
--
--
--
--
--
arr
ay([6,14]
)
================================================================

=>Accessi
ngMul
ti
pleAr
bit
rar
yEl
ement
s--
-3D:

Synt
ax:
- ndar
ray
[[I
ndexesof2Dmat
ri
x],
[
rowi
ndexes]
,
[col
umni
ndexes]]
Exampl
es:

>>>i
mportnumpyasnp
>>>l
1=[[[1,
2,
3,4]
,[
5,6,
7,8]
,
[9,
10,
11,
12]]
,
[[13,
14,
15,
16]
,
[17,
18,
19,
20]
,
[21,
22,
23,
24]]]
>>>mat3d=np.ar
ray(l
1)
>>>pr
int
(mat3d)
>>>pri
nt(mat3d)
[[
[1234]
[5678]
[9101112] ]

[
[13141516]
[17181920]
[21222324] ]]
>>>mat 3d.ndim
3
>>>mat 3d.shape
(2,3,4)
--
---
--
--
--
--
--
--
---
--
--
---
---
--
--
--
--
--
Q1)Accesst heel ements11424
Ans:- mat 3d[[0,
1,1],[
0,0,
2],
[0,
1,
3]]

Whentheabovestatementisexecut
ed,I
nter
nal
l
yPVM t
akesasf
oll
ows.
=>mat
3d[(0,
0,
0),
(1,0,
1),
(1,
2,
3)]-Gi
ves-
->11424

Q1)Accesst heelement s 1016


>>>mat 3d[[
-2,
-1],
[-
1,-
3],
[
-3,
-1]
]-
--
--
--
---
arr
ay([
10, 16])
================================================================
OR
========
>>>l1=[[[1,
2,3,
4],
[5,
6,7,
8],
[
9,10,
11,12]]
,[[
13,14,15,
16]
,
[17,
18,
19,
20]
,
[21,
22,23,
24]]]
>>>a=np.array(l
1)
>>>a
arr
ay([[
[1,2,3,4] ,
[5,6,7,8] ,
[9,10,11,12]]
,

[[
13, 14,15, 16] ,
[
17, 18,19, 20] ,
[
21, 22,23, 24] ]
])
>>>#ndar rayobj[[Mat ri
xIndex]
,[
RowIndex]
,
[Col
Index]]
--
-Sy
ntax
>>>#ndar rayobj[[Mat ri
xIndex]
,[
RowIndex]
,
[Col
Index]]
>>>#access1, 8,13,20
>>>mat ind=(0,0,1,1)
>>>rowi nd=(0,1,0,1)
>>>colind=(0,3,0,3)
>>>a[mat ind,
rowi nd,coli
nd]
arr
ay([1,8, 13, 20] )
>>>a[[0,0,0,
1,1,1],[
0,1,
2,0,
1,2]
,
[0,
1,2,
0,
1,
2]]
arr
ay([1,6, 11, 13, 18,23])
===========================X====================================

a=np.
arr
ay (
[10,
20,
30,40,
50,
60,
70,
80,
15,
25,
35,
45,
55,
65,
75,
85]
)
a.
shape=(2,
2,2,
2)
pri
nt(
a)
[
[[
[1020]
[3040]]

[
[5060]
[7080]
]]

[
[[
1525]
[3545] ]
[[5565]
[7585] ]]
]
#access10f rom a- -
-4-D
a[0][
0][
0][0]
---
---
--
----10
#access10and40f rom a- -
-4D
a[[
0,0],
[0,
0],
[0,1]
,[0,1]]-
---
array([
10,40])
#access60, 55and15f rom a---
4D
a[[0,
1,1],
[1,
1,0],
[0,0,0],[
1,0,0]]
---
-ar
ray([
60,55,
15]
)
================================================================
================================================================
NumPy --
sel
ect i
ngt heel ement sbasedoncondit
ion
(OR)
Creati
ngFi l
terDi rect l
yFr om ndAr r
ay
================================================================
=>Tosel ectanyel ementf rom ndarrayobj
ect
,wethet
woappr
oaches.Theyar
e

Approach-1:
=>PrepareBool
eanArr
ay(Itcont
ainsTrueorFal
se.Truerepr
esent
sCondi
ti
on
sati
sfi
edandFalser
epr
esentsCondit
ionnotsat
isf
ied]

Sy
ntax:
- v
arname=ndar
ray
obj
ectwi
thcondi
ti
on

v
arnamei
scal
l
edbool
eanar
ray
.

=>PasstheBool
eanAr r
aytothendarrayobject
.sot hatwecangett
hoseel
ement
s
fr
om ndarr
aywhichsatisfi
es withtheentryTrue(or)wecanget t
hoseel
ement
s
fr
om ndarr
aycorr
espondingTrueent
riesofBooleanarray
.
Sy
ntax: ndar ray[Bool
eanAr r
ay]

Approach-
2:
=>Inthi
sapproach,wedi
rect
lypassBool
eanar
rayv
aluest
othendar
rayf
orget
ti
ng
requi
redel
ementsbasedoncondit
ion.

Sy ntax: ndar ray [


ndarr
ay objectwit
hconditi
on]
--
--
--
--
--
----
---
--
----
----
--
---
---
---
--
---
--
---
--
--
--
----
--
--
--
--
--
----
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
Exampl es:
Q1)Selectt hePossi t
iveElement sfrom ndar ray
>>>impor tnumpyasnp
>>>l=[
10, 21,-34,23,-45,30,-
40]
>>>print(l
)--
----
----
--
--[
10, 21,-34,23,-45,30,-40]
>>>a=np. array (
l)
>>>a---
---
---
--
-ar ray([10,21, -34,23, -45,30, -
40])
>>>b=a>0 #Bool eanAr r
ay
>>>print(b)-
---[TrueTr ueFal seTr ueFalseTr ueFalse]
>>>a[b]--
---
--
ar ray([10,21, 23,30])
=======OR========
>>>a[a>0] -
----
----
--
ar r
ay (
[10,21,23, 30])
--
--
--
--
--
----
---
--
----
----
--
---
---
---
--
---
--
---
--
--
--
----
--
--
--
--
-
Q2)Selectt heNegat i
v eElement sfrom ndarray
>>>l=[
10,21,-34,23,-
45,30,
-40]
>>>a=np.array(l)
>>>a---
--
--
--
- array(
[10,21, -34,23,-
45,30,-
40]
)
>>>b=a<0#Bool eanAr ray
>>>b---
-array([False,Fal
se,Tr ue,Fal
se,True,
Fal
se,Tr
ue]
)
>>>a[b]-
--
--
-- array(
[-
34,-45,-40]
)
=================OR=============
>>>a[a<0]-
---
---
---
--
-- ar
ray([
-34,-
45,-
40])
================================================================

================================================================
NumPyAr rayCopyvsView
================================================================

=>TheDi
ff
erenceBet
weenCopyandVi
ew

=>Themai ndif
ferencebetweenacopyandav iewofanarrayi
sthatt hecopyi sa
newarray
, andthev i
ewisjustavi
ewoftheori
ginalar
ray.
=>Thecopyownst hedataandanychangesmadet othecopywi
llnotaffectori
ginal
arr
ay,and any changes made t othe ori
ginalarray wi
l
lnotaf fectt he copy.
modif
icat
ionsareIndependent(Li
keShall
owCopy )

=>Sy
ntax:
- v
arname=ndrray
obj.
copy()
(OR)
ndar
ray
obj2=numpy.copy(
ndar
ray
obj
1)

=>Thev i
ewdoesnotownt hedataandanychangesmadet othev iewwil
laf
fectt
he
ori
ginalarr
ay,andanychangesmadet otheorigi
nalarraywil
laffectthev
iew.
=>Syntax:
- v ar
name=ndr r
ayobj.
view()
--
--
--
---
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
---
--
--
--
--
--
---
--
--
--
---
--
--
--
---
--
--
--
--
--
---
--
--
--
--
--
--
---
--
--

COPY:

Exampl es:
#Makeacopy ,changetheorigi
nalarr
ay,anddisplaybotharrays:
i
mpor tnumpyasnp
arr=np. arr
ay([
1,2,3,4,5]
)
x=ar r.
copy ()
arr[
0]=42
pri
nt(ar
r ) #[422345]
pri
nt(x) #[12345]
--
--
--
---
--
----
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
---
--
--
--
--
--
--
--
---
--
--
--
--
---
--
NOTE: ThecopySHOULDNOTbeaf f
ectedbythechangesmadet otheori
ginal
arr
ay.

VI
EW:

Exampl
e

#Makeav
iew,
changet
heor
igi
nal
arr
ay,
anddi
spl
aybot
har
ray
s:
i
mpor tnumpyasnp
arr=np. arr
ay (
[1,2,3,4,5]
)
x=ar r.
view()
arr[
0]=42
pri
nt(ar
r)#[ 422345]
pri
nt(x) #[ 422345]
--
--
--
---
--
----
--
--
---
--
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
NOTE: Thev iewSHOULDbeaf f
ectedbythechangesmadet otheorigi
nal
arr
ay.
--
--
--
---
--
----
--
--
---
--
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--

#MakeChangesi ntheVIEW:
--
--
--
--
--
--
---
--
-
Example
--
--
--
--
--
--
---
--
-
#Makeav iew, changethevi
ew,
anddi
spl
aybot
har
ray
s:
i
mpor tnumpyasnp
arr=np.arr
ay (
[1,2,3,4,
5])
x=ar r
.vi
ew( )
x[
0]=31

pri
nt(
arr)#[312345]
pri
nt(
x)#[ 312345]
================================================================
================================================================
NumPySor
ti
ngAr
ray
s
================================================================

=>Sort
ingisnothi
ngarrangingtheelement
sinanor der
edsequence.
=>Orderedsequenceisanysequencet hathasanor dercorr
espondi
ngtoel
ements,
l
ikenumer i
coralphabeti
cal,ascendi
ngordescendi
ng.
=>TheNumPyndar rayobjecthasaf unct
ioncall
edsort()
,thatwil
lsor
taspeci
fi
ed
arr
ay.

Exampl
es:

i
mpor tnumpyasnp
arr=np.arr
ay([
3, 2,0,1])
pri
nt(np.
sort(
arr)
)# [ 0123]
--
--
--
--
---
--
--
--
--
--
--
---
---
--
---
--
---
---
--
--
i
mpor tnumpyasnp
arr=np.arr
ay([
'banana', '
cherry
','
apple'
])
pri
nt(np.
sort(
arr)
)#[ 'apple''
banana''cherr
y'
]
--
--
--
--
---
--
--
--
--
--
--
---
---
--
---
--
---
---
--
--
--
---
--
i
mpor tnumpyasnp
arr=np.arr
ay([
True, False,True])
pri
nt(np.
sort(
arr)
)#[ FalseTr ueTrue]
--
--
--
--
---
--
--
--
--
--
--
---
---
--
---
--
---
---
--
--
--
---
--
--
Sort
inga2- DAr r
ay
--
--
--
--
---
--
--
--
--
--
--
---
---
--
---
--
---
---
--
--
--
---
--
--
-
I
fyouuset
hesor
t()met
hodona2-
Dar
ray
,bot
har
ray
swi
l
lbesor
ted:

Exampl
es:
i
mportnumpyasnp
ar
r=np.arr
ay([
[3,2,
4],
[5,
0,1]
])
pr
int
(np.
sort
(ar
r )
)
#out
put
[
[234]
[015]]
================================================================

1)del
ete(
):

=>numpymodul
econt
ainadel
ete(
)tor
emov
eanar
rayel
ementwi
thr
espectt
oit
s
I
NDEX.

Sy
ntax:numpy
.del
ete(
ndar
ray
obj
,INDEX)

=>her
enumpyisamodulewhi
chcont
aindelet
efunct
ion
=>ndarr
ayobj
isv
ari
abl
enameofndarr
ayclass

Example:
>>>l
st=[10,
20,
30,
40,
50,
60,
70,
80,
90]
>>>arr
=np.arr
ay(l
st)
>>>pri
nt(
arr)-
--
--
--
--
--
--
--
--
-[
102030405060708090]
>>>np.
delete(
arr,
1)-
--
--
--
--
arr
ay(
[10,
30,
40,
50,
60,70,
80,
90]
)
================================================================
================================================================
Pandas
================================================================
I
ntroducti
ontoPandas:
--
--
--
--
---
--
--
--
--
--
---
--
---
--
--
-
=>Pandasi sanopensour cePy thonLi brar
y/Modul epr ovidi
nghighper f
ormance
anddat a mani pulat
ionandAnal ysi
sTool .
=>Thewor dPANDAsder i
vedf rom PANel DAta
=>Thepandasconceptdev el
opedbyWESMCKi nneyinthey ear2008.
=>The Tradit
ionalPy thon Pr ogrammi ng doesnotcont ai
n anyModul eforData
Analysi
sand NowPy thonPr ogrammi ngusesPandasasaDat aanaly
sistool
.
=>Python Pandas can be used i n wi de r
ange off i
elds li
ke Fi
nancialServ
ices,
Stati
sti
cs,retai
lmar keti
ngsect ors..etc asdat aanal
ysistool
=>pandasmodul edevelopedinCandPy thonLanguages.

I
nst
all
ati
onofPandas:

=>Thestandar
dpy thonsoftware/Dist
ri
buti
on(CPYTHON)doesnotcontai
nany
modulefordataanalysi
sandnow wear eusi
ngthir
dpar t
ymodulecal
l
edPANDAS
andwhosemodul enamei spandas.
=>Progr
ammatical
lytousepandasaspar tofourpythonprogr
am,wemusti
nst
all
pandasmodulebyusingpiptool.

Sy
ntax:
- pi
pinst
allmodul
ename

Exampl
e:- pi
pinst
allpandas

KeyFeat uresofPandas: ---


--
>Ser iesDataFrame:
--
--
---
---
--
--
--
---
--
--
---
---
---
--
--
--
--
--
--
----
--
--
---
--
--
--
--
--
--
1)FastandEf fi
cientDataFr amewi thdefaultandcustomisedindexi
ng
2)Tool sf orloadi ng the datai ni n-memor y dat
a object
s(obj ect
s ofSeri
es,
DataFrame)
3)Wecanaccesst hedatafr om pandasbyusi ngLabel
edBasedSl i
cingandi
ndexi
ng.
4)Col umnsf r
om i n-memor ydat aobjects(object
sofSeries,DataFrame )canbe
deletedandi nserted

================================================================
Ser
ies
================================================================

=>I
tisaOne- DimensionalLabell
edArr
ayCapableofStori
ng/Hol di
ng
Homogeneousdat aofanyt ype(I
nteger
,Stri
ng,f
loat
,.
..
..
..
..
Pythonobj
ect
setc).
=>TheAxisLabel sar
ecol l
ecti
vel
ycall
edIndex.
=>PandasSer i
esisnothingbutacolumnv al
ueinexcelsheet.
=>PandasSer i
esValuesar eMutabl
e.
=>PandasSer i
escontainsHomogeneousDat a(Int
ernall
yevenwest or
edif
fer
ent
t
ypesvalues, Theyaretreat
edasobjecttype)

Cr
eat
ingaSer
ies:

=>ASeri
esobjectcanbecreatedbyusi
ngthefol
lowingSyntax:
Synt
ax:
-
varname=pandas.
Seri
es(
object
,index,
dtype)
Expl
anat
ion:
-

=>Her ev arnamei sanobjectof<cl ass, pandas.core.


ser i
es.Series>
=>pandasi smodul ename
=>Series( )ispre-defi
nedFunct ioni npandasmodul eandi tisusedf orcreati
ngan
objectofSer i
esclass.
=>'object'canei therli
st,ndar r
ay,di ct...
..etc(Butnotsett ypebcozt heyareun-
ordered)
=>'i
ndex' r
epresentsthepositi
onofv aluespr esentSeriesobject .Thedefaultval
ue
ofI ndexst art
sfrom 0ton- 1,Her enr epresentsnumberofv aluesinSeries
object .Programmat i
call
ywecangi veourownI ndexVal ues.
=>'dty
pe' r
epresentsdatatype( Ex:-i
nt 32,,
int64,fl
oat32,fl
oat 64...
etc)
--
--
---
--
-----
--
---
--
--
---
--
--
--
--
--
--
--
---
--
--
---
---
---
--
----
--
--
--
---
--
--
--
---
--
--
--
---
--
---
----
--
---
Exampl es:- Createaseriesfor102030405060

>>>i
mpor tpandasaspd
>>>i
mpor tnumpyasnp
>>>l
st=[10,
20,30,
40,50,
60]
>>>s=pd.Seri
es(l
st)
>>>pri
nt(s,
type(
s))
0 10
1 20
2 30
3 40
4 50
5 60
dtype:int64<cl ass'pandas.cor
e.seri
es.
Ser
ies'
>
--
--
---
--
--
---
---
---
--
----
--
>>>lst=[10,20,30,40,50,60]
>>>s=pd. Series(lst
,dtype=fl
oat
)
>>>pr i
nt(s,
type( s))
0 10. 0
1 20. 0
2 30. 0
3 40. 0
4 50. 0
5 60. 0
dtype:fl
oat64<cl ass' pandas.core.seri
es.Series'
>
--
--
---
--
--
--
--
---
----
--
--
---
---
---
--
---
--
--
--
---
--
---
---
--
--
---
--
>>>lst=["
Rossum" ,"
Gosl i
ng","
Travis",
"MCKi nney"]
>>>a=np. array(l
st)
>>>a- -
----
-array(['
Rossum' ,'
Gosling','
Travis'
,'MCKinney'
]
,dtype='<U8'
)
>>>pr i
nt(
a, type(a))
--[
'Rossum' '
Gosl i
ng' '
Travis''
MCKinney'
]<class'numpy
.ndar
ray
'>
>>>s=pd. Series(a)
>>>pr i
nt(
s,type(s))
0 Rossum
1 Gosl i
ng
2 Tr avis
3 MCKi nney
dtype:object<class' pandas.core.seri
es.Series'>
--
--
---
--
--
--
--
---
----
--
--
---
---
---
--
---
--
--
--
---
--
---
---
--
--
---
--
---
-
>>>lst
=[10,"Rossum" ,34.56,"
Author "
]
>>>s=pd. Series(l
st)
>>>pr i
nt(
s,type(s))
0 10
1 Rossum
2 34. 56
3 Aut hor
dtype:object<class' pandas.core.seri
es.Series'>

Creati
nganSer i
esobj ectwi thPr ogrammer -
definedIndex:
--
--
---
--
--
--
-----
---
--
---
---
--
----
------
--
---
---
---
--
--
---
--
---
--
---
---
--
--
--
--
--
---
--
--
--
-
>>>lst=[10,"Rossum" ,34. 56,"Author"]
>>>pr i
nt(lst)-
--
---
--[
10, 'Rossum' ,34.56,'Author']
>>>s=pd. Ser i
es( l
st,
index =["Stno","
Name" ,"
Mar ks",
"Desg"]
)
>>>pr i
nt(s)
Stno 10
Name Rossum
Mar ks 34. 56
Desg Aut hor
dtype: object
>>>pr i
nt(s["Stno"])
--
-----10
--
--
---
--
--
--
-----
---
--
---
---
--
----
------
--
---
---
---
--
--
---
--
---
--
---
---
--
--
--
>>>lst=["Rossum" ,
"Gosl i
ng" ,
"Travis",
"MCKi nney"]
>>>s=pd. Ser i
es( l
st,
index =[100,200,300,400])
>>>pr i
nt(s,t
y pe(s))
100 Rossum
200 Gosl i
ng
300 Tr avis
400 MCKi nney
dtype:object<cl ass' pandas. core.seri
es.Series'
>
--
--
---
--
--
--
-----
---
--
---
---
--
----
------
--
---
---
---
--
--
---
--
---
--
---
---
--
--
--
--
--
Creati
ngaSer iesobj ectf rom di ct:
--
--
---
--
--
--
-----
---
--
---
---
--
----
------
--
---
---
---
--
--
---
--
---
--
---
---
--
--
--
--
--
-
=>Adi ctobj ectcanbeusedf orcreati
ngaser iesobject
=>Ifweusedi ctobj
ectinSer i
es()thenkey scanbet akenasI ndices( OrI
ndexes)
automat icallyandcor r
espondingv aluesofdictcanbet akenasdat a.
Exampl es:
--
--
---
--
---
-
>>>impor tpandasaspd
>>>d1={ "sub1" :"
Python",
"sub2"
:"
Jav a",
"sub3"
:"DataScience",
"sub4":"ML"}
>>>pr i
nt(d1) -
-{'
sub1':'
Python'
,'
sub2':'Java'
,'
sub3':'
DataScience','sub4':
'ML'
}
>>>s=pd. Ser i
es(d1)
>>>pr i
nt(s)

sub1 Python
sub2 Java
sub3 Dat aScience
sub4 ML
dtype:obj ect
>>>d2={"
RS":
2.3,"JG" :
1.2,"MCK" :
4.5,
"TOLI"
:2.
4}
>>>pri
nt(
d2)-
--{
'RS':2.3,'JG' :1.
2,'
MCK' :
4.5,'
TOLI
'
:2.
4}
>>>s=pd.
Seri
es( d2)
>>>pri
nt(
s)
RS 2. 3
JG 1. 2
MCK 4. 5
TOLI 2. 4
dtype:float64
===================================x============================
================================================================
Dat
aFr
amei
nPandas
================================================================

=>ADat aFrameis2-Dimensi
onalDat
aStr
ucturetoor
ganizethedata.
=>I
nOt herwordsaDat aFr
ameOrgani
zesthedataintheTabularFor
mat,
whi
chi
s
nothingbutCollecti
onofRowsandCol
umns.
=>TheCol umnsofDat aFr
amecanbeDiff
erentDataTypesorSameTy pe
=>TheSi zeofDataFramecanbemutabl
e.

================================================================
Numberofappr
oachest
ocr
eat
eDat
aFr
ame
================================================================
=>Tocr eat eanobj ectofDat aFr ame,weusepr e-definedDat aFrame( )whi chis
presenti npandasModul eandr etur nsanobj ectofDat aFramecl ass.
=>Wehav e5Way stocr eateanobj ectofDat aFrame.Theyar e
a)Byusi nglist/t uple
b)Byusi ngdi ct
c)Byusi ngSer ies
d)Byusi ngndar rayofnumpy
e)Byusi ngCSVFi le( CommaSepar atedVal ues)
--
--
---
---
---
--
----
--
--
---
--
--
--
---
---
---
--
---
--
----
------
-----
--
---
---
-
=>Sy ntaxf orcreati
nganobj ectofDat aFramei npandas:
--
--
---
---
---
--
----
--
--
---
--
--
--
---
---
---
--
---
--
----
------
-----
--
---
---
--
--
varname=pandas. DataFr ame( object,i
ndex,col umns, dtype)
--
--
---
---
---
--
-
Explanat i
on:
--
--
---
---
---
--
-
=>'varname' i
sanobj ectof<cl ass, '
pandas. core.dataf rame. DataFrame'>
=>'pandas. DataFrame( )'i
sapr e-def inedf unctionpr esenti npandasmodul eandi ti
s
usedt ocr eateanobj ectofDat aFr amef orst ori
ngDat aset s.
=>'object'representslist(or)tuple( or)di ct(or)Ser ies( or)ndar r
ay(or)CSVf i
le
=>'i
ndex' representsRowi ndexandwhosedef aul ti
ndexi ngstartsfrom 0,
1,.
..n-
1
wher e'n'representsnumberofv aluesi nDat aFr ameobj ect
.
=>'columns' r
epresentsCol umni ndexwhosedef aultindexi ngstartsfrom 0,1..
n-1
wher ennumberofcol umns.
=>'dtype'representsdat at ypeofv aluesofCol umnVal ue.
Creatinganobj ectDataFramebyUsi ngli
st/tuple:
--
--
--
-----
--
---
--
--
----
--
--
--
--
--
--
--
--
---
--
---
--
--
--
---
---
--
--
--
--
--
--
--
---
--
--
--
>>>impor tpandasaspd
>>>lst=[10,20,30,
40]
>>>df =pd.DataFrame(lst)
>>>print(df)
0
010
120
230
340
--
--
--
-----
--
---
--
--
----
--
--
--
--
--
--
l
st=[[10,20,30,40],
["
RS",
"JS",
"MCK" ,
"TRV"]]
df=pd. DataFrame( l
st)
pri
nt(df )
01 2 3
01020 30 40
1RSJSMCK TRV
--
--
--
-----
--
---
--
--
----
--
--
--
--
--
--
--
--
---
-
l
st=[[10,'
RS'],
[20,'
JG']
,[
30,'
MCK' ]
,[
40,'
TRA']]
df=pd. DataFrame( l
st)
pri
nt(df )
0 1
010 RS
120 JG
230MCK
340TRA
--
--
--
-----
--
---
--
--
----
--
--
--
--
--
--
--
--
---
--
---
--
l
st=[[10,'
RS'],
[20,'
JG']
,[
30,'
MCK' ]
,[
40,'
TRA']]
df=pd. DataFrame( l
st,
index=[1,
2,3,
4],
columns=['Rno',
'
Name'
]
)
pri
nt(df )

RnoName
1 10 RS
2 20 JG
3 30MCK
4 40TRA

t
pl=((
"Rossum"
,75)
,("
Gosl
i
ng"
,85)
,("
Trav
is"
,65)
,("
Rit
che"
,95)
,(
"MCKi
nney
",
60))

df
=pd.DataFr
ame( tpl
,i
ndex=[
1,2,
3,
4,
5],
col
umns=[
'
Name'
,
'Age'
]
)
pr
int
(df)
Name Age
1 Rossum 75
2 Gosl i
ng 85
3 Travis 65
4 Ritche 95
5MCKi nney60
Creatinganobj ectDataFramebyUsi ngdi ctobject
--
---
---
--
----
---
--
--
--
---
--
--
--
---
--
--
----
--
--
--
---
--
---
---
---
----
-
=>Whenwecr eateanobj ectofDat aFr amebyusi ngDi ct,allt
hekey saretakenas
ColumnNamesandVal uesofVal uear et akenasDat a.
--
---
---
--
----
---
Exampl es:
--
---
---
--
----
---
>>>i mpor tpandasaspd
>>>
dictdata={ "
Names" :[
"Rossum" ,"
Gosl i
ng" ,
"Ritche"
,"
McKi nney"
],
"Subject
s":
["
Python"
,"
Jav
a","
C","
Pandas" ]
,"
Ages":[
65,80,85,55]}
>>>df =pd. DataFrame(dictdata)
>>>pr int(df)
Names Subj ect s Ages
0 Rossum Py t
hon 65
1 Gosling Jav a 80
2 Ri t
che C 85
3McKi nney Pandas 55
>>>df =pd. DataFrame(dictdata,
index =[1,
2,3,4])
>>>pr int(df)
Names Subj ects Ages
1 Rossum Py t
hon 65
2 Gosling Jav a 80
3 Ri t
che C 85
4McKi nney Pandas 55

Creati
nganobj ectDat aFramebyUsi ngSer i
esobject
---
--
--
--
---
--
---
--
--
---
--
--
----
--
--
---
--
--
---
--
--
--
---
--
---
--
--
--
---
-
>>>impor tpandasaspd
>>>sdat a=pd.Series([
10,20,30,
40])
>>>df =pd.DataFrame( sdata)
>>>pr i
nt(df)
0
010
120
230
340
>>>sdat a=pd.Series({
"IntMarks":
[10,
20,30,40],
"Ex
tMarks"
:[
80,
75,
65,
50]
})
>>>pr i
nt(sdata)
IntMarks [ 10,20, 30,40]
ExtMar ks [80, 75,65, 50]
dtype:object

>>>df
=pd.DataFr
ame(
sdat
a)
>>>pr
int
(df)
0
Int
Marks[10,20,30,
40]
ExtMarks[80,75,
65,50]
>>>ddat
a={"
Int
Marks":
[10,
20,
30,
40],
"Ext
Mar
ks"
:[
80,
75,
65,
50]
}
>>>df =pd.Dat aFrame( ddat a)
>>>pr i
nt(df)
IntMar ksExt Mar ks
0 10 80
1 20 75
2 30 65
3 40 50
--
--
--
---
---
---
--
---
----
---
---
-----
---
--
----
--
--
---
--
--
-----
---
---
----
---
----
---
--
--
--
--
--
---
--
Creati
nganobj ectDat aFr amebyUsi ngndar rayobj ect
--
--
--
---
---
---
--
---
----
---
---
-----
---
--
----
--
--
---
--
--
-----
---
---
----
>>>impor tnumpyasnp
>>>l1=[[10,60] ,
[20,70] ,
[40,50]]
>>>a=np. array (l
1)
>>>df =pd.Dat aFrame( a)
>>>pr i
nt(df)
01
01060
12070
24050
>>>df =pd.Dat aFrame( a,columns=[ "IntMar ks" ,
"ExtMar ks"]
)
>>>pr i
nt(df)
Int Mar ksExt Mar ks
0 10 60
1 20 70
2 40 50
--
--
--
---
---
---
--
---
----
---
---
-----
---
--
----
--
--
---
--
--
-----
---
---
----
---
----
---
--
--
--
--
--
e)Byusi ngCSVFi le( CommaSepar atedVal ues)
--
--
--
---
---
---
--
---
----
---
---
-----
---
--
----
--
--
---
--
--
-----
---
--
i
mpor tpandasaspd1
df=pd1.read_ csv (
"D: \KVR- JAVA\ stud. csv "
)
pri
nt("ty
peofdf =",
ty pe(df))#typeofdf =<cl ass'pandas. core.
frame.
Dat
aFr
ame'
>
pri
nt(df)
--
--
--
---
---
---
--
---
-OUTPUT- ---
---
--
--
--
---
--
--
stno name mar ks
0 10 Rossum 45. 67
1 20Gosl ing 55. 55
2 30 Ri tche 66. 66
3 40 Tr av is 77. 77
4 50 KVR 11. 11
--
--
--
---
---
---
--
---
----
---
---
-----
---
--
----
--
--
---
--
--
-----
---
---
----
---
----
---
--
MiscOper ati
onsonDat aFrame
--
--
--
---
---
---
--
---
----
---
---
-----
---
--
----
--
--
--
>>>dat a={"First":
[10, 20,30,40],
"Second" :
[1.4,1.3,1.5,
2.5]}
>>>pr i
nt(data,type( dat a))
{'
Fir
st':[
10, 20, 30, 40] ,'
Second' :[
1.4, 1.3,1.5, 2.5]}<class'di
ct'
>
>>>df =pd.Dat aFrame( dat a)
>>>pr i
nt(df)
FirstSecond
0 10 1. 4
1 20 1. 3
2 30 1. 5
3 40 2. 5
>>>df["Third"]
=df[
"Fi
rst
"]+df[
"Second"]
>>>print(df)
FirstSecondThi rd
0 10 1. 4 11.4
1 20 1. 3 21.3
2 30 1. 5 31.5
3 40 2. 5 42.5
--
--
--
---
--
---
---
---
--
--
--
--
--
--
--
--
--
---
--
--
--
--
---
>>>df["Total"]
=df[
"Fi
rst
"]
+df [
"Thir
d"]
>>>print(df)
FirstSecondThi rdTot al
0 10 1. 4 11.4 21.4
1 20 1. 3 21.3 41.3
2 30 1. 5 31.5 61.5
3 40 2. 5 42.5 82.5

>>>df.
pop("
Total"
)
0 21.4
1 41.3
2 61.5
3 82.5
Name:Total
,dtype:f
loat
64
>>>pri
nt(
df)
Fir
stSecondThi rd
0 10 1. 4 11.4
1 20 1. 3 21.3
2 30 1. 5 31.5
3 40 2. 5 42.5
================================================================
Accessi
ngt
heDat
aofDat
aFr
ame
================================================================

1)DataFrameobj.head(no.ofrows):
=>head()isusedtoaccesst hetopmostrows.
=>no.ofr owsrepresentst hathow manyr owsy ouwantt oselectfr
om t
op.I
fwe
doesnotpassanyv al
uet henbydef aul
titsel
ect5rows.
--
--
--
--
--
--
---
--
---
--
--
--
--
--
--
--
--
---
--
---
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--

2)Dat aFrameobj.
tail
(no.
ofr ows):
=>tai
l()isusedtoaccesst hebot tom mostr ows.
=>no.ofr owsrepresentst hathowmanyr owsy ouwanttoselectfr
om bot
tom.I
fwe
doesnotpassanyv al
uet henbydef aul
titselect5rows.
--
--
---
--
---
--
---
--
--
--
--
--
--
---
--
--
--
--
------
--
--
--
---
--
--
--
--
--
--
--
----
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-

3)DataFrameobj.descr
ibe(
):
=> describe() giv
es the stati
sti
calinfor
mat i
on about datafr
ame .Such as
count,
mean, st
d,minmaxandper cent.
.
--
--
--
--
--
--
--
---
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--

4)DataFrameobj .shape:
=>shapeat t
ributeofdatafr
ameobj ectgiv
etheshapeofDat af
rameinf or
m of
RowXcol umn.
--
--
--
--
--
--
--
----
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-

5)DataFrameobj[st
art:
stop:
step]
:
=>usi
ngthiswecanaccesst henumberofr owsaswedesi re.
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--

6)DataFrameobj[
"ColName" ]:
=>wit
ht hi
swecanaccesst heonecolumni nformati
onbysupplingthecol
umnname.
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
---
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--

7)Dat aFrameobj[[
"ColName1","
ColName- 2".
..
."
Col Name-n"]]:
=>witht hiswecanaccesst hennumberofcol umnsi nformati
onbysuppl
i
ngt
he
columnsname.
--
--
---
--
---
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
---
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
8)Dat aFrameobj[[
"ColName1" ,"
ColName- 2".
..
."
Col Name-n"]
][st
art:
stop:
step]
=>witht hiswecanaccesst hennumberofcol umnsi nfor
mat i
onbysuppl i
ngt
he
columnsnamewr thowmanyr owwewant .
--
--
---
--
---
--
---
--
--
--
--
--
--
--
--
---
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
---
--
--
--
--
---
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
9)Dat aFrameobj.
it
errows():

=>Ifweusei t
errows()wr tDataFr
ameobj ectthenitgiv
ehexadeci
maladdr
essof
dataf
rameobject.
Example-
1:
>>>p.i
ter
rows()
--
---
--
--
-<gener
atorobjectDat
aFrame.i
ter
rowsat
0x000002382938CB30>

=>i
ter
rows(
) gives the tot
al infor
mat
ion about one r
ow when we use
Dat
aFrameobj
.i
terr
ows()i
nforloop.

Example-2:
p=pd.DataFrame( [[10,
"pooja",
56,68,90],
[
20,"
ri
tesh"
,68,79,
78],
[30,
"shubham"
,87,
56,
80]
],
i
ndex=[1,2,
3],columns=[ "
roll
_no" ,
"name","
pyt
hon","
mat h",
"dat
asci
"])
>>>p---
--
---
--
---
---
--
roll_no name py thonmat hdat asci
1 10 pooj a 56 68 90
2 20 r itesh 68 79 78
3 30shubham 87 56 80
>>>res=p.it
errows( )
>>>foriinres:
..
. pr i
nt(i
)
..
.
OUTPUT: -
--
--
---
---
(1,rol
l_no 10
name pooj a
py t
hon 56
mat h 68
datasci 90
Name: 1,
dt ype:object)
(2,rol
l_no 20
name r i
tesh
py t
hon 68
mat h 79
datasci 78
Name: 2,
dt ype:object)
(3,rol
l_no 30
name shubham
py t
hon 87
mat h 56
datasci 80
Name: 3,
dt ype:object)

================================================================

Under
standi
ngl
oc(
)--
--
-her
est
artandst
opi
ndexI
ncl
udedand
ColNamescanbeused( butnotcol umnnumber s]
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
---
--
--
--
--
--
--
---
--
--
--
---
--
--
--
--
---
--
--
--
--
---
-
1)DataFrameobj.
loc[
row_number]
2)DataFrameobj.
loc[
row_number, [
Col Name,..
..
..
..
.]]
3)DataFrameobj.
loc[
star
t:
stop:
step]
4)DataFrameobj.
loc[
star
t:
stop:
step,["ColName" ]]
5)DataFrameobj.
loc[
star
t:
stop:
step,["ColName1" ,ColName- 2..
..
..
."
]]
6)DataFrameobj.
loc[
star
t:
stop:
step,"ColName1": Col Name-n"]

-
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-

Underst
andingiloc()--
--
-herest artindexi ncludedandst opi ndexexcludedand
Col Number smustbeused( butnotcol umnnames]
--
--
--
--
--
--
--
---
--
--
--
--
---
--
---
--
--
--
--
----
--
--
---
---
---
---
--
---
--
----
--
--
--
----
--
--
1)DataFrameobj.i
loc[r
ow_ number ]
2)DataFrameobj.i
loc[r
ow_ number ,Col Number .
..
..
....
]
3)DataFrameobj.i
loc[r
ow_ number ,[
Col Number 1,Col Number 2.
..
..
..
..
..
.]]
3)DataFrameobj.i
loc[r
owst art:
rowst op,Col Start:Col stop]
4)DataFrameobj.i
loc[r
owst art:
rowst op,Col Number]
5)DataFrameobj.i
loc[[r
ownumber 1,rownumber -2..
..
.]]
6)DataFrameobj.i
loc[rowst art
: r
owst op, [ColNumber 1,Col Number2...
..
..
..
..
.]]
6)DataFrameobj.i
loc[:,[
Col Number 1,Col Number 2..
..
....
...
.]]
================================================================

Addi
ngCol
umnNamet
oDat
aFr
ame:

1)datafr
ameobj['
newcol name']
=defaultv
alue
2)datafr
ameobj['
newcol name']
=expressi
on
================================================================

Remov
ingCol
umnNamef
rom Dat
aFr
ame:

1)dat
afr
ame. dr
op(col
umns="colname")
2)dat
afr
ame. dr
op(col
umns="colname",i
nplace=Tr
ue)
================================================================

sor
ti
ngt
hedat
afr
amedat
a:

1)dataf
rameobj.
sort_
values(
"colname"
)
2)dataf
rameobj.
sort_
values(
"colname"
,ascendi
ng=False)
3)dataf
rameobj.
sort_
values(
["col
name1","
colname2",
...
colname-n])
================================================================

knowi
ngdupl
i
cat
esi
ndat
afr
amedat
a:

1)dataf
rameobj.
dupli
cated(
)--
--
--
--
--
--
--
-gi
vesbooleanresul
t
================================================================

Remov
ingdupl
i
cat
esf
rom dat
afr
amedat
a:
1)dataf
rameobj.
drop_dupl
icat
es()
2)dataf
rameobj.
drop_dupl
icat
es(i
nplace=Tr
ue)
================================================================

Dat
aFi
l
ter
ingandCondi
ti
onal
Change:

1)dat
aframeobj
.l
oc[si
mpl econdi
t i
on]
Ex: df.l
oc[df[
"mat
hs"
]>75]
2)dat
aframeobj
.l
oc[compundcondi ti
on]
Ex:df .
loc[(
df[
"mat
hs"]
>60)&(df["
maths]<85)]
Ex:df.l
oc[(df[
"per
cent"
]>=60) & ( df
["
per
cent"
]<=80)
,[
"gr
ade"]
]="Fi
rst
" # cond
updat
ti
on.

Speci
alCase:
3)dat
aframeobj
.l
oc[
simpl
econdi
ti
on.
str
.contai
ns(st
r)]
4)dat
aframeobj
.l
oc[
simpl
econdi
ti
on.
str
.star
tswit
h(st
r)]
5)dat
aframeobj
.l
oc[
simpl
econdi
ti
on.
str
.endswit
h(str
)]

================================================================
================================================================
NetworkProgr
ammi ng
================================================================
=>ThepurposeofNet workProgr
ammi ngisthat"Tosharethedatabetweenmul t
ipl
e
machines"
.

=>Def
.ofNetwork:
=>ANetwor
kisacol l
ect
ionofI
nter
-connect
edcomputer
sconnectedwi
thServ
er"
.
=>I
nNetworkprogr
ammi ng,
wehav etwowritet
wotypesofPr
ograms.Theyar
e

1)ServerSi
deProgram
2)Cli
entSidePr
ogram
1)Ser
verSi
dePr
ogram:

=>ASer verSi
dePr ogram isofthePy t
honPr ogram,whichreceivestherequestf
rom
cl
ientsideprogram,Pr ocesst heRequestandgi v
esr esponsebackt oCl i
entSide
Program.
--
--
--
--
---
--
--
--
--
--
--
--
--
--
---
--
---
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
---
--
--
--
--
--
--
---
--
--
--
-

2)ClientSidePr ogram:
=>ACl ientSidePr ogr
am isofthePythonProgram ,whichalwayssendrequestt
othe
serversidepr ogram andrecei
vestheresponsefrom serversi
deProgram
--
--
--
---
--
----
--
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
-

3)DNS(
Domai
nNami
ngSer
vice)

=>ADNSi saNameoft hePhy si


calmachinewhereServerSideProgramsr
esi
des
=>ThedefaultDNSofev er
ycomput eris"l
ocal
host"
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
-

4)I
PAddr
ess(
Int
ernetPr
otocol
addr
ess)

=>AnI PAddr essi soneoft heNumer i


calAddressoft hePhy si
calMachine,wher
e
serverside
program resides.
=>Thedef aultI
PAddr essofev er
ymachi neis127.0.
0.1(loopbackaddress)
--
--
--
---
--
---
--
--
--
---
---
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
---
--
--
--
--
--
--
--
--
--
-

5)por
tnumber
:
=>APortNumberi salogi
calnumericali
dwher eserv
ersideprogr
am isrunni
ng.
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-

================================================================
Stepsfordevel
opi
ngSer verSi deProgram
================================================================
1)impor tsocketmodul e
2)EverySer verSideProgram mustrunatCer t
ainDNS/I PAddr essandPor tNumber.
3)ServerPr ogram mustACCEPTt heClientSidePr ogram Request.
4)ServerSidePr ogram mustREADt hedatacomi ngf r
om cl i
entsidepr ogr
am.
5)Serv erSi dePr ogr
am mustPROCESS t het heDat acomi ngf rom cl i
entsi
de
progr
am.
6)ServerSidePr ogram mustSendRESPONSEbackt ocli
entsidepr ogram.

Note:AslongasCli
entSideProgr
am sendingrequest
st otheser
versidepr
ogr
am,
TheServerSi
dePr
ogram perf
ormsStep-
(3),
Step-(
4),Step-
(5)andStep-
(6)

St
epsf
ordev
elopi
ngCl
i
entSi
dePr
ogr
am

1)importsocketmodule
2)EveryCli
entSideProgram mustgettheconnect i
onfrom ServerSidePr
ogr
am by
passi
ng
DNSorI PAddressandPortNumber .
3)Cli
entSideProgram mustSENDr equesttotheServerSi
dePr ogram
4)Cli
entSideProgram mustRECEIVEther esponsefr
om ServerSideProgr
am.

================================================================
socketmodul
e
================================================================
=>Todealwi thnetworkprogrammi ng,wemustuseapr e-def
inedmodul ecal
l
ed
"socket
".
=>SocketModulecontai
nsVar i
abl
es, Funct
ion,
cl
assnames.

1)socket
()

=>Thisfuncti
onisusedforcreati
nganobj ectofsocket.
=>Anobj ectofSocketcanbecr eated bothatclientandserversidepr
ogramsand
anobj ectofsocketactsasaBi -
Direct
ionalCommuni cat
ionobjectbet
weenServ
er
SideandCl i
entProgr
am.
Syntax: v arname=socket
.socket(
)
her
evar
namei
sanobj
ectof<cl
ass,
socket
.Socket
>

Examples: s=socket.socket(
)
-
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-

2)bind()
=>Thisfunct
ioni
susedforbindingt heser v
ersideprogram atcer
tai
nDNSandpor
t
number .
=>Syntax: socketobj
.
bi nd(("DNS/ IPaddr
ess",port
no))
=>Examples: s.bi
nd((
"localhost"
,8888))
(
OR)
s.bi
nd(( "127.0.
0.1"
,8888))

3)li
sten()
:
=>ThisFuncti
onisusedf orconfi
guri
ngSer verSi
dePr
ogram i
nsuchwayt
hatt
ohow
manycl i
entsTheServerSideProgram cancommunicate.
=>Syntax: socket
obj.l
isten(
numberofclients)
=>Examples: s. l
ist
en( 2)

4)accept()
:
=>Thisfuncti
oni
susedf oraccept
ingthecl i
entsidepr ogram request
.
=>Thisfuncti
onr
eturnstwoobjects(cl
ientconobj,cl
ientaddress)
=>Syntax: cl i
entsocketobj
ect,
cli
entaddr=socketobj.accept()

=>Exampl
es: cl
i
ent
socket
obj
,
caddr
=s.
accept
()

5)send()withencode():
>Thisfuncti
onisusedf orsendi ngTher esponseofSer versi
deprogram tothecl
ient
sideprogram andClientSi depr ogr
am sendr equestt oServerSideProgram i
nt he
form ofEncrypt
edformat( bytesorby t
earray)bycalli
ngencode()
=>Syntax1: cl
ientsocketobject.
send(st r(
data)
.encode() ) #Atser verside
program
=>Syntax2: cl i
ent
socket object.
send(str
(data).
encode()
)#Atclientcode

6)recv()withdecode():
=>Thisf uncti
on isused forreceivi
ng thetherequestcomi ng fr
om Cli
entSide
Program and
andusedf orreceivi
ngt her
esponsefrom Ser
verSi
deprogram atcl
ientsi
deprogr
am.
=>Syntax1:- clientsocket
obj
.recv
(1024/2048/4096...
.)
.decode(
)#Atserversi
de

=>Sy
ntax2:
- cl
i
ent
socket
obj
.r
ecv
(1024/2048/4096.
..
.)
.decode(
)#Atcl
i
entSi
de

7)connect()
:
=>ThisFuncti
onisusedforobtaini
ngconnect
ionfrom serv
ersi
deprogr
am atcl
i
ent
si
depr ogr
am.
=>Syntax:
- cl i
ent
socketobj
ect
.connect
(("
DNS/IPAddress"
,por
no)
)
=>Examples: s=socket.
socket
()
s.
connect(("
localhost"
,8888)
)
(
OR)
s.
connect((
"127.0.0.
1")
,8888)
=============================x==================================

EXAMPLE1:

#Program f orSquar ingoft hegi vennumbercomi ngf rom cl


ientsidepr
ogr
am
#ServerSquar e.
py
i
mpor tsocket
s=socket.socket()
s.
bind(("localhost",
8888))
s.
li
sten(2)
pri
nt(
"Ser verSidePr ogr am i sreadyt oacceptanycl ientrequest:
")
whil
e(True) :
try:
cli
ent obj,cli
entaddr =s.accept()
cdat a=clientobj .
recv(1024).decode( )
print("
Val ofCl i
entatSer ver={}
" .
format (
cdata))
val=float (
cdat a)
result=v al**2
cli
ent obj.send( str(
result)
.encode( )
)
exceptVal ueEr ror:
cli
ent obj.send( "Don'enterstrs,symbol s,al
pha-numeri
cs"
.encode(
))

-
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-

#Pr ogram forsendi nganumbert oserversideprogram andobtai


nSquar
eoft
he
givennumbercomi ngf rom Serversi
depr ogram atcli
entsi
deprogram
#Cl i
entSquar e.
py
i
mpor tsocket
s=socket .socket (
)
s.
connect (("local
host "
,8888))
print(
"Cli
entSi dePr ogram gotconnectionfrom ServerSi
deProgram")
n=input (
"Ent eranumber :"
)
s.
send( n.encode( ))
sres=s.recv( 1024).decode()
print(
"Resul tf r
om Ser v
eratclient={}
".
format(sr
es))

================================================================

EXAMPLE2:
#Chat Ser ver.py
i
mpor tsocket
#st ep- 1
s=socket .socket ()
s.bind( ("
local host "
,11111))
s.l
ist en(2)
print("-"
*50)
print("SSPi sr eadyt oacceptanyCSPr equest"
)
print("-"
*50)
whi le(True) :
#st ep-2
con, adr=s.accept (
)
#st ep-3
cdat a=con. recv(1024).
decode( )
print("Cli
entDat aatServer-
>{}"
.format(
cdat
a))
sdat a=input ("
SSPMessaget oClient
:"
)
#st ep-4
con. send( sdata.encode()
)
--
---
-----
---
----
-----
--
--
---
---
---
---
--
--
---
--
--
--
--
--
--
#chat cl
ient .
py
i
mpor tsocket
#st ep- 1
s=socket .socket ()
#st ep- 2
s.connect (("localhost "
,11111))
print("-"
*50)
print("CSPgotconnect edtoSSP" )
print("-"
*50)
#st ep- 3
cdat a=input ("EnterCl i
entMessage: ")
s.send( cdat a. encode( ))
#st ep- 4
sdat a=s. recv (1024) .
decode( )
print("SSPdat aatCSP- ->{}
".
format(sdata))

================================================================

EXAMPLE3:
#Thi spr ogr am receivesEmpnumberf rom cl
i
entsi
deprogr
am ,connectempl
oyee
table, r
eadi ngotherdet ail
sofemploy
eeandsendtocli
entsidepr
ogram.
#EmpDat aSer ver.
py--
--Program-
(A)
i
mpor tsocket
i
mpor tcx_ Oracle
#st ep-1
s=socket .socket()
s.bind(( "127.0.0.1"
,8888))
s.l
ist en(2)
print("SSPi sr eadytoacceptanyCSPRequest :"
)
#st ep-2
whi le(True) :
t
ry:
conn,addr=s.accept ()
eno=int(
conn. recv (
1024).
decode())
#PDBCCode
oracon=cx_Or acl e.
connect
("scott
/ti
ger
@local
host
/or
cl"
)
cur=oracon.cur sor()
cur.
execute("sel ectename,sal,
j
obf r
om empwhereempno=%d"
%eno)
empr ec=cur.
fetchone( )
if
(empr ec==None) :
conn.send("Employ eeRecor dDoesnotExists:
".
encode()
)
else:
conn.send(str(
empr ec).encode())
exceptValueError:
conn.send("Don'tEnterstrs/symbol s/
alpha-numeri
cs".
encode(
))
exceptcx_Oracle.
DatabaseEr rorasdb:
conn.send("Problem inDat abase:"+st
r(db)
.encode(
))

-
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--

#Thisprogr am receiv esEmpName, Sal,Designat i


onandCompNamef
rom Ser
ver
si
depr ogram byconnect i
ngt oemploy eet able
#EmpDat aCl i
ent.py--
--Pr ogram-(A)
i
mpor tsocket
whil
e(True) :
s=socket .
socket ()
s.connect (("127. 0.
0.1",
8888))
print("CSPConnect edt oSSP:")
eno=i nput("\nEnt erEmpl oyeeNumber: "
)
s.send( eno.encode( ))
empr ec=s.recv (1024).decode()
print("Employ eedat a:{}
".
format (empr ec))
ch=i nput("
\nDouwantt ocont inue(yes/ no):
")
if(ch=="no"):
pri
nt ("Thanksf orusingt hispr ogram:"
)
break
================================================================
================================================================
r
andom modul
e
================================================================
=>random oneofpre-defi
nedmodul epresentinpy t
hon
=>Thepur poseofr
andom i sthat"
Togener at
er andom valuesi
nvar
iouscont
ext
s".
=>random modulecontainsthefoll
woingessent i
alfunct
ions.
a)randrange()
b)randint(
)
--
--
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
-
c)random( )
d)uniform()
--
--
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
-
e)choice()
f)shuf f
le(
)
g)sampl e()
--
--
--
---
--
--
---
--
--
--
--
--
--
--
--
--
--
--
===============================================================
a)randrange()

=>Thi
sfunct
ionisusedf orgenerati
ngrandom int
egerval
uesbet
weenspeci
fi
ed
l
imit
s.
Synt
ax1:
- r
andom.r
andrang(
Value)
Thi
ssynt
axgeneratesanyrandom v
aluebet
ween0toVal
ue-
1

Sy
ntax-
2: r
andom.r
angerange(
star
t,
stop)
Thi
ssy
ntaxgener
atesanyrandom val
uebet
weenst
artt
ost
op-
1

Examples:
--
--
--
--
--
--
--
-
>>>importrandom
>>>pri
nt(r
andom. r
andrange(
100,150)
)-
--
-133
>>>pri
nt(r
andom. r
andrange(
100,150)
)-
--
-121
>>>pri
nt(r
andom. r
andrange(
100,150)
)-
--
-139
>>>pri
nt(r
andom. r
andrange(
100,150)
)-
--
-143
>>>pri
nt(r
andom. r
andrange(
100,150)
)-
--
106
>>>pri
nt(r
andom. r
andrange(
100,150)
)-
--
133
>>>pri
nt(r
andom. r
andrange(
10))-
--
-5
>>>pri
nt(r
andom. r
andrange(
10))-
--
-9
--
--
--
--
--
--
--
--
--
---
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
#randrangeex.
py
i
mpor trandom
forii
nr ange(
1,6):
pr
int
(random.randrange(10))
pri
nt("
---
--
--
--
--
--
---
--
--
--
--
--
---
--
--
---
--
-"
)
forii
nr ange(
1,6):
pr
int
(random.randrange(1000,
1100)
)
pri
nt("
---
--
--
--
--
--
---
--
--
--
--
--
---
--
--
---
--
-"
)
================================X============================

b)r
andi
nt(
):

=>Syntax:
- random.r
adint
(st
art
,st
op)
=>Thissyntaxgener
atesanyrandom val
uebet
weenst
artt
ost
op.Her
est
artand
stopareincl
usi
ve.

Exampl es:
>>print(r
andom. r
andint(
10,15))
--
---
-10
>>>pr i
nt(r
andom. r
andint(
10,15))
---
--
13
>>>pr i
nt(r
andom. r
andint(
10,15))
---
-14
>>>pr i
nt(r
andom. r
andint(
10,15))
---
-11
>>>pr i
nt(r
andom. r
andint(
10,15))
---
-15
--
--
--
--
---
---
--
--
--
--
--
--
--
---
--
--
--
---
--
--
--
--
---
--
--
---
#randintex.
py
i
mpor trandom
forii
nr ange(1,
6):
pri
nt(
random. r
andint(
10,20))
pri
nt("
---
---
--
--
--
--
--
--
--
--
---
--
--
--
---
--
--
-"
)
================================================================

c)r
andom(
)

=>Syntax:- r andom.random( )
=>Thissy ntaxgener at
esfloati
ngpoi ntrandom val
uesbetween0.
0and1.
0(Exl
usi
ve)
)
Exampl es:
--
--
--
--
--
----
--
>>>impor trandom
>>>print(random. r
andom( ))
--
--
---
---
0.1623906138450063
>>>print(random. r
andom( ))
--
--
---
-0.15382209709271966
>>>print(random. r
andom( ))
--
--
---
0.09542283007844476
>>>print(random. r
andom( ))
--
--
-0.6134301633766425
--
--
--
--
--
----
--
---
---
---
#randomex .py
i
mpor trandom
l
st=[]
forii
nr ange( 1,
6):
l
st .
append( "
%0.2f"%random. random()
)
pri
nt("
---
---
---
---
--
--
---
--
--
--
--
--
--
---
--
--
-"
)
pri
nt(
"Contentofl
st={
}".
for
mat (
lst
))
================================================================

d)uni
for
m()

Synt
ax:- random.uni
for
m(star
t,
stop)
=>Thi
sgeneratesr
andom fl
oti
ngpointvaluesfrom star
ttostop-1val
ues
=>Theval
uesofstartandst
opcanbot hIntegerorfloat
ingpointval
ues.

Exampl es:
>>>impor trandom
>>>print(r
andom. unif
orm( 10,
15) )-
--
----
---
14.416746067678286
>>>print(r
andom. unif
orm( 10,
15) )-
--
-13.2420406264978
>>>print(r
andom. unif
orm( 10,
15) )-
--
--11.716110933506432
>>>print(r
andom. unif
orm( 10,
15) )-
--
----
-10.703499588966528
>>>print(r
andom. unif
orm( 10,
15) )-
--
--11.306226559323017
>>>print(r
andom. unif
orm( 10.75,15.
75) )--
--
---
-13.939787347170148
>>>print(r
andom. unif
orm( 10.75,15.
75) )--
--
10.760428232717597
--
--
--
--
--
----
--
--
---
--
---
--
--
--
--
--
---
--
---
--
---
---
--
--
----
---
--
---
--
---
--
---
--
--
--
--
--
--
-
#unif
ormex. py
i
mpor trandom
l
st=[]
forii
nr ange(1,6):
l
st.append(fl
oat("
%0. 2f"%random. unif
or m(10,
15.5)
))
pri
nt(
"---
---
--
---
--
--
--
---
--
--
--
--
--
---
--
---
-")
pri
nt(
"Cont entoflst={}
".
format (
lst))
===========================X================================

e)choi
ce(
):

Synt
ax:- random.
choice(
It
erabl
e_obj
ect
)
=>Thi
sfuncti
onobt
ainsrandom val
uesfr
om I
ter
abl
e_obj
ect
.

EXAMPLES:
pri
nt(random. choice(
[10,20,
30,40,
50])
,r
andom.choi
ce("
PYTHON" )
,r
andom.choi
ce(
ran
ge(10,15)))
--
-40T11
>>>
pri
nt(random. choice(
[10,20,
30,40,
50])
,r
andom.choi
ce("
PYTHON" )
,r
andom.choi
ce(
ran
ge(10,15)))
--
----
--
--
30P12
>>>
pri
nt(random. choice(
[10,20,
30,40,
50])
,r
andom.choi
ce("
PYTHON" )
,r
andom.choi
ce(
ran
ge(10,15)))
--
----
--
--
-40N12
--
--
---
--
---
--
--
--
---
---
--
--
---
--
--
--
#choiceex.py
i
mpor trandom
s="AaBRe#^ %@8YuQLPau* &"
foriinrange(1,6):
pr
int(r
andom. choice(s),
random.choi
ce(s)
,r
andom.choi
ce(
s),
random.choi
ce(
s))
===========================X================================
f)shuf fl
e()
:
=>Thi
sFunct
ioni
susedf
orr
e-or
gani
zi
ngt
heel
ement
sofanymut
abl
eobj
ect
.

Synt
ax:
-random.shuf
fl
e(l
ist
)
=>Wecanshuf
fl
ethedataofli
stbutnotot
herobj
ect
sofDat
aTy
pes

Examples:
>>>d={10:"cadbur ry
",
20: "
kitkat",30:"malkybar"
,40:"dai
rymilk"
}
>>>pri
nt(d)---
{10:'cadburry',20: 'kit
kat',
30:'malkybar'
,40:'
dairy
milk'
}
>>>fork,vind. i
tems( )
:
..
. print(
k,"--
",
v)
..
.
10- -cadbur ry
20- -kit
kat
30- -mal kybar
40- -dairymilk
>>>impor trandom
>>>pri
nt(random. shuffle(d))---
-Tr aceback(mostr ecentcalll
ast)
:
Fil
e " <st
din>"
, l i
ne 1, i n <modul e> Fi l
e
"C:
\Users\nareshit\AppDat a\ Local \Programs\Python\Python310\l
ib\
random.py
",
l
ine394, i
nshuf flex[i]
,x [
j]=x[ j]
, x[i
]
KeyErr
or:3

>>>s={10,20,30,40,50}
>>>pri
nt(random. shuffl
e(s))
--
--
--
---
---
--
---
--
-
Traceback(mostr ecentcall
last
):
File"<stdi
n>"
,li
ne1, i
n<modul e>
Fi
le
"C:
\Users\nareshit\AppData\Local\Programs\Python\Python310\l
i
b\random.
py"
,
l
ine394, i
nshuf fle x[i
],x[j
]=x[j
],x[i
]
TypeErr
or: '
set'objecti
snotsubscr iptable

>>>t=(
10,20, 30,40,50)
>>>pri
nt(random. shuf f
le(t
))-
---
--
--
---
--
---
-
Traceback(mostr ecentcall
last
):
File"<st
din>"
,li
ne1, i
n<modul e>
Fi
le
"C:
\Users\nar eshit\AppDat a\Local\Programs\Python\Python310\l
i
b\random.
py"
,
l
ine394, i
nshuf fl
e x[ i
],x[
j]=x[j
],x[i
]
TypeErr
or: '
tuple'obj ectdoesnotsuppor tit
em assignment

>>>l
=[10,20,30,
40, 50]
>>>pri
nt(random. shuffle(l)
)-
--
--
None
>>>pri
nt(l
)--
---
--
--
---
-[30, 40,50,10,20]
>>>random. shuff
le(l)
>>>pri
nt(l
)--
---
--
--
---
[40, 30,10,20,50]
>>>random. shuff
le(l)
>>>pri
nt(l
)--
---
--
--
[40, 10, 50,20,30]
>>>random. shuff
le(l)
>>>pri
nt(l
)--
---
--
--
---
[30, 50,20,40,10]
#shuffl
eex .
py
i
mpor trandom asr
l
=[10,
"Py thon","
Rossum",
34.
56,Tr
ue]
forii
nrange( 1,
6):
r.shuff
le(
l)
pr i
nt(
"cont
entofl
=",
l
)
===================================X============================

g)sampl
e()

=>ThisFuncti
onisusedf orselecti
ngrandom sampl
esf
rom anyI
ter
abl
eobj
ect
basedonnumberofsamples(+ve)
Syntax:
- r andom.
sample(i
ter
able_obj
ect
,k)
=>Here'k'
canbenumberofsampl es.

Exampl es:
--
--
--
---
--
---
--
--
>>>impor trandom
>>>s="ABCabcERTYUer tyu$%^&*#@!%^ &ghjkiy
l"
>>>pr i
nt(r
andom. sampl e(s,
5))-
--
--
--
--
-[
'A'
,'*'
,'
^','
j
','
t'
]
>>>pr i
nt(r
andom. sampl e(s,
5))-
--
--
--
--
['
%','
l'
,'
b','
C','y
']
>>>pr i
nt(r
andom. sampl e(s,
5))-
--
--
--
--
-[
'%','
e'
,'
Y','j
','
u'
]
>>>pr i
nt(r
andom. sampl e(s,
5))-
--
--
-[
'y
','
E'
, '
&'
,'$'
,'#']
>>>pr i
nt(r
andom. sampl e(s,
5))-
--
--
--
--
-[
'j
',
'*'
,'
t'
, '
$'
,'u'
]
--
--
--
---
--
---
--
--
---
--
---
--
---
--
---
--
--
---
--
--
--
--
--
--
--
--
---
--
-
#sampl eex.py
i
mpor trandom
l
st=[10,"
Rossum" ,
"Python",
34.56,
True]
foriinrange(1,6):
pri
nt(r
andom. sample(l
st,
2))
================================X===========================

You might also like