Chab funetions and Modules,
Chop 4A: funtion
Need o funcion /hatis Funion
Fun cion DeihiHon
ELun tio n Call
\ariable Stapt and litcime
The Return Statemunt Arqumnt o} funthon
Lambda or Anonymous Funtion
DoLmentatien Sring.
hood Pragrammin Prachiua
Chap 4B: Modules
Tnttoducion to Modutes
Inro d thon oPakaae
Siandard Libray Hodule
fun cki en
funci on Deiniion Funtion Call
DATE
#
Function's
Need ot fun ctien
what is fun ien:
Funcion i a blo ck of adt Ihat perlorm
spu lie task
)tollosing
AII Ingaly alatd stakem unt can be getuprd
tngthur in sing inity
un derstand and dabug
J) Repratiien a trquantly Heuird nde ian b.
araidad by usina untisn
9 Dividing Lonq progmm ino funcien alow us to
dubua he partb o program enu at a time.sR
5) RLwsabili hy js an impor tant attature ot Funchion.
Onc hi un tien ia dcared e can use I
hmt anuhtuby calling it
Funttion Deiniion it coNit of tun Parts
funci on Deinitien
Pun stiên Huadur Fun chior Body
DATE
funttim dinikin means wrapping seNeralin s
C0de Io gi calls rel ated statement) toquther in.
binau eniby
In Pathon. uncian ii deined by 'dtt' kuuuaerd
Sntax:h
hodLr
SIateonnt -l
Slatmnt-2
Stolemnts
stakum nt-3
Statmunt
A. Cyuru funtien shold have fun tin nam
whith hold be yaid votiablt/icunHHr.
2). "
empuls orstindicate hat
3) fvun snmunt altr cetn are qetintund ed
to show that thàL ae put at nctien
abAocitkd mith paramter.
haramte, are 0pti en al, wcan pADA Sn MMort paramua
) Paramctr ar the input iable ct, un ctin
Ud to held thi vae pass by HunUH en call
det mtssaqe
print ("HLtn")
orint This is Statkumund
print"Proqram inished."
print(Rent o tde.")
DATE
2). dtt addihion()
print la,'t'b=', atb)
*3). de agtl):
print (" Child")
ded deloaratien ):
print Programis tiniuhed")
print
rest o he cod
>funhion Ca i
fun cion cal is a Ath statemant that invekes
hen A unti i calltd, the gutier Controt
aet ee utd, altr teuti the CGntA goes back
An ctiem name ith reqird paramekr
Syntan.:
print ('LuLky)
name
Erry ouwtur punhion cont acuss inn r fun cion data - memb un
det mt).age
print (1x )
Euehy iìnner un tion has acess to th data
memben of ith prior fun ttien's"
Variable Scope and itetimei
Scopei the part/tunction al prorann in oh\ch
Global Variabie Local Vaiable
)A vari ableohich s
declared outbid h decladinsidea
in maçnunci oniN knOLh
bodyoProgram is as Lo(al uariahle
called sGlab a
Wariable.
2) Asesbibility sk ariahl2) ALas bibilhy o uariable
program AllL un ion un diem in io hich it
tan arSA the dohal decaed.and al th
unctiern deined uithin
thot ncten
3) The lohal vari abl Ahe oLal varioable i
MUmannitD hrouoh eatrd uwhon the hunchon
D
hi ntire pragrom stank enetina and qe
e1eCutin
Aotal waniable
uncien can change more S e r thLL
he values sl qlebal vaniable caunot b
yari cuble Chanad by ataida
global Ryuard qabal
de clare a aobal wariable
inaid tuntiem
The ins tante at which MAriable is decarLd
gdobal rom th at inatonco anu it beome aas
obol uariable hroughout pragram.
# hlobd
b: 20 # (alo bal b 20
qlobal a
print la)
print l6) print a)
f1) print Lb)
a 20
OlP enor -variable "
b20.
torterentod btore
Enampl:
def 20:
print (ab) b=20O Low
+ Lora print (b)
printlo
riw100)
3) 0=100 # (hlobal a1000#updateda
print La
alobal a 4 Galabal Statemeht
prit(a)
print la)
Retarn Statemont
more thas Zro
3ero Vle D th alin a
part of function
T4 is op tiÛn alit
al it atuuys inditate theend
alao td do ranser the controt
bark t6 th ealling pad
Syntax: return ValR
:it there cre multiple walu t hetur
ol tuple.
DATE
Example ) del
41) deihulot
rurn msa Catb
print (hillo priNt Sum is . )
3) de tacn: priN (sum)
14 n== 0:
rtrn 1
rebulte n*tauln-1)
Loteteurn rswlt
print (ac5)
Arquument o} Function:
Argument he varioble d in functien
then, theal in needo to pab theco
-ing value to calling part
dk tunt (argl,ag2, argas rgn)
tuncl MaVal)val3 val n)
torrponding v alus qet asigntd to he
det un (arn):
print ( a r g ) l
un(Lu cky")
TE
yps ot argument- ththe are
rment
A Reqird ArFumunt
ALCUim, hey ntd to be passd in
Coect numbtr and ndaridurinq calluna.
Syntaai
orgumut.
Example d! add Cab) _de add Co. b, c)
deatbtC
printld
add. (5, 6) add 5y6)
*EOr -missing one
tuirtà posihia nal ar
boan 2> Dau Artåi ment
duhing untti rall thuh hese Malus are
Aaken dekautt
func CUalval3,)
DATE
faample: d} adàla 10,b=5) : 1) det addlab,c-20):
print(C9,b, )
add) adls10)
aadd(15) add (11,12,30)
add (20,25) add (1l,0)
3 Ktysord Argumenti
ktuyword aagment ClHealb0 relkered s Named
ae asociatrd mith alues duning caliing
-fDsing pan, henc poihion a arquhent dos nat
mal
Each arument name sheulal haw o match wih
qLnint used in deininq part
Syntai deR Aunclorgi
Aune(aral= valu araia Value2,..)
Bune Cag 1: value arg2 = Value )
Ealomple det fun ( name, age
print Chame",=, name)aeat
print ('age ='ag)
fun (name e Lutky' 0¡t=20)
tun ( age= 20, nam='Lucky)
del add(anb, G,d):
Ctbt Gtd
(asb G, d, e))
add(b=5, à=Ba-9, C=L)
add (d:S,C-4 b=2,a =1)
ononm an unctnn
I Lombdn
Funion:AnonyMots Lombda
Aror
(L22,333) sum print
fun1(l3)
60) 40, 1l0, fan
mnts
in the retun larns)#it print
1args) tun cle! Exaaple
clwaltvaVal3,
Valn
his tsyniax
or tia spe *ias #
am):gument_n or(*
tune dt
Syntayi
it. oferm oAmiht
ho
aNAumehd
ha in the acept
thon en h does arq. ono. OAC what
guinmendi enath
Ar Votiabl 4
DATE
Syntax: lamba orqumsnth nprebsion
faamplc addlambda a.biatb
prin(add (2, 5)
add lam bda asb=7:0tb
Print Cadd)
helo lambel aja
print hel helo Vou! |")
1ambAamb daprint " Hllo. 13orld)
Printlam b)
Doumentation String /Doc srina:
Dot string in juat imilar to camment, Stale
iting
Rother han hi cing lik comano ntit Can be
dibplaed, wina-doc
Syntai def un (My):
doc-sting
prink (tun.--doc)
Example: det tuni)
this is cdoc-string.
itis mnultlin
Print ("hello You'")
det unename a),
Gioud Progzammnina Pratti tes:
D Make Ue o}Meanina Ful Uar table.
DInxrt blank in to bepanate BunttimclaAes
Cnd din pragtamming tonotaint
3 LUS CPpropriate cornmont in thi prngcam.
mOr abut hunton ed
6) uncttin namhouldbo writtenUn ooer
nom:
7) The laA nam hould he oriHe n a Airat
tertopttaloh
8) Sa ath-ond euen rnqtam ta at you irit
clAsSMAte
Date
Page
Chop- 48: Modoles
-Tntro ductian to Ho dules
Bscallu modude in python aHe pu ile in which
Modules aae im porttd used using importOMMONd.
The tomimport taBenent
Then are Aemu tandard un tíonaliHea
puthen that an oriten in pordiular in ndules.
to import the cOSp&nding module
pontiul or module, by ing on mporf we
mDdul.
R'4 mnport motth g
math sqrt 2 5 ) a t n l i
5.0
mathIN mpdule
sqrt CsaUare- ro0t) un otien o t
Syntax import moddename
module-Dame (uale /Exprcosibn/
rqumAt)
clssmate
Date
Page
2) Lan alb0 erom impor
but wwL tan onuo olected Vaiable m
Aunctibn pAUnt within that nodule
rom mnath imprt sqrt
pintSquanE roo(25)=Sart(2s)
haue mportd math module, buk
tt enl sqrt CsquaL-10ct) Hunctien
Suyntaxi Htom modename import fun nam
unnamlarqaumint/Enprusien)
Hoo to Ctati a Modue
program
Evtny ilt with .Py entension ib a module.
the e nam in Used 0 impert pntiular
modul.
Stp-1: Cttot a pth on le, cAtate a
functin in it nd a t.
det add (ab):
print (atb)
Swe this ile with nodl.pu
clasSMate
Date
Page
3hp-2; CHtae anothar pyth en filt, jmpori the
ile no
## anolhar python ile
ìmport mpdiAmodult in porked
modi. add io5) # ing tunchion
The dir Reintin
Tt i ud to din play uncind, Variahl2s
classes ubed i pantieulo module
print (Hello Yau")no
name Lutky'k
print (dir()) # Sauu his il as module1
|Name Apace
ENtaythina in pythen jbis iomply aabjazcd,.
nam
alasSmate
Date
Page
RAH)
hdm.
oucan inaunL
ueu nam wrd hor that ohects.
n Pythn eath nmodnle a namL,hs namspa
mD o it bintien and variablt.
(lobalLocal and Buit in Namespaei
qlohal ymamespate contain the odnte Lohith
Qunntly ene cuting
Ths Jocal namespace ç a namusp a on daining
the nomes
Thi Built-in nan Lsp ae À C nanSpace jn which
lub built- in hun ctien alihy can be iny ake d.
g. import math
det even.num num):
return nmhniteo
elst:
rturn 0
print("Eter Some nimber") hulin namespae
num= int input) # qabal nampau
itlevennum (num)= 0):
print ("Thi sauat Yoot of",numis" math. sart{num
cASSMAte
Date
Page
Private Nariable;
he varinblesAhat beon with Ao ndrstore
as priuoate voiobles
hat moduleothr odull tonnnt acess
dttadd (anb):
aa=253
--bb = 342
Saue the file as Mo dule-1
Voríable aa s a publio vania bBe, it cocan
be ccSs ed by othen mDdule als9.
Vai ablebbIN priyate to module it can't
he accDD b&d by gther modules.
python Packaqe
init py is used to ini halige Date
Page
Intre dustion to Packagen i
Githeray Pakaqes th talders Containing
Containe
mtiple e packoQes
packoges and modulta
A\onq uitt sub patkaaes ond modules, it
Contoios ohir python Sile andinit-py
For pe a holder, to ben packaq e, conpuborryt
houl be One -ini-Py yilele inn
packag and nib-padeag
My- Pacikage/
Hinit--py
subpacieoqtl/
int-py
-nodutel-py
-module2py
=module-5. py
-module-py
module-2py
=motrttpy
module-2.y
alAsSMAte
Date
Page
mport Hy-Packae.modlel
rom My.Packa a import modult-2
imparh My-Patkaat.. Subpackaqtl
Whon oe im port Moin Package thun thts
o to Create a Packagei
* (reating a Calulator or pr orming basic
opnationS
Step-l Crea a older namad My Hoth s. in
your ioorkina oldsr
p-2: Ihside ytaths directory create
gubdireories and initp le
So-3;Tnide Mytaths Greatea ub-diractory
aitaousle and a module namd as
adaiion, in adáiHor module create
print ( Rast b3-{c30
clAsSMAte
Date
Page
Stp4i Similoy, inid Myahs teate
0nohor Aub-diret ctory S Sb
no inside bub reat - init
Ahd a modul namsd as ubiraon
Aublr aimpy
Subll unctn a
det sublab
print f"a3-b3 =ic3)
Sep-5: Similaln~ide Mu\aths creade
a sub dirrctory namd as Kultiplitation
insidr muuA iplitabien crtatt intp
ile cnda modul mtipy ohd
mulla, b)osno
de mulaib):
Step- 6 Simil anl create Oiv ol dor
AuHatthin DiiN Crealeinitpy
and diusiommntule in it
dlint divtabntiem
print(Sa3bs =i )
classMate
Date
Page
|Sttp-1: The oeral structre o diretory
inikp
initpy
Lsubta ctinn subla.b)
-Mul
--init- py
multiplcation pumwlaib)s
-Div
--init--py
division. py 1 diylas b)
Step-B NoCheate a cdirwer pogoum that
pront in MyMath packagye
clAsSMAte
Date
Page
mport,HyMath Addaddiion
3kep g: impor MHath Suh subirackin
import MyMathsNulmuliplitatisn
impor MyMoths Div.diuision
MyMah. Add ad ditiomdd (20,to0)
MyHatths. Sub. Subtracion. Subl80,40)
MyMath. Mulnldipmul(20,s)
MyMathnsDi.divisiondiv (80, 20)
Step-9: noo run th program and out pul
Ail b .
20* S 100
Ro/0 4
pragram inished
classMate
Date
Page
Tntrodution to Stand ond 1ibrories
Pythan'a Slondad libray is veM emtensue,
The madula Hhat ae pre-instolad/deinad
1Jt can gd lot of Steun daxd Lihtorits by tying
he folauiing cmMand,
helo ('moduleS)
`gmi Commany used Hodules a
time
Sys
math
mai
yandom
shring
re
Socket
he punpos ok Atandad Aibrors modles j
o eneUMage and en hance fhe prorabilih
puth on programnA.