You are on page 1of 90

PYTHONNOTES

UNI
T1
ThePr
ogr
ammi
ngCy
clef
orPy
thon:
Python'
sdevel
opmentcy cl
e i
sdramatical
lyshort
erthanthatoft
radit
ional
tool
s.In 
Python,
ther
e
arenocompileorl
inksteps--
 Pyt
hon programssimplyimportmodulesatrunt
imeanduset he
object
stheycont
ain.Becauseofthi
s,
 Py t
hon pr
ogramsrunimmedi at
elyaft
erchangesare
made.

BecausePy t
honisinterpreted, there'sar apidturnaroundaf t
erpr ogram
changes.AndbecausePy thon' spar serisembeddedi nPy thon- basedsy stems,
i
t'
seasyt omodi f
yprogramsatr unt i
me.Forexampl e,wesawhowGUI
programsdevelopedwi thPy thonal lowdev el
oper stochanget hecodet hat
handlesabuttonpresswhi let heGUIr emai nsactive;theeffectoft hecode
changemaybeobser vedimmedi atelywhent hebut t
oni spressedagai n.
There'snoneedtostopandr ebuild.Mor egener ally
,theent i
redev elopment
processinPythonisanexer ciseinr apidpr otot
yping.Py t
honl endsi tselft
o
experimental
,i
nter
acti
vepr
ogram dev
elopment
,andencour
agesdevel
oping
systemsincremental
l
ybytest
ingcomponentsi
nisol
ati
onandputt
ingthem
togetherl
ater.

Py
thonI
DE:
 
Py thonIDE(I
ntegrat
edDev el
opmentEnvi
ronment
)underst
andyourcodemuchbet tert
hana
textedit
or.I
tusuall
yprovi
desfeatur
essuchasbui
ldautomati
on,codel
ini
ng,test
ingand
debugging.Thiscansigni
fi
cantl
yspeedupyourwork.Thedownsi
deisthatI
DEscanbe
compl i
catedtouse.

Li
stofsomef
amouspy
thonI
DEar
easf
oll
ows:

1. Py
Char
m

2. Jupy
ter

3. Qtdesi
gner

4. Spy
der

5. At
om

Py
thonVar
iabl
es:
Pythonv
ariabl
esaredy
namical
l
yt y
ped,i
tmeanswedonot
needtodeclar
ethedat
aty
peofv ari
abl
es.
Sy
ntax,
a=5
b=”
Hel
l
o”
c=4.
6
pr
int
(a)
pr
int
(b)
pr
int
(c)
out
put
:
5
Hel
l
o
4.
6
Mul
ti
pleassi
gnment
:
x=y
=z=10
pr
int(
x)
pr
int(
y)
pr
int(
z)
out
put
:
10
10
10
Assi
gni
ngmul
ti
plev
aluest
omul
ti
plev
ari
abl
es:

a,
b,
c=5,
7,
10

pr
int
(a)
  
pr
int
(b)
  
pr
int
(c)
  

out
put
:

5
7

10

Py
thonOper
ator
s:

Ar
it
hmet
icOper
ator Descr
ipt
ion

+ addeg.3+6=9

- subt
racteg.3+1=4

* Mul
t,eg.3*
6=18

/ Dev
ide,
eg.15/
6=2.
5

% Modul
ardev
isi
on,
15%6=3

/
/ dev
ide,15/
/6=2

*
* Power
,eg.2*
*4=16

Rel
ati
onal
Oper
ator
s
Thef
oll
owi
ngt
abl
econt
ainst
her
elat
ional
oper
ator
sthatar
eusedt
ocheckr
elat
ions.

Oper
ator
s Descr
ipt
ion

< Lesst
han

> Gr
eat
ert
han

<= Lesst
hanorequal
to

>= Gr
eat
ert
hanorequal
to

== Equal
to
!
= Notequal
to

<> Notequal
to(
simi
l
art
o!=)

eg:

1. >>> 
10<20 
 
2. Tr
ue 
 
3. >>> 
10>20 
 
4. Fal
se 
 
5. >>> 
10<=10 
 
6. Tr
ue 
 
7. >>> 
20>=15 
 
8. Tr
ue 
 
9. >>> 
5==6 
 
10.Fal
se 
 
11.>>> 
5!=6 
 
12.Tr
ue 
 
13.>>> 
10<>2 
 
14.Tr
ue 
 
15.>>> 
 

Assi
gnmentOper
ator
s
Thef
oll
owi
ngt
abl
econt
ainst
heassi
gnmentoper
ator
sthatar
eusedt
oassi
gnv
aluest
othev
ari
abl
es.

Oper
ator
s Descr
ipt
ion

= Assi
gnment

/
= Di
vi
deandAssi
gn

+= Addandassi
gn

-
= Subt
ractandAssi
gn
*
= Mul
ti
plyandassi
gn

%= Modul
usandassi
gn

*
*= Exponentandassi
gn

/
/= Fl
oordi
vi
sionandassi
gn

Exampl
e

1. >>> 
c=10 
 
2. pr
int
(c)o/
p=>10 
 
3. >>> 
c+=5 
 
4. >>> 
pri
nt(
c)o/
p=> 
15 
5. >>> 
c-=5 
 
6. >>> 
pri
nt(
c)o/
p=> 
10 
 
7. >>> 
c*=2 
 
8. >>> 
pri
nt(
c)o/
p=> 
20 
 
9. >>> 
c/=2 
 
10.>>> 
pri
nt(
c)o/
p=> 
10 
 
11.>>> 
c%=3 
 
12.>>> 
pri
nt(
c)o/
p=> 
1  
13.>>> 
c=5 
 
14.>>> 
c**
=2 
 
15.>>> 
pri
nt(
c)o/
p=> 
 25 
 
16.>>> 
c//
=2 
 
17.>>> 
pri
nt(
c)o/
p=> 
 12 
 
 

Logi
cal
Oper
ator
s
Thef
oll
owi
ngt
abl
econt
ainst
hear
it
hmet
icoper
ator
sthatar
eusedt
oper
for
m ar
it
hmet
icoper
ati
ons.

Oper
ator
s Descr
ipt
ion

And Logi
cal
AND(
Whenbot
hcondi
ti
onsar
etr
ueout
putwi
l
lbet
rue)
Or Logi
cal
OR(
Ifanyonecondi
ti
oni
str
ueout
putwi
l
lbet
rue)

Not Logi
cal
NOT(
Compl
i
mentt
hecondi
ti
oni
.e.
,rev
erse)

Exampl
e

1. a=5>4 
and 
3>2 
 
2. pr
int
(a)
  
3. b=5>4 
or 
3<2 
 
4. pr
int
(b)
  
5. c=not
(5>4)
  
6. pr
int
(c)
  

Out
put
:

1. Tr
ue 
 
2. Tr
ue 
 
3. Fal
se 
 

Member
shi
pOper
ator
s
Thef
oll
owi
ngt
abl
econt
ainst
hemember
shi
poper
ator
s.

Oper
ator
s Descr
ipt
ion

I
n Ret
urnst
ruei
fav
ari
abl
eisi
nsequenceofanot
herv
ari
abl
e,el
sef
alse.

noti
n Ret
urnst
ruei
fav
ari
abl
eisnoti
nsequenceofanot
herv
ari
abl
e,el
sef
alse.

Exampl
e

1. a=10 
 
2. b=20 
 
3. l
i
st=[
10,
20,
30,
40,
50]
  
4. i

(a 
in 
l
ist
):
  
5.  
  
 pr
int
("a 
i
s i
n gi
ven 
l
ist
") 
 
6. el
se:
 
 
7.  
  
 pr
int
("a 
i
s not
 i
n gi
ven 
l
ist
") 
 
8. i
f(
b not
 i
n l
i
st)

 
9.  
  
 pr
int
("b 
i
s not
 gi
ven 
i
n l
i
st"

 
10.el
se:
 
 
11. 
  
 pr
int
("b 
i
s gi
ven 
i
n l
i
st"

 

Out
put
:

1. a 
is 
in 
giv
en 
l
ist
  
2. b 
is 
giv
en 
in 
l
ist
  

I
dent
it
yOper
ator
s
Thef
oll
owi
ngt
abl
econt
ainst
hei
dent
it
yoper
ator
s.

Oper
ator
s Descr
ipt
ion

I
s Ret
urnst
ruei
fident
it
yoft
wooper
andsar
esame,
elsef
alse

i
snot Ret
urnst
ruei
fident
it
yoft
wooper
andsar
enotsame,
elsef
alse.

Exampl
e

1. a=20 
 
2. b=20 
 
3. i
f(
 a 
is 
b):
 
 
4.  
  
 pr
int
  
a,
b hav
e same 
i
dent
it
y  
5. el
se:
 
 
6.  
  
 pr
int
 a,
 
b ar
e di
ff
erent
  
7. b=10 
 
8. i
f(
 a 
is 
not
 b)

 
9.  
  
 pr
int
  
a,
b hav
e di
ff
erent
 i
dent
it
y  
10.el
se:
 
 
11. 
  
 pr
int
 a,
b hav
e same 
i
dent
it
y  

Out
put

1. >>> 
  
2. a,
b hav
e same 
i
dent
it
y  
3. a,
b hav
e di
ff
erent
 i
dent
it
y  
4. >>> 
 

I
nput
/Out
putI
nst
ruct
ion:
Out
puti
nst
ruct
ion:
Pr
int
()f
unct
ioni
susedt
opr
inti
npy
thon
e.
g(i
).
pr
int
(“Hel
l
o”)
a=5
pr
int
(a)
o/
p=>Hel
l
o
5
e.
g(i
i
).
a=5
b=6.
5
c=“
wel
come”
pr
int
(a) o/
p=>5
pr
int
(b) o/
p=>6.
5
pr
int
(c) o/
p=>wel
come
pr
int
(a,
b,
c) o/
p=>56.
5wel
come
pri
nt(
“a=”
,a,
”b=”
,b,
”c=”
,c) o/
p=>a=5b=6.
5
c=wel
come

i
nputi
nst
ruct
ion:
i
nput
()f
unct
ioni
susedt
otakei
nputi
npy
thon
t
her
ear
efourmet
hodt
ousei
nputf
unct
ion.
e.
g.(
i)
a=i
nput
(“Ent
erName”
)
pr
int
(a)
Out
put
:
EnterNameRahul
Rahul

Eg(
ii
)
b=i
nt(
input
(“Ent
eranyno.
”)
)
c=b*
b
pr
int
(c)
Out
put
:
Ent
eranyno.7
49

Eg(ii
i
)
b=fl
oat(
input
(“Ent
eranyno.
”)
)
c=b*b
pri
nt(
c)
Out
put:
Ent
eranyno.4.
5
20.
25

Eg(
ii
ii
)
b=eval
(i
nput
(“Ent
eranyno.
”)
)
c=b*b
pri
nt(
c)
Out
put:
Ent
eranyno.3
9

Notes: *ini
nputmet hod,intkeywor di
susedtostoreonl
y
i
nteger value.
*I
ni nputmet hod,fl
oatkeywor disusedtostor
eonlydeci
mal
val
ue.
*I
ni nputmet hod,evalkeywordi susedtost
orebothdeci
mal
andi nt
egerv alue.
*I
ftherei snotanykey word(asintorfl
oatoreval
)thenby
defaultitwil
ltakeinputasst r
ing.
Py
thonComment
s
Py
thonsuppor
tst
wot
ypesofcomment
s:

1)Si
ngl
eli
nedcomment
:

I
ncaseuserwant
stospeci
fyasi
ngl
eli
necomment
,thencommentmustst
artwi
th#

Eg:

1. # 
Thi
s i
s si
ngl
e l
i
ne 
comment

 

2)Mul
til
inedComment
:

Mul
til
i
nedcommentcanbegi
veni
nsi
det
ri
plequot
es.

eg:

1. '
'
''
'
 Thi

2.  
  
 I

3.  
  
 Mul
ti
pli
ne 
comment
'
''
  

eg:

1. #si
ngl
e l
i
ne 
comment
  
2. pr
int
 "
Hel
l
o Py
thon"
  
3. '
'
''
'
Thi
s i

4. mul
ti
li
ne 
comment
'
''
  

Py
thonKey
wor
ds
PythonKeywor
dsarespecial
reser
vedwordswhichconveyaspecialmeaningtothecompil
er/
int
erpr
eter.
Eachkeywordhav
easpecialmeaningandaspecif
icoperat
ion.Thesekey
wor dscan'
tbeusedasv ar
iabl
e.
Fol
lowingi
stheLi
stofPythonKeywords.

Tr
ue Fal
se None And As

Asset Def cl
ass cont
inue br
eak

El
se Fi
nal
l
y el
i
f Del except

Gl
obal For i
f Fr
om i
mpor
t

Rai
se Tr
y or r
etur
n pass

Nonl
ocal I
n not I
s l
ambda

I
dent
if
ier
s
I
dent
if
ier
sar
ethenamesgi
vent
othef
undament
albui
l
dingbl
ocksi
napr
ogr
am.

Thesecanbev
ari
abl
es,
cl
ass,
obj
ect,
funct
ions,
li
sts,
dict
ionar
ieset
c.

Ther
ear
ecer
tai
nrul
esdef
inedf
ornami
ngi
.e.
,I
dent
if
ier
s.

I
.Ani
dent
if
ieri
sal
ongsequenceofchar
act
ersandnumber
s.

I
I.
Nospeci
alchar
act
erexceptunder
scor
e(_)canbeusedasani
dent
if
ier
.

I
II
.Key
wor
dshoul
dnotbeusedasani
dent
if
iername.

I
V.Py
thoni
scasesensi
ti
ve.Sousi
ngcasei
ssi
gni
fi
cant
.

V.
Fir
stchar
act
erofani
dent
if
iercanbechar
act
er,
under
scor
e(_)butnotdi
git
.

UNI
T2
Condi
ti
onal
Stat
ementi
npy
thon:
Ther
ear
evar
ioust
ypesofi
fst
atement
sinPy
thon.

o i
fst
atement
o i
f-
elsest
atement
o nest
edi
fst
atement

Py
thonI
fSt
atementSy
ntax

1. i
f(
condi
ti
on)

 
2.  
  
stat
ement
s  

Py
thonI
fSt
atementExampl
e

1. a=10 
 
2. i

a==10:
 
 
3.  
  
  
  
 pr
int
 "
(Wel
come 
to 
SRCol
l
ege"
 )

Out
put
:

Wel
come 
to 
SRCol
l
ege

Py
thonI
fEl
seSt
atement
s
TheIfstat
ementisusedtotestspeci
fi
edcondi
ti
onandi
fthecondi
ti
oni
str
ue,
ifbl
ockexecut
es,
other
wiseelsebl
ockexecut
es.

Theel
sest
atementexecut
eswhent
hei
fst
atementi
sfal
se.

Py
thonI
fEl
seSy
ntax
1. i
f(
condi
ti
on)

  
 
2.  
  
  
  
  
  
  
stat
ement
s  
3.  
  
 el
se:
 
  
4.  
  
  
  
  
  
  
stat
ement
s  

next
>><<pr
ev

Py
thonI
fel
i
fSt
atement
I
npy
thon,
wecanuseI
fel
i
ftocheckmul
ti
plecondi
ti
ons.Py
thonpr
ovi
des 
eli

key
wor
dtocheck
mul
ti
plecondi
ti
on.

Py
thonI
fel
ifSy
ntax

1. i

condi
ti
on:
 
 
2.  
  
 Code
3. ……… 
 
4. el
if
 condi
ti
on:
 
 
5.  
  
 code
6. …….

 
7. el
se:
 
 
8.  
  
 code

9. …….
.

Py
thonNest
edi
f:
I
npy
thon,
whenweusei
fst
atementi
nsi
deofanyot
heri
fst
atementt
heni
twi
l
lbet
heExampl
eof
Nest
edi
f.

Py
thonNest
edi
fSy
ntax

i

condi
ti
on:
i

condi
ti
on:
 
  Code
……… 
 
 

Loopsi
nPy
thon
1.
Forl
oop

ForLoop
Pyt
hon 
forl
oop i
susedtoit
erat
etheel
ement
sofacol
l
ect
ioni
ntheor
dert
hatt
heyappear
.Thi
scol
l
ect
ion
canbeasequence(
li
storst
ri
ng).

Py
thonForLoopSy
ntax

1. f
or 
<var
iabl
e> 
in 
<sequence>:
 
2. code1
3. ……… 

Expl
anat
ion:

o Fi
rst
ly,
thef
ir
stv
aluewi
l
lbeassi
gnedi
nthev
ari
abl
e.
o Secondl
yal
lthest
atement
sint
hebodyoft
hel
oopar
eexecut
edwi
tht
hesamev
alue.
o Thi
rdl
y,oncest
epsecondi
scompl
etedt
henv
ari
abl
eisassi
gnedt
henextv
aluei
nthesequence
andst
epsecondi
srepeat
ed.
o Fi
nal
l
y,i
tcont
inuest
il
lal
lthev
aluesi
nthesequencear
eassi
gnedi
nthev
ari
abl
eandpr
ocessed.

Py
thonForLoopSi
mpl
eExampl
e

1. num=2 
 
2. f
or 
a i
n r
ange 
(1,
6):
 
 
3.  
  
 pr
int
(num 

a) 
 

Out
put
:

1. 2 
  
 
2. 4 
  
3. 6 
 
4. 8 
 
5. 10 
 

Py
thonExampl
etoFi
ndSum of10Number
s

1. sum=0 
 
2. f
or 
n i
n r
ange(
1,11)

 
3.  
  
 sum+=n 
 
4. Pr
int
(sum)
  
Out
put
:

1. 55 
 

Py
thonNest
edForLoops
Loopsdef
inedwit
hinanotherLoopar
ecal
ledNest
edLoops.Nest
edl
oopsar
eusedt
oit
erat
emat
ri
x
el
ementsortoperf
orm complexcomput
ati
on.

Whenanout
erl
oopcont
ainsani
nnerl
oopi
nit
sbodyi
tiscal
l
edNest
edLoopi
ng.

Py
thonNest
edForLoopSy
ntax

1. f
or 
 <expr
essi
on>:
 
 
2.  
  
  
  
 f
or 
<expr
essi
on>:
 
 
3.  
  
  
  
  
  
 Body
  

Py
thonNest
edForLoopExampl
e

1. f
or 
i
 i
n r
ange(
1,6)

 
2.  
  
 f
or 
j
 i
n r
ange 
(1,
i
+1)

 
3.  
  
  
  
 Pr
int
(i
)
4.  
  
 pr
int
  

Out
put
:

1. 1 
 
2. 2 
2  
3. 3 
3 3 
 
4. 4 
4 4 
4  
5. 5 
5 5 
5 5 
 

Expl
anat
ion:

Foreachv
alueofOut
erl
oopt
hewhol
einnerl
oopi
sexecut
ed.

Foreachv
alueofi
nnerl
oopt
heBodyi
sexecut
edeacht
ime.

Py
thonNest
edLoopExampl
e2

1. f
or 
i
 i
n r
ange 
(1,
6):
 
 
2.  
  
 f
or 
j
 i
n r
ange 
(5,
i
-1,
-
1):
 
 
3.  
  
  
  
 pr
int
("
*")
  
4.  
  
 pr
int
() 
 
Out
put

  

1. *
 * 



 
2. *
 * 


 
3. *
 * 

 
4. *
 * 
 
5. *
  

2.
Whi
l
eloop

Py
thonWhi
l
eLoop
I
nPy t
hon,whil
eloopisusedtoexecutenumberofst
atementsorbodyt
il
lthespeci
fi
edcondi
ti
oni
str
ue.
Oncethecondi
tioni
sfalse,
thecontr
olwil
lcomeoutoftheloop.

Py
thonWhi
leLoopSy
ntax

1. whi
le 
<expr
essi
on>:
 
 
2.  
  
  
  
 Body
  

Her
e, l
oopBodywi
l
lexecut
eti
l
ltheexpr
essi
onpassedi
str
ue.TheBodymaybeasi
ngl
est
atementor
mul
tipl
estat
ement
.

Py
thonWhi
leLoopExampl
e1

1. a=10 
 
2. whi
le 
a>0:
 
 
3.  
  
 pr
int
("Val
ue 
of 
a i
s",
a)
4.  
  
 a=a-
2  

pr
int"
Loopi
sCompl
eted"

Out
put

  

1. Val
ue 
of 
a i
s 10 
 
2. Val
ue 
of 
a i
s 8 
 
3. Val
ue 
of 
a i
s 6 
 
4. Val
ue 
of 
a i
s 4 
 
5. Val
ue 
of 
a i
s 2 
 
6. Loop 
is 
Compl
eted 
 
7. >>> 
 
Expl
anat
ion:

o Fi
rst
ly,
thev
aluei
nthev
ari
abl
eisi
nit
ial
i
zed.
o Secondl
y,t
hecondi
ti
on/
expr
essi
oni
nthewhi
l
eisev
aluat
ed.Consequent
lyi
fcondi
ti
oni
str
ue,
the
cont
rol
ent
ersi
nthebodyandex
ecut
esal
lthest
atement
s.I
fthecondi
ti
on/
expr
essi
onpassed
r
esul
tsi
nfal
set
hent
hecont
rol
exi
stst
hebodyandst
rai
ghtawaycont
rol
goest
onexti
nst
ruct
ion
af
terbodyofwhi
l
e.
o Thi
rdl
y,i
ncasecondi
ti
onwast
ruehav
ingcompl
etedal
lthest
atement
s,t
hev
ari
abl
eis
i
ncr
ement
edordecr
ement
ed.Hav
ingchangedt
hev
alueofv
ari
abl
est
epsecondi
sfol
l
owed.Thi
s
pr
ocesscont
inuest
il
ltheexpr
essi
on/
condi
ti
onbecomesf
alse.
o Fi
nal
l
yRestofcodeaf
terbodyi
sexecut
ed.

Py
thonWhi
leLoopExampl
e2

1. n=153 
 
2. sum=0 
 
3. whi
le 
n>0:
 
 
4.  
  
 r
=n%10 
 
5.  
  
 sum+=r
  
6.  
  
 n=n/
10 
 
7. pr
int
(sum)
  

Out
put

  

1. 9 
 

Py
thonBr
eak
Breakstat
ementi
sajumpstat
ementwhichisusedtot
ransf
erexecut
ioncont
rol
.Itbr
eakst
hecur
rent
execut
ionandi
ncaseofi
nnerl
oop,i
nnerloopter
minat
esimmediatel
y.

Whenbreakstat
ementi
sappli
edt
hecont
rol
point
stothel
i
nefol
lowingthebodyofthel
oop,hence
appl
yi
ngbreakstat
ementmakest
hel
ooptoter
minat
eandcontr
olsgoestonextl
inepoi
nti
ngafterl
oop
body.

Py
thonBr
eakExampl
e1

1. f
or 
i
 i
n [
1,2,
3,
4,
5]:
 
 
2.  
  
 i

i==4:
 
 
3.  
  
  
  
 pr
int
("
Element
 f
ound"

 
4.  
  
  
  
 br
eak 
 
5.  
  
 pr
int
(i
)
Out
put
:


2 3 
Element
 f
ound 
  
 

Py
thonBr
eakExampl
e2

1. f
or 
l
ett
er 
in 
'
Pyt
hon3'
:
  
2.  
  
 i

let
ter
 == 
'
o':
 
 
3.  
  
  
  
 br
eak 
 
4.  
  
 pr
int
 (
let
ter

 

Out
put
:

1. P 
 
2. y
  
3. t
  
4. h 
 

Py
thonCont
inueSt
atement
Pyt
honConti
nueSt
atementi
saj umpstatementwhi
chi
susedt
oski
pexecut
ionofcur
renti
ter
ati
on.Af
ter
ski
ppi
ng,
loopcont
inuewi
thnextit
erat
ion.

Wecanusecont
inuest
atementwi
thf
oraswel
laswhi
l
eloopi
nPy
thon.
Py
thonCont
inueSt
atementExampl
e

1. a=0 
 
2. whi
le 
a<=5:
 
 
3.  
  
 a=a+1 
 
4.  
  
 i

a%2==0:
 
 
5.  
  
  
  
 cont
inue 
 
6.  
  
 pr
int
(a)
  
7. pr
int
("End 
of 
Loop"

 

Out
put

  

1. 1 
 
2. 3 
 
3. 5 
 
4. End 
of 
Loop 

Py
thonPass
I
nPy t
hon,passkeywor
disusedtoexecut
enothi
ng;itmeans,whenwedon' twantt
oexecutecode,
the
passcanbeusedtoexecuteempty
.Iti
ssameast henamer ef
ersto.I
tjustmakesthecont
rolt
opassby
wit
houtexecut
inganycode.I
fwewanttobypassanycodepassstatementcanbeused.

Py
thonPassSy
ntax

1. pass 
 

Py
thonPassExampl
e

1. f
or 
i
 i
n [
1,2,
3,
4,
5]:
 
 
2.  
  
 i

i==3:
 
 
3.  
  
  
  
 pass 
 
4.  
  
  
  
 pr
int
 "
Pass 
when 
val
ue 
i
s",
i
  
5.  
  
 pr
int
 i

 

Out
put
:

1. >>> 
  
2. 1 
2 Pass 
when 
val
ue 
is 
3  
3. 3 
4 5 
 
UNI
T3
Py
thonFunct
ions
Funct
ionsarethemostimpor
tantaspectofanappl
icati
on.Afunct
ioncanbedef
inedast
heor
gani
zed
bl
ockofreusablecodewhi
chcanbecal l
edwheneverrequi
red.

Pythonal
lowsust odiv
idealar
geprogr
am i
ntot
hebasicbuil
dingblocksknownasfunct
ion.Thefunct
ion
contai
nsthesetofprogrammingst
atement
sencl
osedby{}.Af unct
ioncanbecal
ledmulti
pleti
mest o
provi
dereusabi
l
ityandmodulari
tyt
othepyt
honprogr
am.

Adv
ant
ageoff
unct
ionsi
npy
thon
Ther
ear
ethef
oll
owi
ngadv
ant
agesofCf
unct
ions.

o Byusi
ngf
unct
ions,
wecanav
oidr
ewr
it
ingsamel
ogi
c/codeagai
nandagai
ninapr
ogr
am.
o Wecancal
lpy
thonf
unct
ionsanynumberoft
imesi
napr
ogr
am andf
rom anypl
acei
napr
ogr
am.
o Wecant
rackal
argepy
thonpr
ogr
am easi
l
ywheni
tisdi
vi
dedi
ntomul
ti
plef
unct
ions.
o Reusabi
l
ityi
sthemai
nachi
evementofpy
thonf
unct
ions.
o Howev
er,
Funct
ioncal
l
ingi
sal
way
sov
erheadi
napy
thonpr
ogr
am.

Sy
ntaxofCr
eat
ingaf
unct
ion
I
npython,wecanuse 
def
 key
wor
dtodef
inet
hef
unct
ion.Thesy
ntaxt
odef
ineaf
unct
ioni
npy
thoni
s
gi
venbelow.

1. def
 my
_funct
ion(
):
  
2.  
  
 f
unct
ion-
sui
te 
  
3.  
  
 r
etur
n <expr
essi
on> 
  

Thef
unctionblockisst
art
edwi
tht
hecol
on(
:)andal
lthesamel
evel
blockst
atement
sremai
natt
he
sameindentat
ion.

Afunct
ioncanacceptanynumberofpar
amet
erst
hatmustbet
hesamei
nthedef
ini
ti
onandf
unct
ion
cal
li
ng.

Funct
ioncal
l
ing
Inpython,afuncti
onmustbedef inedbefor
ethefuncti
oncall
i
ngot her
wisethepy
thoni
nter
pretergi
vesan
error
.Oncethef unct
ionisdef
ined,wecancallitf
rom anot
herfuncti
onorthepyt
honpr
ompt .Tocallt
he
functi
on,usethefuncti
onnamef ollowedbytheparent
heses.

Asi
mpl
efunct
iont
hatpr
int
sthemessage"
Hel
l
oWor
d"i
sgi
venbel
ow.
1. def
 hel
l
o_wor
ld(
):
  
2.  
  
 pr
int
("hel
l
o wor
ld"

 
3.  
 
4. hel
l
o_wor
ld(

  
 

Out
put
:

hel
l
owor
ld

Par
amet
ersi
nfunct
ion
Theinf
ormationi
ntot
hefunct
ionscanbepassedasthepar
ameter
s.Thepar
ametersar
especi
fi
edi
nthe
par
entheses.Wecangiv
eanynumberofparameter
s,butwehav
etoseparat
ethem wi
thacomma.

Ex
ampl
e2
1. #py
thon 
funct
ion 
to 
cal
cul
ate 
the 
sum 
of 
two 
var
iabl
es 
  
2. #def
ini
ng 
the 
funct
ion 
 
3. def
 sum 
(a,
b):
 
 
4.  
  
 r
etur
n a+b 
 
5.  
 
6. #t
aki
ng 
val
ues 
fr
om 
the 
user
  
7. a 
= i
nt(
input
("
Ent
er 
a: 
")

 
8. b 
= i
nt(
input
("
Ent
er 
b: 
")

 
9.  
 
10.#pr
int
ing 
the 
sum 
of 
a and 
b  
11.pr
int
("Sum 
= "
,sum(
a,b)

 

Out
put
:

Ent
era:
10
Ent
erb:
20
Sum =30

Ty
pesofar
gument
s(Par
amet
ers)
Ther
emaybesev
eral
typesofar
gument
swhi
chcanbepassedatt
het
imeoff
unct
ioncal
l
ing.
1. Requi
redar
gument
s
2. Key
wor
dar
gument
s
3. Def
aul
tar
gument
s
4. Var
iabl
e-l
engt
har
gument
s

Requi
redAr
gument
s
Til
lnow,wehav elearnedaboutf
uncti
oncal linginpy t
hon.Howev er,
wecanpr ovi
detheargumentsatthe
ti
meoff uncti
oncalli
ng.Asfarastherequiredar gument sareconcerned,t
hesear
etheargumentswhi ch
arerequi
redtobepassedatt hetimeoffunct ioncalli
ngwi t
htheexactmat choft
hei
rpositi
onsi
nt he
functi
oncallandfuncti
ondefi
nit
ion.I
feitheroft heargument si
snotpr ovi
dedint
hefunct
ioncall
,orthe
posit
ionoftheargument si
schanged,thent hepy thoninter
pret
erwillshowtheer
ror
.

1. def
 f
unc(
name)

 
2.  
  
 message 
= "
Hi 
"+name;
 
 
3.  
  
 r
etur
n message;
 
 
4. name 
= i
nput
("
Ent
er 
the 
name?
") 
 
5. pr
int
(func(
name)

 

Key
wor
dar
gument
s
Pythonal
lowsustocall
thefuncti
onwit
hthekey
wor
dar
gument
s.Thi
ski
ndoff
unct
ioncal
lwi
l
lenabl
eus
topasstheargument
sintherandom or
der
.

Thenameoft
heargumentsi
str
eatedast
hekeywordsandmatchedinthefuncti
oncal
li
nganddef
ini
ti
on.
I
fthesamematchi
sfound,t
heval
uesoft
heargumentsar
ecopiedinthefunct
iondefi
nit
ion.

Consi
dert
hef
oll
owi
ngexampl
e.

Ex
ampl
e1
1. #f
unct
ion 
func 
i
s cal
l
ed 
wit
h t
he 
name 
and 
message 
as 
the 
key
wor
d ar
gument
s  
2. def
 f
unc(
name,
message)

 
3.  
  
 pr
int
("pr
int
ing 
the 
message 
wit
h",
name,
"and 
",
message)
  
4. f
unc(
name 
= "
John"
,message="
hel
l
o")
 #name 
and 
message 
i
s copi
ed 
wit
h t
he 
val
ues 
John 
and 
hel
l
o r
esp
ect
ivel

 

Out
put
:

pr
int
ingt
hemessagewi
thJohnandhel
l
o
Def
aul
tAr
gument
s
Pyt
honall
owsustoini
tial
i
zethear
gumentsatthef unct
iondef
ini
ti
on.I
ftheval
ueofanyoft
heargument
i
snotprovi
dedatthet
imeoffunct
ioncal
l,
thenthatargumentcanbeini
tial
i
zedwi
ththeval
uegi
veninthe
def
ini
ti
oneveni
ftheargumenti
snotspeci
fiedatthefuncti
oncal
l.

Ex
ampl
e1
1. def
 pr
int
me(
name,
age=22)

 
2.  
  
 pr
int
("My
 name 
i
s",
name,
"and 
age 
i
s",
age)
  
3. pr
int
me(
name 
= "
john"

#the 
var
iabl
e age 
i
s not
 passed 
i
nto 
the 
funct
ion 
howev
er 
the 
def
aul

val
ue 
of 
age 
i
s consi
der
ed 
i
n t
he 
funct
ion 
 

Out
put
:

Mynamei
sjohnandagei
s22

Var
iabl
elengt
hAr
gument
s
Inthelar
geproject
s,sometimeswemaynotknowthenumberofar
gumentstobepassedi
nadvance.I
n
suchcases,Pythonprov
idesusthefl
exi
bil
i
tyt
oprovi
dethecommasepar
atedval
ueswhichar
einter
nal
ly
treat
edastuplesatthefuncti
oncal
l
.

Howev
er,
att
hef
unct
iondef
ini
ti
on,
wehav
etodef
inet
hev
ari
abl
ewi
th*(
star
)as*
<var
iabl
e-name>.

Consi
dert
hef
oll
owi
ngexampl
e.

Ex
ampl
e
1. def
 pr
int
me(
*names)

 
2.  
  
 pr
int
("t
ype 
of 
passed 
argument
 i
s "
,t
ype(
names)

 
3.  
  
 pr
int
("pr
int
ing 
the 
passed 
argument
s..
."

 
4.  
  
 f
or 
name 
in 
names:
 
 
5.  
  
  
  
 pr
int
(name)
  
6. pr
int
me(
"j
ohn"
,"
Dav
id"
,"
smi
th"
,"
nick"

 

Out
put
:

t
ypeofpassedar
gumenti
s<cl
ass'
tupl
e'
>
pr
int
ingt
hepassedar
gument
s..
.
j
ohn
Dav
id
smi
th
ni
ck
Scopeofv
ari
abl
es
Thescopesoft
hevar
iabl
esdependupont
helocat
ionwherethevar
iabl
eisbei
ngdecl
ared.Thev
ari
abl
e
decl
aredi
nonepar
toftheprogr
am maynotbeaccessi
blet
ot heot
herpar
ts.

I
npy
thon,
thev
ari
abl
esar
edef
inedwi
tht
het
wot
ypesofscopes.

1. Gl
obal
var
iabl
es
2. Local
var
iabl
es

Thevari
abledefi
nedoutsi
deanyfuncti
onisknownt
ohav
eagl
obal
scopewher
east
hev
ari
abl
edef
ined
i
nsideafuncti
onisknowntohaveal ocal
scope.

Consi
dert
hef
oll
owi
ngexampl
e.

Ex
ampl
e1
1. def
 pr
int
_message(
):
  
2.  
  
 message 
= "
hel
l
o !


am 
goi
ng 
to 
pri
nt 
a message.

# t
he 
var
iabl
e message 
i
s l
ocal
 
to 
the 
funct
ion 
i
tsel

 
3.  
  
 pr
int
(message)
  
4. pr
int
_message(

 
5. pr
int
(message)
 # 
thi
s wi
l

cause 
an 
err
or 
since 
a l
ocal
 
var
iabl
e cannot
 be 
accessi
ble 
her
e. 
  

Out
put
:

hel
l
o!!Iam goi
ngt
opr
intamessage.
Fi
l
e"/
root
/Py
char
mPr
oject
s/Py
thonTest
/Test
1.py
",l
i
ne5,
in
pr
int
(message)
NameEr
ror
:name'
message'
isnotdef
ined

Ex
ampl
e2
1. def
 cal
cul
ate(
*ar
gs)

 
2.  
  
 sum=0 
 
3.  
  
 f
or 
arg 
in 
args:
 
 
4.  
  
  
  
 sum 
= sum 
+ar
g  
5.  
  
 pr
int
("The 
sum 
i
s",
sum)
  
6. sum=0 
 
7. cal
cul
ate(
10,
20,
30)
 #60 
wil
l
 be 
pri
nted 
as 
the 
sum 
 
8. pr
int
("Val
ue 
of 
sum 
out
side 
the 
funct
ion:
",
sum)
 # 
0 wi
l

be 
pri
nted 
 

Out
put
:

Thesum i
s60
Val
ueofsum out
sidet
hef
unct
ion:
0
Py
thonSt
ri
ng
Ti
l
lnow,wehavedi
scussednumbersasthestandarddatat
y pesi
npy
thon.I
nthi
ssect
ionoft
het
utor
ial
,
wewil
ldi
scusst
hemostpopulardat
atypeinpythoni.
e.,
str
ing.

I
npy t
hon,
str
ingscanbecreatedbyenclosi
ngthecharact
erorthesequenceofcharact
ersint
hequot
es.
Pyt
honall
owsustousesinglequotes,
doublequotes,
ortri
plequot
estocr eat
ethestri
ng.

1. st

= "
Hi 
Pyt
hon 
!"
  

Her
e,i
fwecheckt
het
ypeoft
hev
ari
abl
est
rusi
ngapy
thonscr
ipt

1. pr
int
(ty
pe(
str
)),
 
then 
i
t wi
l

pri
nt 
str
ing 
(st
r).
  

St
ri
ngsi
ndexi
ngandspl
i
tti
ng
Li
keotherl
anguages,thei
ndexi
ngofthepy
thonst
ri
ngsst
art
sfr
om 0.Forexampl
e,Thest
ri
ng"
HELLO"i
s
i
ndexedasgiveni
nt hebel
owf i
gur
e.
Asshowninpyt
hon,thesl
iceoper
ator[]i
susedtoaccessthei
ndi
vidual
char act
ersofthestri
ng.Howev
er,
wecanusethe:(col
on)operat
ori
npy t
hontoaccessthesubst
ri
ng.Considerthefol
lowingexample.

Her
e,wemustnoti
cethattheupperrangegi
veni
nthesl
i
ceoper at
orisal
waysexcl
usi
vei
.e.
,i
fstr=
'
pyt
hon'
isgi
ven,
thenstr[
1:3]wi
llal
way si
ncl
udest
r[
1]='
p',
str
[2]='y'
,st
r[
3]='
t'
andnothi
ngelse.

Reassi
gni
ngst
ri
ngs
Updati
ngt hecontentoft
hestri
ngsisaseasyasassigningi
ttoanewst
ri
ng.Thest
ri
ngobjectdoesn'
t
supporti
tem assi
gnmenti.e.
,Astr
ingcanonlybereplacedwit
hanewstr
ingsi
ncei
tscont
entcannotbe
part
ial
l
yreplaced.Stri
ngsarei
mmut abl
einpython.

Consi
dert
hef
oll
owi
ngexampl
e.

Ex
ampl
e1
1. st

= "
HELLO"
  
2. st
r[
0] 
= "
h" 
 
3. pr
int
(st
r) 
 
next→← pr
ev

Py
thonSt
ri
ng
Ti
l
lnow,
wehav
edi
scussednumber
sast
hest
andar
ddat
aty
pesi
npy
thon.I
nthi
ssect
ionoft
he
t
utor
ial
,wewi
l
ldi
scusst
hemostpopul
ardat
aty
pei
npy
thoni
.e.
,st
ri
ng.

I
npy
thon,
str
ingscanbecr
eat
edbyencl
osi
ngt
hechar
act
erort
hesequenceofchar
act
ersi
nthe
quot
es.Py
thonal
l
owsust
ousesi
ngl
equot
es,
doubl
equot
es,
ort
ri
plequot
est
ocr
eat
ethest
ri
ng.

Consi
dert
hef
oll
owi
ngexampl
einpy
thont
ocr
eat
east
ri
ng.

1. st

= "
Hi 
Pyt
hon 
!"
  

Her
e,i
fwecheckt
het
ypeoft
hev
ari
abl
est
rusi
ngapy
thonscr
ipt

1. pr
int
(ty
pe(
str
)),
 
then 
i
t wi
l

pri
nt 
str
ing 
(st
r).
  

I
npy
thon,
str
ingsar
etr
eat
edast
hesequenceofst
ri
ngswhi
chmeanst
hatpy
thondoesn'
tsuppor
tthe
char
act
erdat
aty
pei
nst
eadasi
ngl
echar
act
erwr
it
tenas'
p'i
str
eat
edast
hest
ri
ngofl
engt
h1.

St
ri
ngsi
ndexi
ngandspl
i
tti
ng
Li
keot
herl
anguages,
thei
ndexi
ngoft
hepy
thonst
ri
ngsst
art
sfr
om 0.Forexampl
e,Thest
ri
ng
"
HELLO"i
sindexedasgi
veni
nthebel
owf
igur
e.
Asshowni
npy
thon,
thesl
i
ceoper
ator[
]isusedt
oaccesst
hei
ndi
vi
dual
char
act
ersoft
hest
ri
ng.
Howev
er,
wecanuset
he:
(col
on)oper
atori
npy
thont
oaccesst
hesubst
ri
ng.Consi
dert
hef
oll
owi
ng
exampl
e.
Her
e,wemustnot
icet
hatt
heupperr
angegi
veni
nthesl
i
ceoper
atori
sal
way
sexcl
usi
vei
.e.
,i
fst
r=
'
pyt
hon'
isgi
ven,
thenst
r[
1:3]wi
l
lal
way
sincl
udest
r[
1]='
p'
,st
r[
2]='
y'
,st
r[
3]='
t'
andnot
hingel
se.

Reassi
gni
ngst
ri
ngs
Updat
ingt
hecont
entoft
hest
ri
ngsi
saseasyasassi
gni
ngi
ttoanewst
ri
ng.Thest
ri
ngobj
ectdoesn'
t
suppor
tit
em assi
gnmenti
.e.
,Ast
ri
ngcanonl
yber
epl
acedwi
thanewst
ri
ngsi
ncei
tscont
entcannot
bepar
ti
all
yrepl
aced.St
ri
ngsar
eimmut
abl
einpy
thon.

Consi
dert
hef
oll
owi
ngexampl
e.

Exampl
e1
1. st

= "
HELLO"
  
2. st
r[
0] 
= "
h" 
 
3. pr
int
(st
r) 
 
Out
put
:

Tr
aceback(
mostr
ecentcal
ll
ast
):
Fi
l
e"12.
py"
,li
ne2,
in<modul
e>
st
r[
0]="
h";
Ty
peEr
ror
:'st
r'obj
ectdoesnotsuppor
tit
em assi
gnment

Howev
er,
inexample1,
thest
ri
ngst
rcanbecompl
etel
yassi
gnedt
oanewcont
entasspeci
fi
edi
nthe
f
oll
owi
ngexample.

Ex
ampl
e2
1. st

= "
HELLO"
  
2. pr
int
(st
r) 
 
3. st

= "
hel
l
o" 
 
4. pr
int
(st
r) 
 

Out
put
:

HELLO
hel
lo

St
ri
ngOper
ator
s
Oper
ator Descr
ipt
ion

+ I
tisknownasconcat
enat
ionoper
atorusedt
ojoi
nthest
ri
ngsgi
venei
thersi
deoft
heoper
ator
.

* I
tisknownasr
epet
it
ionoper
ator
.Itconcat
enat
est
hemul
ti
plecopi
esoft
hesamest
ri
ng.

[
] I
tisknownassl
i
ceoper
ator
.Iti
susedt
oaccesst
hesub-
str
ingsofapar
ti
cul
arst
ri
ng.

[
:] I
tisknownasr
angesl
i
ceoper
ator
.Iti
susedt
oaccesst
hechar
act
ersf
rom t
hespeci
fi
edr
ange.

i
n I
tisknownasmember
shi
poper
ator
.Itr
etur
nsi
fapar
ti
cul
arsub-
str
ingi
spr
esenti
nthespeci
fi
ed
st
ri
ng.
noti
n I
tisal
soamember
shi
poper
atoranddoest
heexactr
ever
seofi
n.I
tret
urnst
ruei
fapar
ti
cul
arsubst
ri
ng
i
snotpr
esenti
nthespeci
fi
edst
ri
ng.

r
/R I
tisusedt
ospeci
fyt
her
awst
ri
ng.Rawst
ri
ngsar
eusedi
nthecaseswher
eweneedt
opr
intt
heact
ual
meani
ngofescapechar
act
erssuchas"
C:/
/py
thon"
.Todef
ineanyst
ri
ngasar
awst
ri
ng,
thechar
act
err
orRi
sfol
l
owedbyt
hest
ri
ng.

% I
tisusedt
oper
for
m st
ri
ngf
ormat
ti
ng.I
tmakesuseoft
hef
ormatspeci
fi
ersusedi
nCpr
ogr
ammi
ng
l
i
ke%dor%ft
omapt
hei
rval
uesi
npy
thon.Wewi
l
ldi
scusshowf
ormat
ti
ngi
sdonei
npy
thon.

Ex
ampl
e
Consi
dert
hef
oll
owi
ngexampl
etounder
standt
her
eal
useofPy
thonoper
ator
s.

1. st

= "
Hel
l
o" 
  
2. st
r1 
= "
 wor
ld"
  
3. pr
int
(st
r*3)
 # 
pri
nts 
Hel
l
oHel
l
oHel
l
o  
4. pr
int
(st
r+st
r1)
# pr
int
s Hel
l
o wor
ld 
  
5. pr
int
(st
r[
4])
 # 
pri
nts 
o  
  
  
  
  
  
  
6. pr
int
(st
r[
1:4]
);
 # 
pri
nts 
ell
 
  
  
  
 
  
  
  
  
  
7. pr
int
('
w' 
in 
str

# pr
int
s f
alse 
as 
w i
s not
 pr
esent
 i
n st

 
8. pr
int
('
wo'
 
not
 i
n st
r1)
 # 
pri
nts 
fal
se 
as 
wo 
i
s pr
esent
 i
n st
r1.
  
 
9. pr
int
(r'
C:/
/py
thon37'

# pr
int
s C:
//py
thon37 
as 
i
t i
s wr
it
ten 
 
10.pr
int
("The 
str
ing 
str
 :
 %s"
%(st
r))
 # 
pri
nts 
The 
str
ing 
str
 :
 Hel
l

11.pr
int
('
H' 
in 
str

# pr
int
s t
rue 
as 
H i
s pr
esent
 i
n st

 
 
 Out
put
:
HelloHell
oHell
o
Helloworld
o
l
l
False
False
C://pyt
hon37
Thest r
ingstr:Hel
l
o
True

Py
thonFor
mat
ti
ngoper
ator
Pythonal
l
owsust ousethefor
matspeci
fi
ersusedinC'spri
ntfst
atement .Theformatspeci
fi
ersin
pyt
honaretr
eatedinthesamewayastheyaretr
eatedinC.Howev er,
Py t
honpr ovi
desanaddit
ional
operat
or%whichisusedasanint
erf
acebetweentheformatspeci
fiersandt hei
rval
ues.I
notherwords,
wecansaythatitbi
ndsthefor
matspeci
fi
erstotheval
ues.
Consi
dert
hef
oll
owi
ngexampl
e.

1. I
nteger
 = 
10;
 
 
2. Fl
oat
 = 
1.290 
 
3. St
ri
ng 
= "
Ayush"
  
4. pr
int
("Hi
 
I am 
Int
eger
 .
..
 My
 val
ue 
i
s %d\
nHi
 
I am 
fl
oat
 .
..
 My
 val
ue 
i
s %f
\nHi
 
I am 
str
ing 
..

My 
val
ue 
i
s %s"
%
(
Int
eger
,Fl
oat
,St
ri
ng)
);
  

Out
put
:

Hi
Iam Integer..
.Myv al
ueis10
Hi
Iam float..
.Myvalueis1.290000
Hi
Iam string..
.MyvalueisAyush

Lengt
hOfSt
ri
ng
Lenf
unct
ioni
susedt
ocal
cul
atet
hel
engt
hofst
ri
ng.

Eg.

Name=’intr
otopyt
hon’
Pri
nt(
len(Name)
)
Ouput:
15

Sl
i
cingOfSt
ri
ng
Py
thonDat
aSt
ruct
ure(
Col
l
ect
ion)
:
Ther
ear
efourcol
l
ect
iondat
aty
pesi
nthePy
thonpr
ogr
ammi
ngl
anguage:
o Li
st
o Tupl
e
o Set
o Di
cti
onar
y
o St
ri
ng
o Number

Li
st:
Al
istisacol
lect
ionwhichi
sorder
edandchangeabl
e.I
nPy
thonl
i
stsar
e
wr
itt
enwithsquarebr
acket
s.

Ex
ampl
e
Cr
eat
eaLi
st:

thi
sli
st=["
apple"

"banana"

"cher
ry"
]
pri
nt(
thi
sli
st)

Out
put
:["
appl
e",
 
"banana"

"cher
ry"
]

Ex
ampl
e
Pr
intt
hesecondi
tem oft
hel
i
st:

thi
sli
st=["
apple"

"banana"

"cher
ry"
]
pri
nt(
thi
sli
st[
1])

out
put
:banana

Ex
ampl
e
Ret
urnt
het
hir
d,f
our
th,
andf
if
thi
tem:

thi
sli
st=["
apple"

"banana"

"cher
ry"

"or
ange"

"ki
wi"

"mel
on"

"mango"
]
pri
nt(
thi
sli
st[
2:5]
)

out
put
:cher
ry,
 
orange,
 
kiwi
Ex
ampl
e
Thi
sexampl
eret
urnst
hei
temsf
rom i
ndex-
4(i
ncl
uded)t
oindex-
1(excl
uded)

thi
sli
st=["
apple",
 
"banana"

"cher
ry"

"or
ange"

"ki
wi"

"mel
on"

"mango"
]
pri
nt(
thi
sli
st[
-4:
-1]
)

Out
put
:["
orange"

"ki
wi"

"mel
on"
]

ChangeI
tem Val
ue
Tochanget
hev
alueofaspeci
fi
cit
em,
ref
ert
othei
ndexnumber
:

Ex
ampl
e
Changet
hesecondi
tem:

thi
sli
st=["apple"

"banana",
 
"cher
ry"
]
thi
sli
st[
1]= "bl
ackcurrant
"
pri
nt(
thisl
i
st)

out
put
:["
appl
e",
 
"bl
ackcur
rant"

"cher
ry"
]

LoopThr
oughaLi
st
Youcanl
oopt
hrought
hel
i
sti
temsbyusi
nga 
f  
orl
oop:

Ex
ampl
e
Pr
intal
li
temsi
nthel
i
st,
onebyone:

t
hisli
st=["appl
e",
 
"banana"

"cher
ry"
]
f
or x 
in t
hisl
i
st:
 
 pri
nt(x)

out
put
:

apple
banana
cherr
y
Checki
fIt
em Exi
sts
Todet
ermi
nei
faspeci
fi
edi
tem i
spr
esenti
nal
i
stuset i
he n 
key
wor
d:

Ex
ampl
e
Checki
f"appl
e"i
spr
esenti
nthel
i
st:

t
hisli
st=["apple",
 "
banana",
 
"cher
ry"
]
i
f "
apple"
 i
n thisl
i
st:
 
 pri
nt(
"Yes,'apple'
isinthefr
uit
sli
st"
)

out
put
:Yes,
'appl
e'i
sint
hef
rui
tsl
i
st

Thel
i
st(
)Const
ruct
or
I
tisal
sopossi
blet
ouset l
he i
st(

const
ruct
ort
omakeanewl
i
st.

Ex
ampl
e
Usi
ngt l
he i
st(

const
ruct
ort
omakeaLi
st:

thi
sli
st=li
st(
("appl
e",
 
"banana"

"cher
ry"
)) 
#not
ethedoubl
eround-
bracket
s
pri
nt(
thi
sli
st)

[
'
appl
e'
,'
banana'
,'
cher
ry'
]

Note:Learnsomelistfuncti
onsf
rom y
ourcl
assnot
esl
ike,
del
,remove,
pop,inser
t,sor
t,sort
edet c.

Tupl
e
At
upl
eisacol
l
ect
ionwhi
chi
sor
der
edand 
unchangeabl
e.I
nPy
thont
upl
esar
ewr
it
tenwi
th
roundbracket
sOrWi t
houtbracket
s.
Tuplesalsocal
ledasi
mmut abledatat
ypes.

Ex
ampl
e
Cr
eat
eaTupl
e:

thi
stupl
e=( "
appl
e",
 
"banana"

"cher
ry"
)
pri
nt(t
hist
upl
e)

Out
put
t:(
'appl
e'
,'
banana'
,'
cher
ry'
)

AccessTupl
eIt
ems
Youcanaccesst
upl
eit
emsbyr
efer
ri
ngt
othei
ndexnumber
,insi
desquar
ebr
acket
s:

Ex
ampl
e
Pr
intt
hesecondi
tem i
nthet
upl
e:

thi
stupl
e=( "
appl
e",
 
"banana"

"cher
ry"
)
pri
nt(t
hist
upl
e[1]
)

out
put
:banana

Negat
iveI
ndexi
ng
Negati
veindexi
ngmeansbegi
nni
ngf
rom t
heend,
 
-1 
ref
erst
othel
asti
tem,
 
-2 
ref
erst
othe
secondlasti
tem et
c.

Ex
ampl
e
Pr
intt
hel
asti
tem oft
het
upl
e:

thi
stupl
e=( "
appl
e",
 "
banana"

"cher
ry"
)
pri
nt(t
hist
upl
e[-
1])

out
put
:cher
ry

RangeofI
ndexes
Youcanspeci
fyar
angeofi
ndexesbyspeci
fyi
ngwher
etost
artandwher
etoendt
her
ange.
Whenspeci
fyi
ngar
ange,
ther
etur
nval
uewi
l
lbeanewt
upl
ewi
tht
hespeci
fi
edi
tems.

Ex
ampl
e
Ret
urnt
het
hir
d,f
our
th,
andf
if
thi
tem:

thi
stupl
e=( "
appl
e",
 "
banana"

"cher
ry"

"or
ange"

"ki
wi"

"mel
on"

"mango"
)
pri
nt(t
hist
upl
e[2:
5])

out
put
:("
orange"

"ki
wi"

"mel
on"
)

RangeofNegat
iveI
ndexes
Speci
fynegat
ivei
ndexesi
fyouwantt
ost
artt
hesear
chf
rom t
heendoft
het
upl
e:

Ex
ampl
e
Thi
sexampl
eret
urnst
hei
temsf
rom i
ndex-
4(i
ncl
uded)t
oindex-
1(excl
uded)

thi
stupl
e=( "
appl
e",
 "
banana"

"cher
ry"

"or
ange"

"ki
wi"

"mel
on"

"mango"
)
pri
nt(t
hist
upl
e[-
4:-
1])

out
put
:("
orange"

"ki
wi"

"mel
on"
)

LoopThr
oughaTupl
e
Youcanl
oopt
hrought
het
upl
eit
emsbyusi f
nga or
 l
oop.

Ex
ampl
e
I
ter
atet
hrought
hei
temsandpr
intt
hev
alues:

t
histuple=("appl
e",
 
"banana"

"cher
ry"
)
f
or x i
n t
hist
uple:
 
 pri
nt(x)

out
put
:

appl
e
banana
cher
ry

Checki
fIt
em Exi
sts
Todet
ermi
nei
faspeci
fi
edi
tem i
spr
esenti
nat
upl
euset
he 

i key
wor
d:

Ex
ampl
e
Checki
f"appl
e"i
spr
esenti
nthet
upl
e:

t
histupl
e=( "
apple"

"banana"

"cherr
y")
i
f "
apple" 
i
n t
hist
uple:
 
 pri
nt("
Yes,'
apple'
isinthefr
uitstupl
e")

out
put
:Yes,
'appl
e'i
sint
hef
rui
tst
upl
e

Tupl
eLengt
h
Todet
ermi
nehowmanyi
temsat
upl
ehas,
uset
he 
l
en(

met
hod:

Ex
ampl
e
Pr
intt
henumberofi
temsi
nthet
upl
e:

thi
stupl
e=("appl
e",
 "
banana"

"cher
ry"
)
pri
nt(l
en(
thi
stupl
e))

out
put
:3

Thet
upl
e()Const
ruct
or
I
tisal
sopossi
blet
ouset t
he upl
e()
 const
ruct
ort
omakeat
upl
e.

Ex
ampl
e
Usi
ngt
het
upl
e()met
hodt
omakeat
upl
e:

thi
stupl
e=t upl
e((
"appl
e",
 
"banana"

"cher
ry"
)) 
#not
ethedoubl
eround-
bracket
s
pri
nt(t
hist
uple)

out
put
:('
appl
e'
,'
banana'
,'
cher
ry'
)
Empt
yandSi
ngl
etont
upl
es:
Sy
ntaxf
orEmpt
ytupl
e:

empt
y=( )
Whentupl
ehav
enotanysi
ngl
eval
ue,
theni
twi
l
lcal
l
edasEmpt
ytupl
e.

Sy
ntaxf
orSi
ngl
etont
upl
e:

Singleton=1,
*Whent upl
ehaveonl
ysi
ngleval
uet
heni
twil
lcal
l
edassi
ngl
etont
upl
e.
*Singletontupl
eal
waysendswit
hcomma.

Nest
edTupl
es:
I
fwehav
eat
upl
e,wemakei
tpar
tofanot
hert
upl
e.

Exampl e:
course=‘ python’
,‘AimanSi r
’,302
student=‘ Shani’
,‘1848530009’ ,cour
se
print
(course)o/ p=>‘ python’,‘AimanSir
’,302
print
(student) o/p=>‘Shani’,‘1848530009’,‘
pyt
hon’
,‘Ai
manSi
r’
,302

Set
Asetisacol
l
ect
ionwhi
chi
sunor
der
edanduni
ndexed.I
nPy
thonset
sar
ewr
it
tenwi
thcur
ly
br
ackets.

Ex
ampl
e
Cr
eat
eaSet
:

thi
sset={"
appl
e",
 
"banana"

"cher
ry"
}
pri
nt(
thi
sset
)

{
"appl
e",
 
"banana"

"cher
ry"
}

AccessI
tems
Youcannotaccessit
emsi
nasetbyr
efer
ri
ngt
oani
ndex
,si
nceset
sar
eunor
der
edt
he
i
temshasnoi ndex.

Buty
oucanl
oopt
hroughtheseti
temsusi
nga 
f  
orl
oop,
oraski
faspeci
fi
edv
aluei
spr
esent
i
naset,
byusi
ngt
he n 
i key
word.

Ex
ampl
e
Loopt
hrought
heset
,andpr
intt
hev
alues:

t
hisset={
"appl
e",
 
"banana"

"cher
ry"
}

f
or 
x i
n t
hisset
:
 
 pr
int
(x)

out
put
:

cherry
appl
e
banana

ChangeI
tems
Onceaseti
scr
eat
ed,
youcannotchangei
tsi
tems,
buty
oucanaddnewi
tems.

Gett
heLengt
hofaSet
Todet
ermi
nehowmanyi
temsasethas,
uset
he 
l
en(

met
hod.

Ex
ampl
e
Gett
henumberofi
temsi
naset
:

t
hisset={
"appl
e",
 
"banana"

"cher
ry"
}

pr
int
(l
en(
thi
sset
))

out
put
:3
Theset
()Const
ruct
or
I
tisal
sopossi
blet
ouset set
he  () 
const
ruct
ort
omakeaset
.

Ex
ampl
e
Usi
ngt
heset
()const
ruct
ort
omakeaset
:

thi
sset=set
(("
appl
e",
 
"banana"

"cher
ry"
)) 
#not
ethedoubl
eround-
bracket
s
pri
nt(
thi
sset
)

out
put
:("
appl
e",
 
"banana"

"cher
ry"
)

SetMet
hods:

i
> l
en(

met
hod
Todetermi
nehowmanyel
ement
sinasetweusel
en(

met
hod.
Example1:

t
hisset={
"appl
e",
 
"banana"

"cher
ry"
}

pr
int
(l
en(
thi
sset
))o/
p=>3

i
i
> r
emov
e()
 met
hod:
Toremov
eani
tem i
naset
,weuset r
he emov
e()f
unct
ion.
Exampl
e:

a={
"appl
e",
 
"banana"

"cher
ry"
}

a.
remov
e("
banana"
)

pr
int(
a) o/p=>{"appl
e",
"cher
ry"}
Note: 
Ift
heitem t
oremovedoesnotexi
str
,
 emov
e()
 wi
l
lrai
seaner
ror
.
i
i
i> di
scar
d()
 met
hod
Toremoveanitem i
naset,
weuset di
he  scar
d()f
unct
ion.
Example:
st
udent={"v
ikr
am", 
"Ay
azur
",
 "
Akash"}

st
udent
.di
scar
d("
vikr
am"
)

pr
int
(st
udent
) o/
p=>{
"Ay
azur
",
 "
Akash"
}

Not
e:*
Ift
hei
tem t
oremov
edoesnotexi
stdi
,
  scar
d()
 wi
l

NOT 
rai
seaner
ror
.

Di
cti
onar
y
Adict
ionar
yisacol
lect
ionwhichisunorder
ed,changeableandindexed.I
nPyt
hon
di
cti
onari
esarewri
tt
enwithcurl
ybrackets,
andtheyhav ekeysandv al
ues.

Ex
ampl
e
Cr
eat
eandpr
intadi
cti
onar
y:

thi
sdi
ct= {
"br
and"

"For
d",
"model
":
 "
Must
ang"
,"
year
":
 1964}
pri
nt(
thi
sdi
ct)

out
put
:{'
brand'
:'
For
d',
'model
'
:'Must
ang'
,'
year
':
1964}

Accessi
ngI
tems
Youcanaccesst
hei
temsofadi
cti
onar
ybyr
efer
ri
ngt
oit
skeyname,
insi
desquar
e
bracket
s:

Ex
ampl
e
Gett
hev
alueoft
he"
model
"key
:

x=t
hisdi
ct[
"model
"]

out
put
:Must
ang
Ther
eisal
soamet
hodcal
l get
ed  () 
thatwi
l
lgi
vey
out
hesamer
esul
t:

Ex
ampl
e
Gett
hev
alueoft
he"
model
"key
:

x=t
hisdi
ct.
get
("
model
")

out
put
:Must
ang

ChangeVal
ues
Youcanchanget
hev
alueofaspeci
fi
cit
em byr
efer
ri
ngt
oit
skeyname:

Ex
ampl
e
Changet
he"
year
"to2018:

t
hisdi
ct= {"br
and"

"For
d",
"model
":
 "
Must
ang"
,"y
ear
":
 1964}
t
hisdi
ct[
"year"
]= 
2018

pr
int
(thi
sdi
ct)

out
put
:{'
brand'
:'
For
d',
'model
'
:'Must
ang'
,'
year
':
2018}

LoopThr
oughaDi
cti
onar
y
Youcanl
oopt
hroughadi
cti
onar
ybyusi
nga 
f  
orl
oop.

Whenl
oopingthr
oughadicti
onar
y,t
her
etur
nval
uear
et key
he  s oft
hedi
cti
onar
y,butt
her
e
ar
emethodstoretur
nt v
he al
ues 
aswel
l
.

Ex
ampl
e
t
hisdi
ct= {
 
 "
brand"

"For
d",
 
 "
model":
 "
Mustang"
,
 
 "
year"

1964
}
Pr
intal
lkeynamesi
nthedi
cti
onar
y,onebyone:

f
or 
x i
n t
hisdi
ct:
 
 pr
int
(x)

out
put
:

brand
model
year

Ex
ampl
e
Pr
intal
l
 val
ues 
i
nthedi
cti
onar
y,onebyone:

f
or 
x i
n thisdict
:
 
 pr
int
(thisdict[
x])

out
put
:

Ford
Mustang
1964

Di
cti
onar
yLengt
h
Todet
ermi
nehowmanyi
tems(
key
-val
uepai
rs)adi
cti
onar
yhas,
uset
he 
l
en(

met
hod.

Ex
ampl
e
Pr
intt
henumberofi
temsi
nthedi
cti
onar
y:

pr
int
(l
en(
thi
sdi
ct)
)

Thedi
ct(
)Const
ruct
or
I
tisal
sopossi
blet
ouset di
he  ct
() 
const
ruct
ort
omakeanewdi
cti
onar
y:
Ex
ampl
e
thi
sdi
ct=dict(
brand="
Ford"
, model
="Mustang"
,year=1964)
#notethatkeywordsarenotstr
ingl
it
eral
s
#notetheuseofequalsrathert
hancolonfortheassignment
pri
nt(
thi
sdi
ct)

out
put
:{'
brand'
:'
For
d',
'model
'
:'Must
ang'
,'
year
':
1964}

Met
hodsofDi
cti
onar
y:
i
> Pop(
)met
hod:
Thismet hodisusedtodel
etetheelement
soft
hedi
cti
onar
yfr
om anykeyv
alue.
Example-1
a={'name':'
raj
',
'r
oll
no'
:
101,
'sub'
:'
pyt
hon'
}
pri
nt(a)
a.
pop( '
rol
lno')
pri
nt(a)

output
=>
{'
name':
'r
aj'
,'
rol
lno'
:101,'
sub'
:
'py
thon'
}
{'
name':
'r
aj'
,'
sub':
'
py t
hon'
}

i
i>Del
eteDi
cti
onar
yEl
ement
s
Youcaneit
herremov
eindi
vi
dualdi
cti
onaryel
ementsorcl
eartheent
ir
econt
ent
sofa
di
cti
onar
y.Youcanal
sodel
eteent
ir
edict
ionar
yinasi
ngl
eoperati
on.
Toexpl
ici
tl
yremov
eanent
ir
edi
cti
onar
y,j
ustuset
he 
del
 
stat
ement
.Fol
l
owi
ngi
sa
si
mpleexampl
e
di
ct={ '
Name':
'Zara'
,'
Age':7,'
Class':
'Fir
st'
}
pri
nt(dict) #{ '
Name':'
Zar a'
,'
Age':7,'
Class'
:'
Fi
rst
'
}
deldict['
Name'
]#r emoveent rywithkey'Name'
pri
nt(dict) #{'Age':7,'
Class':'
Fi
rst'
}
di
ct.clear(
) #r emov eal
lentriesindict
pri
nt(dict) #{ }
deldict #deleteent
ir
edi cti
onary
Out
put
:
{'
Name'
:'
Zar
a','
Age':7,'
Class'
:'
Fi
rst
'}
{'
Age'
:7,
'Cl
ass'
:'Fi
rst'
}
{}

Py
thon 
Lambda
Al
ambdaf
unct
ioni
sasmal
lanony
mousf
unct
ion.

Alambdafunct
ioncant
akeanynumberofar
gument
s,butcanonl
yhav
eone
expr
essi
on.

Sy
ntax: lambda arguments : expression
Theexpr
essi
oni
sexecut
edandt
her
esul
tisr
etur
ned:

Ex
ampl
e
Alambdaf
unct
iont
hatadds10t
othenumberpassedi
nasanar
gument
,andpr
intt
he
r
esult
:

x= l
ambda a:
a+ 
10
pr
int
(x(
5))

out
put
:15

Lambdaf
unct
ionscant
akeanynumberofar
gument
s:

Ex
ampl
e
Al
ambdaf
unct
iont
hatmul
ti
pli
esar
gumentawi
thar
gumentbandpr
intt
her
esul
t:
x= l
ambda a,
b:a*b
pr
int
(x(
5, 
6))

out
put
:30
UNI
T4
Fi
l
eHandl
i
ng
Py
thonhassev
eralf
unct
ionsf
orcr
eat
ing,
readi
ng,
updat
ing,
anddel
eti
ngf
il
es.

Fi
l
eHandl
i
ng
Thekeyf
unct
ionf
orwor
kingwi
thf
il
esi
nPy
thoni
sthe 
open(

funct
ion.

The 
open(

funct
iont
akest
wopar
amet
er f
s;
 il
ename, mode.
and 

Ther
ear
efourdi
ff
erentmet
hods(
modes)f
oropeni
ngaf
il
e:

"

"-Read-Def
aul
tval
ue.Opensaf
il
eforr
eadi
ng,
err
ori
fthef
il
edoesnotex
ist

"
a" 
-Append-Opensaf
il
eforappendi
ng,
creat
est
hef
il
eifi
tdoesnotexi
st

"
w" 
-Wr
it
e-Opensaf
il
eforwr
it
ing,
creat
est
hef
il
eifi
tdoesnotexi
st

"
x" 
-Cr
eat
e-Cr
eat
est
hespeci
fi
edf
il
e,r
etur
nsaner
rori
fthef
il
eexi
sts

I
naddi
ti
ony
oucanspeci
fyi
fthef
il
eshoul
dbehandl
edasbi
nar
yort
extmode

"

"-Text-Def
aul
tval
ue.Textmode

"
b" 
-Bi
nar
y-Bi
nar
ymode(
e.g.i
mages)

Sy
ntax
Toopenaf
il
eforr
eadi
ngi
tisenought
ospeci
fyt
henameoft
hef
il
e:

f= 
open(
"demof
il
e.t
xt"
)

OpenaFi
l
eont
heSer
ver
Assumewehav
ethef
oll
owi
ngf
il
e,l
ocat
edi
nthesamef
olderasPy
thon:
demof
il
e.t
xt

Hel
lo!Welcometodemofi
le.
txt
Thi
sfil
eisfort
esti
ngpur
poses.
GoodLuck!

Toopent
hef
il
e,uset
hebui
l
t-i
n open(

funct
ion.

The 
open(

funct
ionr
etur
nsaf
il
eobj
ect
,whi
chhasa 
read(

met
hodf
orr
eadi
ngt
hecont
entof
thef
il
e:

Ex
ampl
e
f= open(
"demof
il
e.t
xt"

"r
")
pri
nt(f
.r
ead()
)

out
put
:

Hel
lo!Welcometodemofi
le.
txt
Thi
sfil
eisfort
esti
ngpur
poses.
GoodLuck!

ReadOnl
yPar
tsoft
heFi
l
e
Bydefaul
tthe 
read(

met
hodret
urnst
hewhol
etext
,buty
oucanal
sospeci
fyhowmany
char
acter
sy ouwanttor
etur
n:

Ex
ampl
e
Ret
urnt
he5f
ir
stchar
act
ersoft
hef
il
e:

f= open(
"demofi
l
e.t
xt"

"r
")
pri
nt(f
.r
ead(5)
)

out
put
:

Hel
l
o
ReadLi
nes
Youcanr
etur
nonel
i
nebyusi
ngt
he 
readl
i
ne(

met
hod:

Ex
ampl
e
Readonel
i
neoft
hef
il
e:

f= open(
"demofi
le.
txt
",
 "
r"
)
pri
nt(f
.r
eadli
ne(
))

out
put
:

Hel
l
o!Wel
comet
odemof
il
e.t
xt

Byl
oopi
ngt
hrought
hel
i
nesoft
hef
il
e,y
oucanr
eadt
hewhol
efi
l
e,l
i
nebyl
i
ne:

Ex
ampl
e
Loopt
hrought
hef
il
eli
nebyl
i
ne:

f= 
open("demof
il
e.t
xt"

"r
")
for
 x 
i
n f:
 
 pr
int(
x)

out
put
:

Hel
lo!Welcometodemofi
le.
txt
Thi
sfil
eisfort
esti
ngpur
poses.
GoodLuck!

Cl
oseFi
l
es
I
tisagoodpr
act
icet
oal
way
scl
oset
hef
il
ewheny
ouar
edonewi
thi
t.

Ex
ampl
e
Cl
oset
hef
il
ewheny
ouar
efi
nishwi
thi
t:

f= open(
"demofi
le.
txt
",
 "
r"
)
pri
nt(f
.r
eadli
ne(
))
f.
close(
)
Wr
it
etoanExi
sti
ngFi
l
e
Towr
it
etoanexi
sti
ngf
il
e,y
oumustaddapar
amet
ert
othe 
open(

funct
ion:

"
a" 
-Append-wi
l
lappendt
otheendoft
hef
il
e

"
w" 
-Wr
it
e-wi
l
lov
erwr
it
eanyex
ist
ingcont
ent

Ex
ampl
e
Opent
hef
il
e"demof
il
e2.
txt
"andappendcont
entt
othef
il
e:

f= open("
demofi
l
e2.txt
",
 "
a")
f.
wr i
te(
"Nowthefi
lehasmor econt
ent
!"
)
f.
close()

#openandr eadt
hef
ileaftert
heappendi
ng:
f= open(
"demofi
l
e2.
txt"

"r
")
pri
nt(f
.r
ead())

out
put
:

Hel
lo!Welcometodemofi
le2.
txt
Thi
sfil
eisfort
esti
ngpur
poses.
GoodLuck!Nowthefi
l
ehasmor econt
ent
!

Ex
ampl
e
Opent
hef
il
e"demof
il
e3.
txt
"andov
erwr
it
ethecont
ent
:

f= open("
demofil
e3.
txt
",
 "
w")
f.
wr i
te(
"Woops!Ihav
edeletedt
hecont
ent
!"
)
f.
close()

#openandr eadt
hef
ileaftert
heappendi
ng:
f= open(
"demofi
l
e3.
txt"

"r
")
pri
nt(f
.r
ead())

out
put
:
Woops!Ihav
edel
etedt
hecont
ent
!

Del
eteaFi
l
e
Todel
eteaf
il
e,y
oumusti
mpor
ttheOSmodul
e,andr
uni
ts 
os.
remov
e( 
)funct
ion:

Ex
ampl
e
Remov
ethef
il
e"demof
il
e.t
xt"
:

i
mport 
os
os.
remove(
"demof
il
e.t
xt"
)

Checki
fFi
l
eexi
st:
Toav
oidget
ti
nganer
ror
,youmi
ghtwantt
ochecki
fthef
il
eexi
stsbef
orey
out
ryt
odel
etei
t:

Ex
ampl
e
Checki
ffi
l
eexi
st t
s,
 hen 
del
etei
t:

i
mpor t
 os
i
f os.path.
exi
sts(
"demofi
le.
txt
"):
 os.remove("
demof i
l
e.t
xt")
else:
  
print(
"Thefi
l
edoesnotexi st
")

Del
eteFol
der
Todel
eteanent
ir
efol
der
,uset
he 
os.
rmdi
r(

met
hod:

Ex
ampl
e
Remov
ethef
older"
myf
older
":

i
mport 
os
os.
rmdi
r("
myf
older
")
Except
ionHandl
ing
Whenanerroroccur
s,orex
cept
ionaswecal
li
t,Py
thonwi
l
lnor
mal
l
yst
opandgener
atean
er
rormessage.

Theseexcept
ionscanbehandl
edusi
ngt f
he ol
l
owi
ngbl
ock:

t
The r
y bl
ockl
etsy
out
establ
ockofcodef
orer
ror
s.

except
The   bl
ockl
etsy
ouhandl
etheer
ror
.

f
The i
nall

blockl
etsy
ouexecut
ecode,
regar
dlessoft
her
esul
toft
het
ry-andexcept
bl
ocks.

Ex
ampl
e
The 
tr
y bl
ockwi
l
lgener
ateanexcept
ion,
because 

isnotdef
ined:

tr
y:
 
 pri
nt(
x)
except
:
 
 pri
nt(
"Anexcept
ionoccur
red"
)

out
put
:Anexcept
ionoccur
red

Si
ncet
het
rybl
ockr
aisesaner
ror
,theexceptbl
ockwi
l
lbeexecut
ed.

Wi
thoutt
het
rybl
ock,
thepr
ogr
am wi
l
lcr
ashandr
aiseaner
ror
:

ManyExcept
ions
Youcandefi
neasmanyexcepti
onbl
ocksasy
ouwant
,e.
g.i
fyouwantt
oexecut
easpeci
al
bl
ockofcodeforaspeci
alki
ndofer
ror
:
Ex
ampl
e
Pr
intonemessagei
fthet
rybl
ockr
ai NameEr
sesa  ror
 andanot
herf
orot
herer
ror
s:

tr
y:
 
 pri
nt(
x)
except
 NameError
:
 
 pri
nt(
"Var
iabl
exisnotdefi
ned")
except
:
 
 pri
nt(
"Somethi
ngelsewentwrong"
)

Out
put
:Var
iabl
exi
snotdef
ined

El
se
Youcanuset
he se 
el key
wor
dtodef
ineabl
ockofcodet
obeexecut
edi
fnoer
ror
swer
e
rai
sed:

Ex
ampl
e
I
nthi
sex
ampl
e,t
he 
tr
y bl
ockdoesnotgener
ateanyer
ror
:

tr
y:
 
 pri
nt(
"Hel
lo"
)
except
:
 
 pri
nt(
"Somethi
ngwentwrong"
)
el
se:
 
 pri
nt(
"Nothi
ngwentwrong"
)

out
put
:

Hel
l
o
Not
hingwentwr
ong

Fi
nal
l
y
The 
fi
nal
l
y bl
ock,
ifspeci
fi
ed,
wil
lbeexecut
edr
egar
dlessi
fthet
rybl
ockr
aisesaner
roror
not.

Ex
ampl
e
t
ry:
 
 pri
nt(
x)
except:
 
 pri
nt(
"Somet
hingwentwr
ong")
fi
nall
y:
 
 pri
nt(
"The'
tr
yexcept
'i
sfi
nished"
)

Somet
hingwentwr
ong
The'
tr
yexcept
'i
sfi
nished

Rai
seanexcept
ion
AsaPy
thondev
elopery
oucanchooset
othr
owanexcept
ioni
facondi
ti
onoccur
s.

Tot
hrow(
orr
aise)anexcept
ion,
uset
he 
r se 
ai key
wor
d.

Ex
ampl
e
Rai
seaner
rorandst
opt
hepr
ogr
am i
fxi
slowert
han0:

x=-
1

i

x< 0:
 
 r
aise 
Except
ion(
"Sor
ry,
nonumber
sbel
owzer
o")

out
put
:

Traceback(mostrecentcal l
last)
:
 
 Fil
e"demo_ref
_key word_rai
se.py"
,li
ne4,i
n<modul
e>
 
  
 rai
seExcepti
on("Sorr
y ,
nonumber sbel
owzer
o")
Excepti
on:Sorr
y,nonumber sbelowzero

Ex
ampl
e
Rai
seaTy
peEr
rori
fxi
snotani
nteger
:

x= 
"hel
l
o"

i

not t
ype(
x)i
s i
nt:
 
 r
aise 
TypeEr
ror
("Onl
yint
eger
sar
eal
l
owed"
)

out
put
:

Tr
aceback(
mostr
ecentcal
ll
ast
):
 
 Fi
le"demo_ref_key word_r
aise2.
py",
li
ne4,in<modul
e>
 
  
 r
aiseTypeError("Onlyint
egersareall
owed")
TypeErr
or:Onlyintegersareallowed

Whati
saModul
e?
Consi
deramodul
etobet
hesameasacodel
i
brar
y.

Af
il
econt
aini
ngasetoff
unct
ionsy
ouwantt
oincl
udei
nyourappl
i
cat
ion.

Cr
eat
eaModul
e
Tocr
eat
eamodul
ejustsav
ethecodey
ouwanti
naf
il
ewi
tht
hef
il
eext
ensi
on 
.
py:

Ex
ampl
e
Sav
ethi
scodei
naf
il
enamed 
mymodul
e.py

def
 gr
eeti
ng(name):
 
 pr
int
("
Hell
o," +name)

UseaModul
e
Nowwecanuset
hemodul
ewej
ustcr
eat
ed,
byusi
ngt
he 
i
mpor

stat
ement
:

Ex
ampl
e
I
mpor
tthemodul
enamedmy
modul
e,andcal
lthegr
eet
ingf
unct
ion:

i
mport
 my modul
e
mymodule.
greet
ing(
"Jonat
han"
)
Hel
l
o,Jonathan
Cl
ass
I
tisthegener
atorofobj
ects.
Or
I
tisthebl
uepri
ntofanobject
s.
Or
“cl
assisthecoll
ect
ionofdatamemberandmet
hod”
Sy
ntax:
cl
asscl
assname:
vari
ables(
datamember )
..
funct
ions(methods)
..

e.
g

cl
assc1:
deffun(
sel
f):
pri
nt(“
Hel
lo”)

Cr
eat
eObj
ect
Nowwecanuset
hecl
assnamedmy
Classt
ocr
eat
eobj
ect
s:

Ex
ampl
e
Ob=c1(
)

Ob.
fun(
)
Out
put
:hel
l
o

The_
_ini
t__
()Funct
ion/
Const
ruct
or
Iti
sthespecial
met hodsofaclasswhichis
automat
ical
lycall
edwhent heobjectofacl
assi
s
creat
ed.

Ex
ampl
e
Cr
eat
eacl
assnamedPer
son,
uset
he_
_ini
t__
()f
unct
iont
oassi
gnv
aluesf
ornameandage:

class 
Person:
 
 def _
_ini
t__
(sel
f,name,
age)
:
 
   
self
.name=name
 
  self
.age=age

p1=Per
son(
"John"

36)

pr
int
(p1.
name)
pr
int
(p1.
age)

out
put
:

John
36

Concept
sofOOPS

o Encapsul at
ion
o Abstraction
o I
nheritance
o Polymor phi
sm
Encapsul
ati
on:

Combiningthevari
abl
esandmet
hodsi
nacl
assi
sthe
conceptofencapsul
ati
on.

e.
g.

cl
asscir
cle:
defarea(
sel
f,
r)
:
a=3.14*
r*r

pri
nt(
a)
defci
rcum(sl
f,
r)
:
cf=2*3.
14*r
pri
nt(
cf)

Abst
ract
ion:

Inf
ormati
onhidingandreducingthecomplexi
tyist
he
conceptofabstr
acti
on.
Publicmethods:Pr
ivat
emet hodsinpythoncanbe
cal
ledoutsi
deofclassbyclassobject
.Allmethodsi
n
pythonarepubli
cbydefaul
t.

e.
g.

cl
assc1:
deffun(
sel
f)
:
pr
int
(“Hel
l
o”)

ob=c1(
)
ob.
fun(
)

Privatt
emethods:Publ
icmethodsinpythoncannotbe
call
edoutsi
deofclassbyclassobj
ect.Allmet
hods
starti
ngwit
hdoubleunder
score(__
)inpy t
honare
priv
ate.

e.
g.

cl
assc1:
def__
fun(
self
):
pri
nt(
“Hel
lo”
)

ob=c1()
ob.
__fun(
)

Note:abov
efunct
ioncan’
tbecal
l
edbecausei
tis
pr
ivat
e.

I
nher
it
ance:
Usingthefeat
uresofoneclassi
ntoanot
hercl
assi
s
theconceptofinher
it
ance.
Ty
pesofi
nheri
tance:
2. Si
ngleLevelInhrit
ance
3. Mult
iLevelInherit
ance
4. Hi
erarchi
calInherii
tance
5. Mult
ipleI
nheritance

SingleLev
elInhr
it
ance:InSi
ngl
eLevelI
nher
it
anceone
baseclasscanhaveonlyoneder
ivedcl
assandvi
se-
versa.
Cl
assC1 BaseClass/SuperCl
ass/
Par
ent
Class

Der
ivedCl
ass/SubCl
ass/
Chi
l
d
Cl
assC2
Cl
ass

Sy
ntax,

Cl
assc1:
Funct
ions…

Cl
assc2(c1):
Funct
ions…
Note:
allpubl
icfunct
ionofc1cl
asswillbei
nher
it
ed
i
ntoclassc2.
Note:
Pr i
vat
efuncti
ondoesnotinher
it
.

e.
g.

cl
assc1:
deffun(sel
f):
pr
int
(“Hell
o”)
def__f
un1(self
):
pr
int
(“Hi”
)

cl
assc2(
c1):
deff
un2(sel
f):
pri
nt(
“good”)

ob=c2(
)
ob.
fun() #itwil
lpr
intHell
o
ob.
fun2() #i
twil
lpr
intgood
ob.
fun1() #Er
ror
,Becausenoti
nher
it
edi
nc2

MultiLevelI
nhrit
ance:InMult
iLevelI
nheri
tanceone
baseclasscanhav eonlyonederi
vedclassandv i
se-
ver
sabutader iedcalsscanal
sobeabasecl assof
anot
herder i
vedclass.
Cl
assC1 BaseCl
assfc2
Deri
vedCl
assofC1andBasecl
ass
Cl
assC2
ofC3

Cl
assC3 Der
ivedCl
assofc2

Sy
ntax,

Cl
assc1:
Funct
ions…

Cl
assc2(c1):
Funct
ions…

Cl
assc3(c2):
Funct
ions…

Note:
allpubl
icfunct
ionofc1cl
asswillbei
nher
it
ed
i
ntoclassc2.
Note:
Pr i
vat
efuncti
ondoesnotinher
it
.

e.
g.
cl
assc1:
deffun(sel
f):
pr
int
(“Hell
o”)
def__f
un1(self
):
pr
int
(“Hi”
)

cl
assc2(
c1):
deff
un2(sel
f):
pri
nt(
“good”)

cl
assc3(
c2):
deff
un3(sel
f)
:
pri
nt(
“Welcome”
)

ob=c3(
)
ob.
fun() #itwil
lpr
intHell
o
ob.
fun2() #i
twil
lpr
intgood
ob.
fun1() #Er
ror
,Becausenoti
nher
it
edi
nc2
ob.
fun3() #i
twil
lpr
intwelcome

Hier
archicalI
nhr
it
ance:I
nHierar
chi
cal
Inheri
tanceone
baseclasscanhavemorethanoneder
ivedclassbuta
deri
vedclasscanhaveonl
yonebaseclass.
Cl
assC1 BaseCl
assfc2
Cl
assC2 Cl
assC3

Sy
ntax,

Cl
assc1:
Funct
ions…

Cl
assc2(c1):
Funct
ions…

Cl
assc3(c1):
Funct
ions…

Note:
allpubl
icfunct
ionofc1cl
asswillbei
nher
it
ed
i
ntoclassc2.
Note:
Pr i
vat
efuncti
ondoesnotinher
it
.

e.
g.

cl
assc1:
deffun(sel
f):
pr
int
(“Hell
o”)
def__f
un1(self
):
pr
int
(“Hi”
)

cl
assc2(
c1):
deff
un2(sel
f):
pri
nt(
“good”)

cl
assc3(
c1):
deff
un3(sel
f)
:
pri
nt(
“Welcome”
)

ob=c3(
)
ob.
fun() #itwil
lpr
intHel
lo
ob.
fun1() #Er
ror
,Becausenoti
nher
it
edi
nc3
ob.
fun3() #i
twil
lpr
intwelcome

Mult
ipl
eInhr
it
ance:I
nMulti
pleI
nher
it
anceader
ived
cl
asscanhavemorethanonebasecl
ass.

Cl
assC1 Cl
assC2

BaseCl
assfc2
Cl
assC3
Sy
ntax,

Cl
assc1:
Funct
ions…

Cl
assc2:
Funct
ions…

Cl
assc3(c1,
c2):
Funct
ions…

Note:
allpubl
icfunct
ionofc1cl
asswillbei
nher
it
ed
i
ntoclassc2.
Note:
Pr i
vat
efuncti
ondoesnotinher
it
.

e.
g.

cl
assc1:
deffun(sel
f):
pr
int
(“Hell
o”)
def__f
un1(self
):
pr
int
(“Hi”
)
cl
assc2:
deff
un2(sel
f):
pri
nt(
“good”)

cl
assc3(
c1,c2):
deff
un3(self
):
pri
nt(“
Welcome”
)

ob=c3(
)
ob.
fun() #itwil
lpr
intHell
o
ob.
fun1() #Er
ror
,Becausenoti
nher
it
edi
nc3
ob.
fun2() #i
twil
lpr
intgood
ob.
fun3() #i
twil
lpr
intwelcome

Pol
ymor
phi
sm:
Functi
onoverl
oadi
ngandf
unct
ionov
err
idi
ngi
sthe
conceptofpol
ymorphi
sm.

Functi
onover
loadi
ng:f
unct
ionov
erl
oadi
ngmeansone
funct
ionwi
thdif
fer
entf
orm.

e.
g.

cl
assc1:
defadd(self
,a=0,b=0,c=0,
d=0)
:
pri
nt(
a+b+c+d)
ob=c1(
)
ob.
add(2,4)#itwi l
lprint6
ob.
add(2,3,
6)#itwi l
lprinit11
ob.
add(1,4,
5,
2)#i twillpri
nit12

Functi
onov err
idi
ng:
Re-defi
ningthefunct
ionofbasecl
assintoder
ived
cl
assistheconceptoffuncti
onover
ri
ding.

e.
g.

cl
assc1:
deff
un(sel
f)
:
pri
nt(
“Hel
lo”)
cl
assc2(
c1):
deff
un(sel
f)
:
pri
nt(
“Welcome”
)

ob=c2(
)
ob.
fun(
)#i
twi
l
lpr
intWel
come

Note:itwil
lpr
intWel
comenotHel
l
obecauseof
overr
iding.
UNI
T5

TOWEROFHANOI
I
tisagamepr obl
em.Ther ewi
ll
bethr
ee
di
ffer
entsi
zeddisks.Eachdi
skhasahol
e
i
nthecanter
.
Sothatitcanbest
ackedonanyoft
hepegs.
Call
threepegsasx,z,
y.Att
hebegi
nni
ngof
thegame
,thediskarestackedont
hexpeg,
thatis
thelargestsi
zeddiskont
hebot
tom andthe
smal l
est
Si
zedi
skont
op.

Rul
efort
hegame:
-
Transf
err
ingthedi
sksfr
om t
hesourcepeg
tothedesti
nati
onpegsucht
hatatanypoi
nt
of
Tr
ansfor
mati
onnolar
gersi
zedi
ski
spl
aced
onthesmal
l
erone.
Onl
yonedi
skmaybemov
edatat
ime
Eachdiskmustbest
ackedonanyoneof
thepegs.

I
ll
ust
rat
ion:
-

Letusseehowthet
owerofHanoi probl
em
i
ssolvedusi
ngr
ecur
sion.Consi
dertheno.
ofdi
skis
Thr
eet
her
ear
esev
enmov
esi
ntr
ansf
err
ing
t
herethr
eedi
sksf
rom xpegt
oxpeg,
wi
thout
Viol
ati
nganyofthethreecondi
ti
ons
speci
fi
edabove.Forthesakeofsimpl
i
cit
y,
l
etusdenote
Thedi
sksasdi
sk1,
disk2,
disk3.

Mov
edi
sk1f
rom t
hexpegt
othezpeg
Mov
edi
sk2f
rom t
hexpegt
otheypeg
Mov
edi
sk1f
rom t
hezpegt
otheypeg
Mov
edi
sk3f
rom t
hexpegt
othezpeg
Mov
edi
sk1f
rom t
heypegt
othexpeg
Mov
edi
sk2f
rom t
hezpegt
otheypeg
Mov
edi
sk1f
rom t
hexpegt
othezpeg
Pr
ogr
am:
defTowerOfHanoi(n,from_ r
od, t
o_ r
od,aux_rod)
:
 
  
 i
fn==1:
 
  
  
  
 pri
nt"Movedisk1f rom rod",
from_ r
od,"
torod",
to_
rod
 
  
  
  
 ret
urn
 
  
 TowerOfHanoi(
n-1,fr
om_ rod,aux_ r
od,to_r
od)
 
  
 pri
nt"Movedisk",
n,
"fr
om r od",
from_ r
od,"
torod",
to_r
od
 
  
 TowerOfHanoi(
n-1,aux_rod,to_rod,fr
om_ r
od)
SEARCHI
NGANDHASHI
NG

Sear
chi
ng:
-
Sear
chi
ngisatechniquesoff
indi
ngan
el
ementinagi
venlistofel
ements.Li
st
of
El
ementcoul
dber
epr
esent
edusi
ngan:
Li
st
Tupl
e
Set
Di
cti
onar
y
Ty
pesofsear
chi
ng:
-

Li
nearSear
chi
ng(
Sequent
ial
Sear
chi
ng)
Bi
nar
ySear
chi
ng

Li
nearSearch(Si
mpleSear
ch):
-Inl
inear
search,
weaccesseachelementonebyone
sequenti
all
yandseewhether
Iti
sdesiredel
ementornot.Asear
chwi
l
lbe
unsuccessful
ifallt
heel
ementsar
e
accessedandt he
Desi
redel
ementi
snotf
ound.
Pr
ogr
am:
-
a={
}
f
ori
inr
ange(
0,8)
:
a[
i]
=ev
al(
input
("
Ent
erno.
")
)
no=ev
al(
input
("
Ent
erno.t
osear
ch:
")
)
f
ori
inr
ange(
0,8)
:
i
fa[
i]
==no:
f
lag=1
br
eak
i
ffl
ag==1:
pr
int
("
no.i
sav
ail
abl
einl
i
st"
)
el
se:
pr
int
("
no.i
snotav
ail
abl
einl
i
st"
)
BinarySearch:
-Binar
ysear
chi
sa
techniquesofsear
chi
ngdatai
nsor
tedl
i
st.
Thistechnique
Sear
chesthedat
ainmi
nimum possi
ble
compari
sons.
Thelogi
cbehi
ndt
hist
echni
quei
sgi
ven
bel
ow:

Fi
rstf
indt
hemi
ddl
eel
ement
soft
hear
ray
Compar
ethemid((f
ir
st+last)
/2)el
ement
wit
hanit
em(ei
therl
eftorri
ght)
Ther
ear
ethr
eecase-
Ifi
tisdesi
redel
ementt
hensear
chi
s
successf
ul.
Ifi
tislessthandesir
edelementsthen
searchonlythefi
rsthal
fofthearr
ay.
Ifi
tisgr
eatert
hanthedesi
redel
ement
searchi
nthesecondhal
fofthearr
ay.
Repeatthesamest
epsunt
ilsear
chi
s
compete.
Pr
ogr
am:
-
a={
}
e=7
s=0
pr
int
(“Ent
erany8el
ement
s:”
)
f
ori
inr
ange(
0,8)
:
a[
i]
=ev
al(
input
("
Ent
erNo.
")
)
no=ev
al(
input
("
Ent
erno.t
osear
ch:
")
)
c=(
s+e)
//2
whi
l
ea[
c]!
=noands<=e:
i
fno>a[
c]:
s=c+1
el
se:
e=c-
1
c=(
s+e)
//2

i
fs<=e:
pr
int
("
noi
sfoundi
nli
st"
)
el
se:
pr
int
("
noi
snotf
oundi
nthel
i
st"
)

SORTI
NG
Sor
ti
ngi
satechniqueofar
rangingdat
ain
somegi
vensequencei.
e.i
ncreasi
ngorder
or
decr
easingorder
.Sor
ti
ngcanbedi
vi
dedi
n
twocategor
ies.

I
nter
nal
Sor
ti
ng
Ext
ernal
Sor
ti
ng

I
nter
nalSor
ti
ng:
-Int
ernal
sorti
ngt
akes
pl
aceinmainmemoryofthecomput
er.I
n
i
nter
nal
Sor
ti
ngwear
ranget
hedat
ainar
ray
.

2.Exter
nal
Sor
ti
ng:
-External
sorti
ngisthe
sort
ingoft
henumber
sfrom theexter
nal
fi
leby
r
eadi
ngi
tfr
om secondar
ymemor
y.Weuse
ext
ernalsor
ti
ngift
henumber
sofdat
atobe
sor
tedistoolar
ge.
Sel
ecti
onSort:
-Sel
ect
ionsor
tisaver
y
si
mplesort
ingmethod.I
nsel
ecti
onsortwe
l
ocate
Minimum v
alueandplacei
ttof
istposi
ti
on
ofthear
ray.Si
mil
arl
ywef i
ndnext
minimum
Val
ueandplacei
tto2ndposi
ti
onoft
he
ar
rayandsoon.

Pr
obl
em:-Sortt
heelementgi
venbel
ow
wi
tht
hehelpofsel
ecti
onsort
.

10615213114
I
ter
ati
on1:
(0t
o6)

10615213114(
swappi
ngof10and6i
s
needed)

61015213114(
Noswappi
ng)

61015213114(
Swappi
ngof6and2
i
sneeded)

21015613114(
Noswappi
ng)

21015613114(
Swappi
ngof2and1i
s
needed)
11015613214(
Noswappi
ng)

11015613214

I
ter
ati
on2:
(1t
o6)

11015613214(
Noswappi
ng)

11015613214(
Swappi
ngof10and6i
s
needed)

16151013214(
Noswappi
ng)

16151013214(
Swappi
ngof6and2i
s
needed)
12151013614(
Noswappi
ng)

12151013614

I
ter
ati
on3:
(2t
o6)

12151013614(
Swappi
ngof15and10
i
sneeded)

12101513614(
Noswappi
ng)

12101513614(
Swappi
ngof10and6i
s
needed)
12615131014(
NoSwappi
ng)

12615131014

I
ter
ati
on4:
(3t
o6)

12615131014 (
swappi
ngof15and13
i
sneeded)

12613151014 (
swappi
ngof13and10
i
sneeded)

12610151314 (
Noswappi
ng)
12610151314

I
ter
ati
on5:
(4t
o6)

12610151314(
swappi
ngof15and13i
s
needed)

12610131514(
Noswappi
ng)

12610131514(
Noswappi
ng)

I
ter
ati
on6:
(5t
o6)

12610131514(
Swappi
ngof15and14i
s
needed)
12610131415

Fi
nalSor
ti
ng:12610131415

Pr
ogr
am:
-
#sel
ect
ionsor
ti
ng
a={
}
pr
int
("
Ent
erany8no:
")
f
ori
inr
ange(
0,8)
:
a[
i]
=ev
al(
input
("
Ent
erno"
))
f
orj
inr
ange(
0,8)
:
f
ori
inr
ange(
j+1,
8):
i
fa[
i]
<a[
j]
:
p=a[
j]
;
a[
j]
=a[
i]
;
a[
i]
=p;
pr
int
("
\nSor
ti
ng:
-\
n")
f
orki
nrange(
0,8)
:
pr
int
(a[
k])

You might also like