0% found this document useful (0 votes)
30 views25 pages

Ch3 Functions (C.S clw)

The document discusses the concept of functions in Python programming, highlighting their role in breaking down complex problems into smaller, manageable sub-problems. It covers the structure of functions, including their definition, parameters, and return values, as well as the advantages of using functions for code reusability and organization. Additionally, it provides examples of built-in functions and user-defined functions, emphasizing the importance of proper function calls and parameter passing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views25 pages

Ch3 Functions (C.S clw)

The document discusses the concept of functions in Python programming, highlighting their role in breaking down complex problems into smaller, manageable sub-problems. It covers the structure of functions, including their definition, parameters, and return values, as well as the advantages of using functions for code reusability and organization. Additionally, it provides examples of built-in functions and user-defined functions, emphasizing the importance of proper function calls and parameter passing.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

Chis Worhina with tunciiuns.

attt Gn dato and otten rcturns


value

’Aunction s a named unit


a qnoup ol sta tements This unit
(an be Dhvolhe (caled) frosm othe.
pars of the prbaram

Ry thon prsviles the feutures io


divide a Large proqram
difkrent Sraler proqrmThese
modules ate 6nswn as Functiuns ,
which have the iesponsibilit
r s uDbA cata Foe process tnq

’ Functions provide a Systemu tte


way ae problem Saluing by divdina
Civenpablem into severl
Sub pnobleas Ending their
Individalsolutions and
in tearating the Saltiuns
indhiu pro blem to Solve the
riginel problem
Fanc tiong Cure the nost
4) ’whi
Codei 3)pyihon
’A
Code
lereusabikity
Compact 2) jS
) buildinq
a/express in
Tun the Comnmon cleine Advantages
Functiozs? of
aPproach
COnquer
Python
heeircd be
CoQeand o Whtten Pro
IE
Fasy dealt 4yam
clled
pnarm Smell
Only a
e with
5ing
Wor
to upla Sense hanallin andblocK
Once
hisb On
y ith,at
locati on
Mase tion wors for
to fom Funcí9ns
whích Once Set
progrmming ana
changes. make becomes
parta n
ocode
any iS thedivide
Functions time app
Cnychange reducec Cnd kiction
Can be
Jo Part eas
prmgrn. ier
0verheuds ok an 2 and
ine time
C"Hi)
prind )
I2345L78
(a)
)A 3))int
(4.5)
-’G
2)
(4.6)Sir Funciunsi Builtih iculay
par in a) ) 3) )
4) 5) 4) ) Ex: tions
Fune 4)Mulles 3gpess
Functions
3
te Stan inportc
module
Exisny Buit User Bu
type Flo) : Fuhctions Jhese
Jhese
deved Sih
() be en cleine
in
()’ runctívn) n
c), C),
hunctions are
Can
’ used an
a unctini cdetine unctíons
Tupl OA SertO type Functions be
< 4.0 holule Cure pre
class
) ahen
Crepre clyailable C, Cateq
- E
'iht'> in
indO, lefinc orize
Functiuns
(onversion Conespundiny CLhcd
Iype Msdles:
-cle LilYvng
Fin inpudO For
For Se into
el
ling
lo) roun d C)- round a given nunm be
to he Spccikiehunbe
He turns thereslt

Jyni round Cn,p)


tx:
)) rouna Ci2.452)
1

12.0

125

|230

2) Functins n Mudule:
6) Mah Motulas

’Betyrns the Closest ntca er hat id


4rca ter hun r ca ul ta

) muth. (efh-67.8)
-67
Q) Floo.()
’ Retns the closes ) nteueer hal
iS Cesj than or

- 4G
>) meth. Floor (l00-22)
160

(3)po (g)
Ex »)nmalh-pue (S.R)

4) Fabs - (like modulus)


’ Returns the abrolute culue (ve)

Ex >> mathFab (- J5)

5) sert(x)
-’ Re turns Ihe se uare raot of
lhis unction Cac cepts
reater Hhan 2eO othe ruise
huntlme

Ex: S>> muth.sqrt Cas)


&.06aa577482455
baseiOLuqarith
3>>
atoLoa.l2)
math n
oo)
-0,4349424466
00
TL54
lo ot 6.J4)1300085
the
base loa CosineCus(3) (S)
the
Sin
e
sin
math muth. he math.
th the
Valuc
E
xror
’Retrns ’Returns
6)
loqio) 20 S >>
>>)
’Retrn 1.0
I0.0 )Cospe) Sih
)
Ex:
Ex Ex
)tan().
+ Return) the tangcnt oF J in radlens

Ex: mth. tan(3)


-0.42s46530 742778
)0her math nolule constantr

3.1415 4a65358A343

math.
e e i s Ca methematicce
Constaht repres enting
Eulers namber approxiaukely
a.718) T+ is co mony
Cxponenhal Gned
logaritmie caleelationf.

S>math.e
2.7)8ayl82s59045
B) Rundog Moclules
’ To Dick randomhumber,wwe
ranlom molles

)randow) (2
’1+ re turnj a randomloet
hmber of

0,28(4141343
2) randiht Ca, b)
’T4 rcturnS a nteyer X be tueen
a and b ,

3) randranq e(Istari, I Siop Lstep])


314 returns a randam item From
the aiven ranae
upperlinit nst inclusive

Ex:random. randrahee (100, lod0 3)


150

c) Statístics Module:
) mean ()
I4 re turms anth metic
anthmetic mean
Fx:>)
Ex sta tis is,ngun ,.3),4SJ
Wo 27.5

) mediun() Of

’ J 4 tcturns median (midle ralue


S>> stutis ticsmedicun (Il. 24,32,45,5
32
3) mode()
’ Tt eturn ole ( the most
Value) Hepeetel
EX: > Stati id.
Mode(C,4,32,11, 45)
User cdeFined Fnctions
.The unctions clefinel bu the
phg ruMmen for sOMe
epurpuse.
Syhtax:
del
Function_name(Paraneters)
Statement i
Statement 2
re turn< Value>
# optional
Ex
def Arta (racdius)
Drind
prihi C Arca ,S.I4r rasls
r= htChpud "Entev reclius:"))
Arca Cr)

Ouiputi
nter rudius: 10
Area = BAH 3J4.l6

’ The keyord
a functiun
’AEtcr the keyworl,cuYnes
hentiien
an
name the
paranthesise&
eist parme tersahd the by
Colon
Chdsup the eine

NextEolus
are he par t of unctisn

We can provicle
can_pro he parametes insile
the paranthesis hich t's opti oncl

Uhderstaninq Functiuns
clef cale(): Funcion clebintin
Parame tevj
return r
a= nt (hput Entcr a no, ))
pont (cal a))
Fanction Coll
Funcisn Boy
’Funeion healer

Defining Functionsi
AFunctisn ha tuomainparts
Functisn heuder
Funcon

’ Functin header
S= g Funetion body
Yeturn
Fwnction Healer:
Jhc first Linc of Anetion definition
beuinsaith clee Cahd cndinith
Colon

Paramctersz
Vanab les hat are listcl urthin
he p ranthesis o a Function hcacler

FahctiSn Bodt
-The blocks of Statementr in deted
Statements benea th fune HRon header
hd ketincs he c ctlon yerformel
he
by he functiun

)he functiun boy may hst


return ny alne
wiay
hsug h return
Statcm enl

Indene ion
· The blunk Space in thc
of a Statemcnt uilhn beginaing
A Statcmen ( within Scme blocls
have SCame hclen tation

Inve bing / aseny a fancion i


o ure ca Functiw }hat h s bcen
c arkier ,
heneral Fyrrmut:
pararneter >)

Jn fanction Cu

calc (5)

) Passta Vaniables as SLSsiqhments in


function call

Calcla).

3) takiny input cnd pussohq the hput


asarq ulMent ih uhc tion call

Ex mynum= nt linut"Entor no.

4) Usie funcbion Cal Si de ahother


Statemnent

print (Calc (3))


sing Fnetien cal asile Ckpressiuc
Structre of a Py thon Program
Tn pyhon prog ramnng Jenerally
all Function definiions are qiven
a ) the top Foklowed by statements
stakem
uhich ate not part of Gn bunctiuns

By default, py thon
py thn names t e
Scament uith top lavd statements
asmain

def function] :

# top level s tatcment here


Statcment l
Statement a

Flow ol execuin in a Function call:


" The Flow o execution he Fers t
4he or ler h which Statennents

prodran

a pyihon, a block is ercwted


Inan executiun frame

An execuhi hram cuntuins :


inteYn information (used
For cdebusging)
’ Nane he Fun tion
7velues passel tohe FuncAivs
\aríables CHeatelithin the

Function hext slnactiUn


a b t the
to be execte

ald
functlon
hunabers thugh c
def caleSum Coc,y)

return S
hum) floallinput C Entey Lst no.)
5 num2 floutibhut l" Entor 2nd ho. ;
6 Sum calcsum (numl, num2)
7 phht

) FOo oh execuioni

Frquements and Parame ters

Hrquements python refers to the


values being passel
throug h Fnction call) as
bnowh es actuapurclnettrs
actual arq uehmehts
Parame térs Value being rceives in
theunchon detiniisn
also knonh as
-es Formal curquemen tt
Passiny Parameters i
Py thon Supports three ty pes o
Formal argue ments parameert

1) PosiHiona arquementr Reuices


Araueentt
)Defauli curq enments
Namecl
3) hey wsrcl arquement
Arquements

) Posiional/ Bea, uircd Arg uements


’whtn you craatea linctione coll
Statement for a Qivenrunction
you
definitio n , you need o match
he n mber OF Crg ucbentt Luith
hum ber ot parame ters hequired

Fx:
clef check (ab, c):

ChecsCXiy,2)
Checs (2,24.g)
checs (2,5,7)
prvtded
he arqueng ent must b
The
for al parascters

he valueJ cf arquerionts Cie


hi4tched uith parameter 3 pusiho
Jettte. wise
lhis way of parame ters andarauement
Specification is calel PositionL

as no kalue can be Skippad bom


the func tion cell

2) Default Arquementrz
Py thon cllows
Ossian dekault valner to a
functto 's parame ter( . h i c h
usefud ih Cue matching Cunnement
pasel inFunctisn call
Statement., he dlefaut vaics Ave
Speuifie & in the fnctibnheaclers o
functisn cletinition
1 Non default Orquements Cahno
follow default crg
Cirg uements
Ex!
det
rcitP,t R OD):
ST = in eest (l0o0,2)
parame teik
¥ HDarament
dealt value ih having header
Fuhction
a

becomel optiOnak in Functi onal cal0


Functisn cal may. May not iree
have vele For it.
Arguemnts
3) Keywored oe Nam ed cont and
Jo huve COmpletc
Ouev the values sent
Elexibikits or the Cuneipo ncding
43 Erquements
purameters JPy thon oFferT another
werl
tupe oF arguementr bey

guement in
any
Orlen phvided J u ile the
name arguennentt.

Ex:
intercst+P=20 o0,¬- 2 n te = O.lo)
ntercst (t=2 rate = Oul2, P-dooo)

Exerise:
Chunae (a bic,d):
m mat (a,bii)
nmin (a,by cocl
t a intupe wernnt
mbine hutiphe
ara Call
e ACtytpesarguementtoyou alwSallows pytnn
Mul i ple Vsing
34 38
34 30
30aO
Ouiputi
(2g) prht
abcly) X
(,y print
priht,y)l) abe
abC(,y)
atb rctun
bi4)i (ara abc def
Output
ghyi) prht
ntur he
def interes( P, t2, rate o.09):
re turn Pt rate

jntenes + (5000, t 5)
SI

Rales For combining al three typesE


Grguements i
cont
Arque ment st must firs Contain
bu
posiional cerguements slloeel
ahy 6eyword arauements
shoulel be
b Bey hord Ctyuements
takenfnm the reg uirecl crq uement
preßerably.
* You cennst Specty a val ue r
Cn arg uement ore than

Returning_ Valnes Pronm unctions:


Functioni in Py thon
re turn Value

) Functions returhing Some value (hsn


Void Functions

2) Functions hot retarning Cany


L Non - Void
unctions
The Funkions thut e turns some
Computed result in tems of awaluc
sing hetura tate mnEnt

The vaue bein4 returael Can.


be a literal or a vaiub le on
n cxpcssion.

retumG
returna*3

The returned value Gf ca fuhction


Shoull be usel ih the callen
Eunctionproaram insicle
expression 0 a State ment

Ex:
addes ult = Suum la,b).
prink C Sum (3,4) )

doa not use their value


in Cny of these waus
andus t
qive a Standalone Function Call.
Pythan will not rer port CAn eror
but their re turn is
Chmpletely waste&
’ Functions hcturning a uelue are
known as Fruithul functions .
The retun state men ehds
Puunction executton
in the midde ol the tuncton,

’ The Fun ctions that perfora Some


Qcion but do
not etur any completed value
callae vot Fnctiuns.
They art

def qre et C):


priht ( hello)

’Void Fun chion but no return


Statem ent

def qreet(namne):
print ("tello,nume)
returo

’voi Functiun with returo


Statement
(3) The void Func tien return

a alue but they re turn


Legal Cmpty vclue
(.c) Nsne

The pussible Combin ahon of functiosi


Functisn uith sut
) Noh - voi
ar uem ent
ang
function with. Some
ara ueMent

3) Vid functionuith

9 yoid Func ion hithout any crq ulaen

Retuming Multip le velei


Jo return mulip le vales rom Function:

> Jbe teturn Statement insile aa

function bocly should be


re tum val, rala

Jhe Fuhcioncall statement should


receive ase the returnel vaes
the follouing Lways
(a) Either receive the he turne
Values in yrm a tuolg variuble
Exi
dek squared (X,y2):
return t , y*y 2*2

print (t)

Output
(9,9, 16)

(b) You can. directly unpach the


rec eiveul kelucs o tuple by
Speciyinhg the scune nwmber of
vartables on the lethand siee
OF the ass ta hment inFunction Cell

Ex:
def seucrecl (xy. z):
return t , yxy, 2* z)
print (The tcturn e values are 3
print V), Va, v3)

Cormps ition i
> Compositioh in qenerLl re ers to ustn
an
expression as past part
Larger expression
as a part
, Or a stoatemet
o arer Statement.
Ex :
2. tess ( a or b)
3. int ( str (52)
4. ini ( FLoa4 C"5).5")2

SCope ola vanalolei


Scone of a variable iS the por hon
oF a pnq ram where the variablo
iS inC re Coqni2 c

’ Scupe haeans pat ot a prqrzm,


in which a yariable can be usel

lape of Scope ?
DLocal Scope
Jhe vaDubles declarcd insiAa
the Fun chion clekinition are colled
Local variables.

dek Fun ct C)i


L=Q0 local Variable
print ( Tnside Funct'...)
Funct c)
Outputi
Lnside Funct...0
Dlobol Scope :
The variables leclarel utsi de the
Punction cleinitisn aCAte ccllel Galobal
Maiables

B=30

poht (A:A
prnt "S:B)
Punct )
Funct,B)

Ouciput
B:30
B outsile of funt 30

’ Yaiables ith Same s

declarcal insilo co uell uS Outrie


the Fuhctbn

EX:
der unc C):
A50
A)
priht (Tnsile Fnction :"
A
Prh+ C"outside hunetion

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy