Python Programming Typing Notes
Python Programming Typing Notes
Text books:
1. William Stallings, Network Security Essentials: Applications and Standards, Prentice Hall, 4th edition, 2010.
2. Michael T. Goodrich and Roberto Tamassia, Introduction to Computer Security, Addison Wesley, 2011.
3. William Stallings, Network Security Essentials: Applications and Standards, Prentice Hall, 4th edition, 2010.
4. Alfred J. Menezes, Paul C. van Oorschot and Scott A. Vanstone, Handbook of Applied Cryptography, CRC Press,
2001.
PYTHON PROGRAMMING
Course Outcome ( CO) Bloom’s Knowledge Level (KL)
Conditionals: Conditional statement in Python (if-else statement, its working and execution),
Nested-if statement and Elif statement in Python, Expression Evaluation & Float Representation.
II 08
Loops: Purpose and working of loops , While loop including its working, For Loop , Nested Loops ,
Break and Continue.
Function: Parts of A Function , Execution of A Function , Keyword and Default Arguments ,Scope
Rules.
Strings : Length of the string and perform Concatenation and Repeat operations in it. Indexing and
III
Slicing of Strings. 08
Python Data Structure : Tuples , Unpacking Sequences , Lists , Mutable Sequences , List
Comprehension , Sets , Dictionaries
Higher Order Functions: Treat functions as first class Objects , Lambda Expressions
Sieve of Eratosthenes: generate prime numbers with the help of an algorithm given by the Greek
Mathematician named Eratosthenes, whose algorithm is known as Sieve of Eratosthenes.
File I/O : File input and output operations in Python Programming
Exceptions and Assertions
IV Modules : Introduction , Importing Modules , 08
Abstract Data Types : Abstract data types and ADT interface in Python Programming.
Classes : Class definition and other operations in the classes , Special Methods ( such as _init_,
_str_, comparison methods and Arithmetic methods etc.) , Class Example , Inheritance , Inheritance
and OOP.
Text books:
1. Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition, Updated for Python 3,
Shroff/O‘Reilly Publishers, 2016 (http://greenteapress.com/wp/thinkpython/)
2. Guido van Rossum and Fred L. Drake Jr, ―An Introduction to Python – Revised and updated for Python 3.2, Network
Theory Ltd., 2011.
3.John V Guttag, ―Introduction to Computation and Programming Using Python‘‘, Revised and expanded Edition, MIT
Press , 2013
4.Robert Sedgewick, Kevin Wayne, Robert Dondero, ―Introduction to Programming in Python: An Inter-disciplinary
Approach, Pearson India Education Services Pvt. Ltd., 2016.
5.Timothy A. Budd, ―Exploring Python‖, Mc-Graw Hill Education (India) Private Ltd.,, 2015.
6.Kenneth A. Lambert, ―Fundamentals of Python: First Programs‖, CENGAGE Learning, 2012.
7.Charles Dierbach, ―Introduction to Computer Science using Python: A Computational ProblemSolving Focus, Wiley
India Edition, 2013.
8.Paul Gries, Jennifer Campbell and Jason Montojo, ―Practical Programming: An Introduction to Computer Science
using Python 3‖, Second edition, Pragmatic Programmers, LLC, 2013.
Mapped With : https://ict.iitk.ac.in/product/python-programming-a-practical-approach/
ST U D YZONE A D I T YA .COM
www.studyzoneaditya.com
PYTHONNOTES
UNI
T1
ThePr
ogr
ammi
ngCy
clef
orPy
thon:
Python'
sdevel
opmentcy cl
eisdramati
cal
lyshor
terthanthatoft
radit
ional
tool
s.InPython,
ther
e
arenocompileorl
inksteps--Pyt
honprogramssimplyimportmodulesatrunt
imeanduset he
object
stheycont
ain.Becauseofthi
s,Pyt
honprogramsrunimmedi 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
onispr essedagai 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
:
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. >>>pr
int
(c)o/
p=>15
5. >>>c-
=5
6. >>>pr
int
(c)o/
p=>10
7. >>>c*
=2
8. >>>pr
int
(c)o/
p=>20
9. >>>c/
=2
10.>>>pr
int
(c)o/
p=>10
11.>>>c%=3
12.>>>pr
int
(c)o/
p=>1
13.>>>c=5
14.>>>c*
*=2
15.>>>pr
int
(c)o/
p=>25
16.>>>c/
/=2
17.>>>pr
int
(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>4and3>2
2. pr
int
(a)
3. b=5>4or3<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
f(ai
nli
st)
:
5. pr
int
("ai
singi
venl
i
st"
)
6. el
se:
7. pr
int
("ai
snoti
ngi
venl
i
st"
)
8. i
f(
bnoti
nli
st)
:
9. pr
int
("bi
snotgi
veni
nli
st"
)
10.el
se:
11. pr
int
("bi
sgi
veni
nli
st"
)
Out
put
:
1. ai
singi
venl
i
st
2. bi
sgi
veni
nli
st
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(ai
sb)
:
4. pr
inta,
bhav
esamei
dent
it
y
5. el
se:
6. pr
inta,
bar
edi
ff
erent
7. b=10
8. i
f(ai
snotb)
:
9. pr
inta,
bhav
edi
ff
erenti
dent
it
y
10.el
se:
11. pr
inta,
bhav
esamei
dent
it
y
Out
put
1. >>>
2. a,
bhav
esamei
dent
it
y
3. a,
bhav
edi
ff
erenti
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
sissi
ngl
eli
necomment
.
2)Mul
til
inedComment
:
Mul
til
i
nedcommentcanbegi
veni
nsi
det
ri
plequot
es.
eg:
1. '
'
''
'Thi
s
2. I
s
3. Mul
ti
pli
necomment
'
''
eg:
1. #si
ngl
eli
necomment
2. pr
int"
Hel
l
oPy
thon"
3. '
'
''
'
Thi
sis
4. mul
ti
li
necomment
'
''
Py
thonKey
wor
ds
FOR IMPORTANT NOTES TOUCH TO OUR WEBSITE "!! studyzoneaditya.com !!"
StudyZoneAditya.com
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. st
atement
s
Py
thonI
fSt
atementExampl
e
1. a=10
2. i
fa==10:
3. pr
i "
nt(Wel
comet
oSRCol
l
ege")
Out
put
:
Wel
comet
oSRCol
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. st
atement
s
3. el
se:
4. st
atement
s
next
>><<pr
ev
Py
thonI
fel
i
fSt
atement
I
npy
thon,
wecanuseI
fel
i
ftocheckmul
ti
plecondi
ti
ons.Py
thonpr
ovi
desel
ifkey
wor
dtocheck
mul
ti
plecondi
ti
on.
Py
thonI
fel
ifSy
ntax
1. i
fcondi
ti
on:
2. Code
3. ………
4. el
ifcondi
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
fcondi
ti
on:
i
fcondi
ti
on:
Code
………
Loopsi
nPy
thon
FOR IMPORTANT NOTES TOUCH TO OUR WEBSITE "!! studyzoneaditya.com !!"
StudyZoneAditya.com
1.
Forl
oop
ForLoop
Pyt
honforl
oopisusedtoit
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<v
ari
abl
e>i
n<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
orai
nrange(
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
orni
nrange(
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
ori
inr
ange(
1,6)
:
2. f
orj
inr
ange(
1,i
+1)
:
3. Pr
int
(i
)
4. pr
int
Out
put
:
1. 1
2. 22
3. 333
4. 4444
5. 55555
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
ori
inr
ange(
1,6)
:
2. f
orj
inr
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
l
eLoopSy
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
l
eLoopExampl
e1
1. a=10
2. whi
lea>0:
3. pr
int
("Val
ueofai
s",
a)
4. a=a-
2
pr
int"
Loopi
sCompl
eted"
Out
put
:
1. Val
ueofai
s10
2. Val
ueofai
s8
3. Val
ueofai
s6
4. Val
ueofai
s4
5. Val
ueofai
s2
6. Loopi
sCompl
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
l
eLoopExampl
e2
1. n=153
2. sum=0
3. whi
len>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
ori
in[
1,2,
3,
4,
5]:
2. i
fi==4:
3. pr
int
("
Elementf
ound"
)
4. br
eak
5. pr
int
(i
)
Out
put
:
123El
ementf
ound
Py
thonBr
eakExampl
e2
1. f
orl
ett
eri
n'Py
thon3'
:
2. i
flet
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
lea<=5:
3. a=a+1
4. i
fa%2==0:
5. cont
inue
6. pr
int
(a)
7. pr
int
("EndofLoop"
)
Out
put
:
1. 1
2. 3
3. 5
4. EndofLoop
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
ori
in[
1,2,
3,
4,
5]:
2. i
fi==3:
3. pass
4. pr
int"
Passwhenv
aluei
s",
i
5. pr
inti
,
Out
put
:
1. >>>
2. 12Passwhenv
aluei
s3
3. 345
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,wecanusedefkey
wor
dtodef
inet
hef
unct
ion.Thesy
ntaxt
odef
ineaf
unct
ioni
npy
thoni
s
gi
venbelow.
1. defmy
_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. defhel
l
o_wor
ld(
):
2. pr
int
("hel
l
owor
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
thonf
unct
iont
ocal
cul
atet
hesum oft
wov
ari
abl
es
2. #def
ini
ngt
hef
unct
ion
3. defsum (
a,b)
:
4. r
etur
na+b
5.
6. #t
aki
ngv
aluesf
rom t
heuser
7. a=i
nt(
input
("
Ent
era:
"))
8. b=i
nt(
input
("
Ent
erb:
"))
9.
10.#pr
int
ingt
hesum ofaandb
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. deff
unc(
name)
:
2. message="
Hi"
+name;
3. r
etur
nmessage;
4. name=i
nput
("
Ent
ert
hename?
")
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
ionf
unci
scal
l
edwi
tht
henameandmessageast
hekey
wor
dar
gument
s
2. deff
unc(
name,
message)
:
3. pr
int
("pr
int
ingt
hemessagewi
th"
,name,
"and"
,message)
4. f
unc(
name="
John"
,message="
hel
l
o")#nameandmessagei
scopi
edwi
tht
hev
aluesJohnandhel
l
oresp
ect
ivel
y
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. defpr
int
me(
name,
age=22)
:
2. pr
int
("Mynamei
s",
name,
"andagei
s",
age)
3. pr
int
me(
name="
john"
)#t
hev
ari
abl
eagei
snotpassedi
ntot
hef
unct
ionhowev
ert
hedef
aul
tval
ueofage
i
sconsi
der
edi
nthef
unct
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. defpr
int
me(
*names)
:
2. pr
int
("t
ypeofpassedar
gumenti
s",
type(
names)
)
3. pr
int
("pr
int
ingt
hepassedar
gument
s..
."
)
4. f
ornamei
nnames:
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. defpr
int
_message(
):
2. message="
hel
l
o!!Iam goi
ngt
opr
intamessage.
"#t
hev
ari
abl
emessagei
slocal
tot
hef
unct
ioni
tsel
f
3. pr
int
(message)
4. pr
int
_message(
)
5. pr
int
(message)#t
hiswi
l
lcauseaner
rorsi
nceal
ocal
var
iabl
ecannotbeaccessi
bleher
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. defcal
cul
ate(
*ar
gs)
:
2. sum=0
3. f
orar
ginar
gs:
4. sum =sum +ar
g
5. pr
int
("Thesum i
s",
sum)
6. sum=0
7. cal
cul
ate(
10,
20,
30)#60wi
l
lbepr
int
edast
hesum
8. pr
int
("Val
ueofsum out
sidet
hef
unct
ion:
",
sum)#0wi
l
lbepr
int
ed
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
r="
HiPy
thon!
"
Her
e,i
fwecheckt
het
ypeoft
hev
ari
abl
est
rusi
ngapy
thonscr
ipt
1. pr
int
(ty
pe(
str
)),
theni
twi
l
lpr
intst
ri
ng(
str
).
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
hanewst
ringsi
ncei
tscont
entcannotbe
part
ial
l
yreplaced.Stri
ngsarei
mmut abl
einpython.
Consi
dert
hef
oll
owi
ngexampl
e.
Ex
ampl
e1
1. st
r="
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
r="
HiPy
thon!
"
Her
e,i
fwecheckt
het
ypeoft
hev
ari
abl
est
rusi
ngapy
thonscr
ipt
1. pr
int
(ty
pe(
str
)),
theni
twi
l
lpr
intst
ri
ng(
str
).
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
r="
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
r="
HELLO"
2. pr
int
(st
r)
3. st
r="
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
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
meani
ngofescapechar
act
erssuchas"
C:/
/py
thon"
.Todef
ineanyst
ri
ngasar
awst
ri
ng,
thechar
ac
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
r="
Hel
l
o"
2. st
r1="wor
ld"
3. pr
int
(st
r*3)#pr
int
sHel
l
oHel
l
oHel
l
o
4. pr
int
(st
r+st
r1)
#pr
int
sHel
l
owor
ld
5. pr
int
(st
r[
4])#pr
int
so
6. pr
int
(st
r[
1:4]
);#pr
int
sel
l
7. pr
int
('
w'i
nst
r)#pr
int
sfal
seaswi
snotpr
esenti
nst
r
8. pr
int
('
wo'
noti
nst
r1)#pr
int
sfal
seaswoi
spr
esenti
nst
r1.
9. pr
int
(r'
C:/
/py
thon37'
)#pr
int
sC:
//py
thon37asi
tiswr
it
ten
10.pr
int
("Thest
ri
ngst
r:%s"
%(st
r))#pr
int
sThest
ri
ngst
r:Hel
l
o
11.pr
int
('
H'i
nst
r)#pr
int
str
ueasHi
spr
esenti
nst
r
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,
Pyt
honpr ovi
desanaddit
ional
operat
or%whichisusedasanint
erf
acebetweentheformatspeci
fier
sandt 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
Iam I
nteger.
..Myv
aluei
s%d\
nHi
Iam f
loat.
..Myv
aluei
s%f
\nHi
Iam st
ri
ng.
..Myv
aluei
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(ex
cluded)
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
ngaf
orl
oop:
Ex
ampl
e
Pr
intal
li
temsi
nthel
i
st,
onebyone:
t
hisl
ist=["
apple",
"banana"
,"cher
ry"
]
f
orxi nthi
sli
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 hei
stuset nkeywor
d:
Ex
ampl
e
Checki
f"appl
e"i
spr
esenti
nthel
i
st:
t
hisl
ist=["apple","
banana",
"cher
ry"
]
i
f"apple"i
nt hisl
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 hel
ouset i
st(
)const
ruct
ort
omakeanewl
i
st.
Ex
ampl
e
Usi hel
ngt 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:Lear
nsomelistfuncti
onsf
rom y
ourcl
assnot
esl
ike,
del
,remove,
pop,i
nsert
,sor
t,sort
edet c.
Tupl
e
At
upl
eisacol
l
ect
ionwhi
chi
sor
der
edandunchangeabl
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,
-1r
efer
stot
hel
asti
tem,
-2r
efer
stot
he
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(ex
cluded)
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 ngaf
emsbyusi orl
oop.
Ex
ampl
e
I
ter
atet
hrought
hei
temsandpr
intt
hev
alues:
t
histuple=("appl
e",
"banana"
,"cher
ry"
)
f
orxi nthist
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
hei
nkey
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
nthist
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
hel )me
en( t
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 het
ouset 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
hrought
heseti
temsusi
ngaf
orl
oop,
oraski
faspeci
fi
edv
aluei
spr
esent
i
naset,
byusi
ngt
heinkey
word.
Ex
ampl
e
Loopt
hrought
heset
,andpr
intt
hev
alues:
t
hisset={
"appl
e",
"banana"
,"cher
ry"
}
f
orxinthisset
:
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
hel )me
en( t
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 hes
ouset et
()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
, her
weuset 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 hedi
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
lNOTr
aiseaner
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={"
brand"
:"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 edget
hodcal
l ()t
hatwi
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
ngaf
orl
oop.
Whenl
oopingthr
oughadicti
onar
y,t
her
etur
nval
uear
ethekey
soft
hedi
cti
onar
y,butt
her
e
ar
emethodstoretur
ntheval
uesaswel
l
.
Ex
ampl
e
t
hisdi
ct={
"
brand"
:"For
d",
"
model":"
Mustang"
,
"
year"
:1964
}
Pr
intal
lkeynamesi
nthedi
cti
onar
y,onebyone:
f
orxinthisdi
ct:
pr
int
(x)
out
put
:
brand
model
year
Ex
ampl
e
Pr
intal
lval
uesi
nthedi
cti
onar
y,onebyone:
f
orxint hisdict
:
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
hel )me
en( t
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 hedi
ouset 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
hedel
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
lent r
iesindict
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
thonLambda
Al
ambdaf
unct
ioni
sasmal
lanony
mousf
unct
ion.
Alambdafunct
ioncant
akeanynumberofar
gument
s,butcanonl
yhav
eone
expr
essi
on.
Sy
ntax: lambdaarguments: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=lambdaa:
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=lambdaa,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
stheopen(
)funct
ion.
Theopen(
)funct
iont
akest
wopar
amet
er f
s;il
ename,
andmode.
Ther
ear
efourdi
ff
erentmet
hods(
modes)f
oropeni
ngaf
il
e:
"
r"-Read-Def
aul
tval
ue.Opensaf
il
eforr
eadi
ng,
err
ori
fthef
il
edoesnotexi
st
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
"
t"-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
nopen(
)funct
ion.
Theopen(
)funct
ionr
etur
nsaf
il
eobj
ect
,whi
chhasar )me
ead( t
hodf
orr
eadi
ngt
hecont
entof
thef
il
e:
Ex
ampl
e
f=open("demof
il
e.t
xt"
,"r
")
pr
int
(f.
read()
)
out
put
:
Hel
lo!Welcometodemofi
le.
txt
Thi
sfil
eisfort
esti
ngpur
poses.
GoodLuck!
ReadOnl
yPar
tsoft
heFi
l
e
Bydefaul
tther )me
ead( t
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
")
pr
int
(f.
read(5)
)
out
put
:
Hel
l
o
ReadLi
nes
Youcanr
etur
nonel
i
nebyusi
ngt
her
eadl
i )me
ne( t
hod:
Ex
ampl
e
Readonel
i
neoft
hef
il
e:
f=open("demofi
le.
txt
","
r"
)
pr
int
(f.
readli
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
")
forxinf:
pri
nt(
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
otheopen(
)funct
ion:
a"-
" Append-wi
l
lappendt
otheendoft
hef
il
e
w"-
" Wr
it
e-wi
l
lov
erwr
it
eanyexi
sti
ngcont
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
ileaft
ertheappendi
ng:
f=open("demofi
l
e2.
txt"
,"r
")
pr
int(
f.
read())
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
ileaft
ertheappendi
ng:
f=open("demofi
l
e3.
txt"
,"r
")
pr
int(
f.
read())
out
put
:
Woops!Ihav
edel
etedt
hecont
ent
!
Del
eteaFi
l
e
Todel
eteaf
il
e,y
oumusti
mpor
ttheOSmodul
e,andr
uni
tsos.
remov
e()f
unct
ion:
Ex
ampl
e
Remov
ethef
il
e"demof
il
e.t
xt"
:
i
mportos
os.
remov
e("
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,hendel
etei
t:
i
mpor tos
i
fos.path.
exi
sts(
"demofi
le.
txt
"):
os.
remove("
demof i
l
e.t
xt")
el
se:
pri
nt(
"Thefi
l
edoesnotexi st
")
Del
eteFol
der
Todel
eteanent
ir
efol
der
,uset
heos.
rmdi
r)me
( t
hod:
Ex
ampl
e
Remov
ethef
older"
myf
older
":
i
mportos
os.
rmdi
r(
"my
fol
der
")
Except
ionHandl
i
ng
Whenanerroroccur
s,orexcept
ionaswecal
li
t,Py
thonwi
l
lnor
mal
l
yst
opandgener
atean
er
rormessage.
Theseexcept
ionscanbehandl
edusi hef
ngt oll
owi
ngbl
ock:
Thet
rybl
ockl
etsy
out
establ
ockofcodef
orer
ror
s.
Theexceptbl
ockl
etsy
ouhandl
etheer
ror
.
Thefi
nall
ybl
ockl
etsy
ouexecut
ecode,
regar
dlessoft
her
esul
toft
het
ry-andexcept
bl
ocks.
Ex
ampl
e
Thet
rybl
ockwi
l
lgener
ateanexcept
ion,
becausexi
snotdef
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
aisesaNameEr
rorandanot
herf
orot
herer
ror
s:
tr
y:
pri
nt(
x)
exceptNameError
:
pri
nt(
"Var
iabl
exisnotdefi
ned")
except:
pri
nt(
"Somethi
ngelsewentwrong"
)
Out
put
:Var
iabl
exi
snotdef
ined
El
se
Youcanuset
heel
sekey
wor
dtodef
ineabl
ockofcodet
obeexecut
edi
fnoer
ror
swer
e
rai
sed:
Ex
ampl
e
I
nthi
sexampl
e,t
het
rybl
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
Thefi yb
nal
l l
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
her
aisekey
wor
d.
Ex
ampl
e
Rai
seaner
rorandst
opt
hepr
ogr
am i
fxi
slowert
han0:
x=-
1
i
fx<0:
r
aiseExcept
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
fnottype(
x)i
sint:
r
aiseTypeEr
ror
("
Onlyi
nteger
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
enamedmymodul
e.py
defgreeti
ng(name)
:
pri
nt("
Hell
o,"+name)
UseaModul
e
Nowwecanuset
hemodul
ewej
ustcr
eat
ed,
byusi
ngt
hei ts
mpor t
atement
:
Ex
ampl
e
I
mpor
tthemodul
enamedmy
modul
e,andcal
lthegr
eet
ingf
unct
ion:
i
mportmy 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:
cl
assPer son:
def__i
nit__
(sel
f,name,
age)
:
sel
f.
name=name
sel
f.
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):
FOR IMPORTANT NOTES TOUCH TO OUR WEBSITE "!! studyzoneaditya.com !!"
StudyZoneAditya.com
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])