Professional Documents
Culture Documents
Notes - PPS Unit 3
Notes - PPS Unit 3
https://www.studymedia.in/fe/notes
Pr
ogr
ammi
ngandPr
obl
em Sol
vi
ng Uni
t-
I
II
Uni
t–I
II
Funct
ion:
-
Functi
onsarethemostimpor
tantaspectofanappli
cati
on.Af
unct
ioncanbedef
inedast
heor
gani
zedbl
ock
ofreusabl
ecodewhichcanbecall
edwhenev err
equi
red.
Pythonall
owsust odivi
deal ar
geprogram i
ntothebasicbui
ldi
ngblocksknownasf
unct
ion.Thefunct
ion
contai
nsthesetofpr ogrammingstat
ement senclosedby{}
.Af uncti
oncanbecal
ledmulti
plet
imest o
provi
dereusabi
l
ityandmodulari
tyt
othepythonprogram.
I
notherwor
ds,wecansayt
hatthecoll
ect
ionoffunct
ionscr
eat
esapr
ogr
am.Thef
unct
ioni
sal
soknownas
pr
ocedur
eorsubr
outi
nei
notherpr
ogrammi ngl
anguages.
Pyt
honpr
ovideusvari
ousinbuil
tfunct
ionsl
i
ker
ange(
)orpr
int
().Al
though,t
heusercancr
eat
eit
sfunct
ionswhi
chcan
becal
l
eduser-
def
inedfunct
ions.
Needoff
unct
ion:
-
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 However
,Funct
ioncal
l
ingi
sal
way
sov
erheadi
napy
thonpr
ogr
am.
Def
ini
ngaFunct
ion
Youcandef
inef
unct
ionst
opr
ovi
det
her
equi
redf
unct
ional
i
ty.Her
ear
esi
mpl
erul
est
odef
ineaf
unct
ioni
n
Pyt
hon.
Funct
ionbl
ocksbegi
nwi
tht
hekey
wor
d def
f
oll
owedbyt
hef
unct
ionnameandpar
ent
heses(())
.
Anyi
nputpar
amet
ersorar
gument
sshoul
dbepl
acedwi
thi
nthesepar
ent
heses.Youcanal
sodef
ine
par
amet
ersi
nsi
det
hesepar
ent
heses.
Thef
ir
stst
atementofaf
unct
ioncanbeanopt
ionalst
atement-t
hedocument
ati
onst
ri
ngoft
he
f
unct
ionor
docst
ri
ng.
Thecodebl
ockwi
thi
nev
eryf
unct
ionst
art
swi
thacol
on(
:)andi
sindent
ed.
Thest
atementr
etur
n[ex
pressi
on]exi
tsaf
unct
ion,
opt
ional
l
ypassi
ngbackanexpr
essi
ont
othecal
l
er.
Ar
etur
nst
atementwi
thnoar
gument
sist
hesameasr
etur
nNone.
ZCOERPage1
Sy
ntax:
-
deff
uncti
on-name(par
ameter):
I
nstruct
iontobeprocessed.
Returnstat
ement
Exampl
es
Ex1 defhel
l
o_world(
):
pr
int
("
hell
owor
ld"
) Ex2 #def
ini
ngthefuncti
on
deff
unc(name):
#Nowy oucancal
lpr
int
mef
unct
ion pr
int
("
Hi "
,name)
;
hel
l
o_worl
d()
#call
i
ngthef
unct
ion
Ex3 defsum (a,
b): func(
"Ay
ush"
)
retur
na+b;
Ex4 defpr
int
me(str):
#t
akingvaluesfr
om t
heuser pri
ntst
r
a=int(
input(
"Ent
era:
")) ret
urn;
b=int(
input(
"Ent
erb:"
))
#Nowyoucancallpri
ntmefuncti
on
#pri
nti
ngthesum ofaandb pr
int
me(
"fi
rstcal
ltouserdef
inedfuncti
on!"
)
pri
nt(
"Sum ="
,sum(a,
b)) pr
int
me(
"secondcalltothesamef unct
ion"
)
Paramet erpartinfuncti
onisoptionalitmayormaynotbeused.
Allparamet er
s( ar
gument s)i
nt hePy t
honl anguagearepassedbyr ef
erence.Itmeansify ouchange
whatapar ameterrefer
st owit
hinaf unction,thechangealsoref
lect
sbacki nthecall
ingfunct
ion
Thereisanexcept ionint hecaseofmut ableobj ect
ssincet
hechangesmadet ot hemutableobject
s
l
ikestringdonotr everttotheorigi
nalstringr at
her,anewstri
ngobjecti
smade, andther
eforethetwo
dif
ferentobjectsareprint
ed.
Ex1 #call
i
ngt hefunct
ion
#defi
ningthefuncti
onimmutablei
tems change_l
ist(
li
st1)
;
defchange_li
st(
li
st1)
: pri
nt(
"l
istoutsi
defunct
ion="
,l
ist
1);
l
ist
1.append(20)
; Ex2
l
ist
1.append(30)
;
pri
nt(
"l
isti
nsidefunct
ion="
,l
i
st1) #defi
ningthefuncti
onmut abl
eobj
ectsl
ike
(st
ri
ng)
#defi
ningt
heli
st defchange_str
ing(st
r):
l
ist
1=[ 10,
30,
40,
50] st
r=st r+"Howsy ou";
pri
nt(
"pri
nti
ngt hestri
nginsi
defunct
ion
ZCOERPage2
:
",
str
); change_
str
ing(
str
ing1)
st
ri
ng1="
HiIam t
her
e" pr
int
("pr
int
ing t
hest
ri
ng out
sidef
unct
ion
:"
,st
ri
ng1)
#cal
l
ingt
hef
unct
ion
Ty
pesofargument
s
Wecanpassdif
fer
entt
ypesofar
gument
satt
het
imeoff
unct
ioncal
l
ing.
Requir
edar guments
Keywordar guments
Defaul
targuments
Vari
able-
lengthargument
s
RequiredArgument:
-
Argumentisprovi
dedatthet i
meoff unct
ioncal
li
ng.Asf arasther equiredar gument
sar econcer
ned,t
hese
aretheargumentswhicharer equiredt obepassedatt het i
meoff unctioncalli
ngwiththeexactmatchof
thei
rpositi
onsinthefuncti
oncal landf uncti
ondefini
ti
on.Ifeitheroft hear gumentsisnotprovi
dedinthe
funct
ioncall
,ort
hepositi
onoft hear gumentsischanged,thenthepy thoni nt
erpret
erwi
llshowtheerr
or.
Exampl
e1
#theargumentnamei sther
equi
redar
gumentt
othef
unct
ionf
unc
deffunc(name):
message=" Hi"+name;
ret
urnmessage;
name=i nput(
"Ent
ert
hename?
")
pri
nt(
func(name))
Output
:
Ent
erthename?
gaur
aw
Higauraw
Exampl
e2
#thef
unctionsi mple_i
nter
estaccept
sthr
eear
gument
sandr
etur
nst
hesi
mpl
eint
erestaccor
dingl
y
defsi
mple_ i
nterest
(p,t
,r
):
r
eturn( p*t
*r)/
100
p=fl
oat(
input
("
Entert
hepri
nci
pleamount?")
)
r=f
loat
(i
nput(
"Ent
erther
ateofi
nter
est?")
)
t=f
loat
(i
nput(
"Ent
erthet
imeinyear
s?"))
ZCOERPage3
pr
int
("
Simpl
eInt
erest
:",
si
mpl
e_i
nter
est
(p,
r,
t)
)
Out
put:
Ent
ert
hepr i
nci
pleamount?10000
Ent
ert
herateofinter
est
?5
Ent
ert
hetimeiny ear
s?2
Si
mpleInt
erest
:1000.0
Exampl
e3
#thefuncti
oncalcul
ater
etur
nst
hesum oft
woar
gument
saandb
defcalcul
ate(
a,b)
:
ret
urna+b
cal
cul
ate(
10)#t
hiscausesaner
roraswear
emi
ssi
ngar
equi
redar
gument
sb.
Output
:
TypeEr
ror
:cal
cul
ate(
)mi
ssi
ng1r
equi
redposi
ti
onal
argument
:'
b'
Key
wor
dar
gument
s:-
Pythonal
lowsustocallt
hefuncti
onwi t
hthekeywor
darguments.Thi
skindoffunct
ioncallwil
lenabl
eust o
passtheargument
sintherandom order
.
Thenameoft heargumentsistr
eatedasthekeywor
dsandmatchedint hef
uncti
oncal l
inganddefi
nit
ion.I
f
thesamemat chi
sfound,t
hev al
uesoftheargument
sar
ecopiedinthefunct
iondefi
nit
ion.
Exampl
e1
#functi
onf unci
scalledwi
ththenameandmessageast hekeywor
dar
gument
s
deffunc(name,message):
print(
"pr
int
ingthemessagewith"
,name,
"and"
,message)
func(
name=" John",
message="
hell
o")
Output
:
pr
inti
ngthemessagewi
thJohnandhel
l
o
Example2
prov
idi
ngt hev al
uesindifferentorderatthecal
li
ng
#Thef uncti
onsi mpl e_i
nterest
(p,t,r
)iscal
ledwi
tht
hekey
wor
dar
gument
stheor
derofar
gument
s
doesn'tmatteri
nt hiscase
defsimple_i
nterest(p,t
,r
):
r
eturn(p*t*r
)/100
ZCOERPage4
pr
int
("
Simpl
eInt
erest
:",
si
mpl
e_i
nter
est
(t=10,
r=10,
p=1900)
)
Out
put:
Si
mpleInt
erest
:1900.
0
I
fwepr
ovi
det
hedi
ff
erentnameofar
gument
satt
het
imeoff
unct
ioncal
l
,aner
rorwi
l
lbet
hrown.
Exampl
e3
#Thefunct
ionsimpl
e_inter
est
(p,
t,r
)iscal
l
edwi
tht
hekey
wor
dar
gument
s.
defsi
mple_i
nter
est(
p,t
,r)
:
r
etur
n(p*t*
r)/
100
pr
int(
"Si
mpleInt
erest
:",
si
mple_
int
erest
(t
ime=10,
rat
e=10,
pri
nci
ple=1900)
) # doesn'
tfi
ndt
heexact
matchofthenameofthear
guments(keywor
ds)
Output:
Ty
peEr
ror
:si
mpl
e_i
nter
est
()gotanunexpect
edkey
wor
dar
gument'
ti
me'
Thepy t
honallowsustoprovi
det hemixoftherequi
redargument
sandkeywordargument
satt heti
meof
funct
ioncall
.However
,therequir
edargumentmustnotbegi v
enaftert
hekeywor
dargument,i
.e.
,oncethe
keywordargumentisencounter
edinthefunct
ioncal
l,thefol
lowi
ngargument
smustalsobet hekeyword
arguments.
Exampl
e4
deffunc(name1,message,
name2) :
pri
nt(
"printi
ngthemessagewith",
name1,
",
",
message,
",
and"
,name2)
func(
"John" ,
message="
hel
lo"
,name2="Davi
d")#t
hefi
rstar
gumentisnott
hekey
wor
dar
gument
Output
:
pr
inti
ngthemessagewi
thJohn,
hel
l
o,andDav
id
Thefoll
owi
ngexamplewi
l
lcauseaner
rorduet
oani
n-pr
opermi
xofkey
wor
dandr
equi
redar
gument
sbei
ng
passedint
hef
uncti
oncal
l
.
Exampl
e5
deffunc(name1,message,
name2):
pri
nt(
"printi
ngthemessagewit
h",
name1,
",
",
message,
",
and"
,name2)
func(
"John" ,
message="
hel
lo"
,"
Davi
d")
Output:
SyntaxEr
ror
:posi
ti
onal
argumentf
oll
owskey
wor
dar
gument
ZCOERPage5
Def
aul
tAr
gument
s:-
Pyt
honal lowsust oi
niti
ali
zetheargumentsatthef uncti
ondefi
nit
ion.I
ftheval
ueofanyoft
hear
gumentis
notprovidedatthetimeoff uncti
oncall,t
hent hatargumentcanbei nit
ial
i
zedwit
htheval
uegi
veni
nt he
def
ini
tionev eni
ftheargumentisnotspecif
iedatthefuncti
oncall
.
Exampl
e1
defpri
ntme(name,
age=22) :
pri
nt(
"Mynamei s"
,name,"andageis"
,age)
pri
ntme(name=" j
ohn")#thev ar
iabl
eagei snotpassedi
ntot
hef
unct
ionhowev
ert
hedef
aul
tval
ueof
ageisconsi
deredinthefunction
Out
put
:
Mynamei
sjohnandagei
s22
Exampl
e2
defpri
ntme(name,age=22):
pri
nt(
"Mynamei s",
name,"andagei s"
,age)
pri
ntme(name=" j
ohn")#thev ar
iableagei snotpassedintothefunct
ionhowevert
hedefaul
tval
ueof
ageisconsider
edinthefunction
pri
ntme(age=10,name="Dav i
d")#thevalueofagei soverwri
ttenher
e,10wil
lbepri
ntedasage
Out
put
:
Mynamei
sjohnandageis22
Mynamei
sDavidandageis10
Var
iabl
elengt
hAr
gument
s:-
Somet i
meswemaynotknow thenumberofar
gumentstobepassedi
nadvance.I
nsuchcases,Python
provi
desusthef
lexi
bil
i
tyt
opr
ovi
dethecommasepar
atedv
alueswhi
char
eint
ernal
l
ytr
eat
edastuplesatthe
funct
ioncal
l
.
Howev
er,
att
hef
unct
iondef
ini
ti
on,
wehav
etodef
inet
hev
ari
abl
ewi
th*(
star
)as*
<var
iabl
e-name>.
Exampl
e
defprintme(*names):
pri
nt("ty
peofpassedargumenti
s",
type(names)
)
pri
nt("pri
nti
ngthepassedar
gument
s...
")
fornamei nnames:
print(
name)
ZCOERPage6
pr
int
me(
"j
ohn"
,"
Dav
id"
,"
smi
th"
,"
nick"
)
Out put:
typeofpassedargumenti
s<class'
tupl
e'
>
printi
ngthepassedar
gument
s..
.
john
Dav id
smi th
Scopeofvariabl
es:
-
Thescopesofthev ar
iabl
esdependuponthelocati
onwherethevar
iabl
eisbei
ngdecl
ared.Thev
ari
abl
e
decl
aredi
nonepartoftheprogr
am maynotbeaccessi
blet
otheot
herpart
s.
Globalvar
iables
Localvari
ables
Thevar
iabledefi
nedout si
deanyfuncti
onisknownt
ohav
eagl
obalscopewher
east
hev
ari
abl
edef
ined
i
nsi
deaf unct
ionisknowntohavealocalscope.
Exampl
e1
defprint
_message()
:
message=" hel
lo!!Iam goingt
opri
ntamessage.
"#t hevar
iabl
emessagei slocalt
othef
unct
ion
i
tself
pri
nt(message)
pri
nt_message()
pri
nt(message)#thi
swi l
lcauseaner
rorsi
nceal
ocalvar
iabl
ecannotbeaccessibl
ehere.
Output:
hell
o!!Iam goingt
opri
ntamessage.
Fil
e"/r
oot/
Py char
mProject
s/Py
thonTest
/Test
1.py
",l
i
ne5,
in
pri
nt(
message)
NameEr r
or:name'message'i
snotdefi
ned
Exampl
e2
defcal cul
ate(*args)
:
sum=0
forar ginargs:
sum =sum +ar g
print("
Thesum i s"
,sum)
sum=0
calculate(
10,20,30)#60will
bepri
ntedasthesum
pri
nt("Valueofsum out si
dethef
uncti
on:
",
sum)#0wi
l
lbepr
int
ed
ZCOERPage7
Out
put
:
Thesum i
s60
Val
ueofsum out
sidet
hef
unct
ion:
0
TheAnony
mousf
unct
ion(l
ambda)
:-
Sy
ntax:
-
l
ambda
argument
s :
expr
essi
on
E.
g.
x=lambdaa:
a+10 x=lambdaa,
b:a+b
pr
int
("
sum ="
,x(
20)
) pr
int
("
sum ="
,x(20,
10)
)
Whyt
ousel
ambda
Whenwewantt oexecut
esomet
askwi
thi
nfunct
ionwi
thsomei
nputwhi
chwi
l
lbepr
ocessi
ngpar
amet
er
passedt
ofunct
ion.
E.g.
ZCOERPage8
defmy f
unc(n)
:
ret
urnlambdaa:
a*n
x=my f
unc(2) /
/wi
l
lexecut
efi
rstf
unwi
thpar
amet
er2t
heni
tpassedont
olambdawi
thxi
.
e.
11
pr
int
(x(
11))
Py
thonmodul
es
Amodul eal
lowsy outologi
cal
lyorganizeyourPy t
honcode.
Groupingr
elatedcodeintoamodul emakest hecodeeasiert
ounderst
andanduse.
Amodul ei
saPy t
honobjectwit
har bi
tr
aril
ynamedat tri
but
esthaty
oucanbindandref
erence.
Moduleisaf i
l
econsisti
ngofPy t
honcode.
Modulecandef i
nefuncti
ons,classesandv ar
iabl
es.Amodul ecanalsoincl
uderunnabl
e
code.
I
mpor
tstatement
Theimportstatementi
susedt oimportallthefuncti
onal
it
yofonemodulei
ntoanot
her
Wecanusethefuncti
onal
i
tyofanypyt
honsour
cefi
l
ebyimport
ingt
hatf
il
east
hemodul
eint
oanot
herpy
thon
sour
cef
il
e.
Wecani
mpor tmult
ipl
emoduleswit
hasingl
eimpor
tst
atement
.
Sy
ntax
:-
i
mpor t
modul
e1,
modul
e2,
.
..
..
..
.
modul
e n
ex.i
mportnumpy
Fr
om-
importstat
ement
Inst
eadofimporti
ngthewholemodulei
ntothenamespace,
pyt
honpr
ovi
desthef
lexi
bil
i
tyt
o
i
mpor tonl
ythespeci
fi
catt
ri
butesofamodul
e.
Thiscanbedonebyusi ngfrom?importstat
ement.Thesynt
axtousethefr
om- i
mport
stat
ementisgiv
enbelow.
Sy
ntax:
-
f
rom
< modul
e-name>
impor
t
<name
1>,
<name
2>.
.,
<name
n>
cal
cul
at i
on.py:
#place the code i
n t
he cal
cul
ati
on.
py
def summat i
on(a,
b):
return a+b
def multipli
cati
on(a,
b):
return a*b;
def div
ide(a,b):
ZCOERPage9
return a/
b;
Mai
n.py:
fr
om calculati
on import
summat i
on
#it
will
import only
the
summat i
on()
f
rom cal
cul
ati
on.
py
a
= int(i
nput (
"Enter
the
fi
rst
number"
))
b
= i
nt(i
nput (
"Enter
the
second
number "
))
pri
nt("Sum =
",summat i
on(a,
b))
Renami
ngi
mpor
tfi
l
e
i
mpor
t
<modul
e-name>
as
<speci
fi
c-name>
Py
thonpackages
Thepackagesinpy t
honfacil
i
tat
et hedev el
operwit
htheappli
cationdev el
opmentenv ir
onmentby
prov
idi
ngahi er
archi
caldi
rect
orystructur
ewher eapackagecontainssub-packages,modules,and
sub-
modules.Thepackagesareusedt ocategor
izet
heappli
cat
ionlevelcodeeffici
entl
y.
ZCOERPage10