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

History of Fortran Programming

The document discusses the importance of functions in programming, highlighting their role in modularity, code reusability, and ease of maintenance. It explains how functions can simplify complex tasks by breaking them into smaller, manageable modules, which can be reused and modified independently. Additionally, it covers the syntax for defining functions in Python, including parameters and docstrings.

Uploaded by

Daksh Dhanraj
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)
32 views25 pages

History of Fortran Programming

The document discusses the importance of functions in programming, highlighting their role in modularity, code reusability, and ease of maintenance. It explains how functions can simplify complex tasks by breaking them into smaller, manageable modules, which can be reused and modified independently. Additionally, it covers the syntax for defining functions in Python, including parameters and docstrings.

Uploaded by

Daksh Dhanraj
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

:,rt.

i(

fll n t'tion is similnr tt\~ u _Erng1·nm I hnt ,

A
( \)t1 ~ 1~ t ~ t,1 n
1
n te-ndt.'<i
-
to pt.'tform n SEt'C'ifk tnsk. Tht' P1 , · •
, - -
g 11111p nt :i 1111, ,111 •11, .. II
, pedfiC' tt,sk or work. 1 hus when th 'r', t 1n
- J)\trpo~. .. 1rt1 11 ,,.
s . . · 1 0 1 n 1111111 1011 1•1 111 •
. t t n,,, ~1·v,•rnl t
u11n1er will wr1tr Sf.'Vt'rul funl't ions. 1'ht•rr nn• ,, ' p,, 1rn111 ,,
rosri - k 1.~ 1\:-\ka It> h1• llt'if111 tt11•d II '
P r on vin-ious tns -s. ror 1.' xnmplt.' to• d•"l"ln •.. , v1'rnt 'b11i11 111 . •,
1111( llnti ·Lill ,f·•v
, "
peno ' '" , v output n.. ~ 11 11111
to 1,,.-lv. to colculatc squnrc root vnh.1t', ther1.' h~· ~q ·t() • ' • ~ 11101 1 1111 H p11111() Jt, , lion
there is power () func u· on. -::-1m1lnr
s1011 ,,.. • 1 11
to tht'St' fu• 1 ,i ~ i1nr 1H)n n,11I t o , 11,I 1it, i1 1 pqw,
r-<• •

,,a}Ue, - . - ' It 1 1
• .., functions which arc cnll0d\ 'uscr-dc-li·i" 'ct' l011~ f '
() pron1 II
,., 11111 w 1 111 11 nlno, 11 •111 ,,
h1s 0\\ •• '- •t lllWI io 11 Tl
rnges of functions · w foll owi11K 111,• Iii,•
sd,·nn . $,

C', nctions arc importan t in progrann ning bt'cnu',


r "l . 11
S1; '\Cy 01\' tl :kcl t
ake cruculotio ns or perform any [Link] which is t't' qu · ., . · . 0 P 10< <•.,., t111111 ,
rn ~ .· .- Ht:(1 111 l 1w sol1w11n· ckwlop, •
Once a function 1s wnttcn. 1t can be reused os nnct wl, ~ . l ·. , 111 111
- ' · ~n I cqq rt.:d So ft111 •t
also called reusable code. Because of this rcttsubilir- , he )ro . · · ' 1011 " 1111•
~ . . . 1 g, nm
. 'J' I
redundan cy. 1t n:ieans 1t 1s possible to avoid writing thl' som e cod, mer rn n nvo,d c·od,
. .
. c ngn1n nnd 11gru1,
,,,/ Functions provide .modulan ly for ?[Link]'\ming . A modu le rcpr~'iwnts po, of llw
✓ program. Usually, a~amm er d1,11des the mnin tns k int o s ninllt•r s ubO l1tsk:31 cnlli'd
modules. To represent each module, the progrumrn cr will d cwlop 1\ ~cpnrn tl' fllnct,cm
'Then these fun~tions are called from a mnin progrn m to occomplish the c.' OThph•tc•
task. MDdular program ~ng makes proi;,r omming cnsy. ,t '1 , }A ,. / ~
1
~Code maintena nce _wi~l bec01T1e easy because 01: functions. W~c n o new fl!otuH' hos' to
be added to the eX1sting software, o new funclton co n be wnltt•n 0 11d i11tcg1 nlt'cl into
the soft\vare. Similarly , when a paJticular fea turC' is no more necclccl by the wH·, , the
correspon ding function can ~c deleted or [Link] into commen ts.
a W}len the re is an en-or in the sq,ftware, the correspon ding runr t ion co n he 111o<lif1t•d
\./ ~thout disturbin g the other functions in the softwnrc. Thus <:_ode cl<'bL1ggi11g will
become easy.
a Th~ us;-of f~[Link] in a program will reduce the le ngth of·thc prognun .
\.
238 tflaJ\l'i"'I Q

een a function and a Method


I'\ ce bet,.v~. -t· n grou p nf ~tlll cmen ts Im (1 J>err
Cl111 toit1!- ti
[l ft1/l h t'I flllH 10 .
progrnm Otrna
.
..,
i,
d 'l.l!C~rd 1 nl 11 be. ,ni ttcn indivicfuolly 111 o· Python · A fu
nc-liCJ
ri
'Il-
\\e ,~, f nrtion 15 ,,nt trn u1s1d c a clAs s ·r be
:1 [Link] ell ,,,_...,-_... -'-'tl ~8i: Qrn c 0 l'I 1
l d, '' \\' hen il u the following ways . , 1
il~ nllllll'• f lq,,t~t.i;.
U" n£ - 11-d us1118 onr o () 1
~ ) S (\1 t odname
mc-11itX - 11teth A
[Link] ()
h t 8 function and a method are sam e except th .
classnaine · will 1 h e1r Pl ar~ . . .
ember t a
ed In tJ'[Link] chap ter, we. earn ow to creat ··,eri
~ nlc,1sr rem . e 8..nd
~,. r- • are call . func tion or writing llct" t li.1-,.
,, a, the) , ting 8 ft JDCu~:on means . definmg a . a fun (°Jilt ~
tIlf • ct100 vt...
ft coons. Crea . be used by calling the function . . f>t, ·q
in 1 is defined, it can •'
funcuo1

_.a. . a Functio.n sing the keyv..'. _, 1 , followed by fun,..,t-:~-


De11ning fu ct10n u .. ~
may cont ain
Jer
'-[Link],llaJ'n
[Link] ~- ¾te r Ir
e a n uld write pare nthe ses whic h
L/ \l e can defin
11
11 -e shO
," .
__ 9
shown in igure .
1 ·
.
.--r.,-~
eters
. Cons .,
function name ld'r
. f tuoctIOn, as
the synta 0
X example

runcdon dellnltfon ~- -- -7para2, ...) :


def sum(a, b):
"""Th is function finds sum of two numb ers'""•
( para1 •••• c=a+b
f runcnonn11me
de ••• tundl<>f1 docstrinl pr1nttc)
runction sllltements

. 9 I. Understanding the Function Definition


F,gure . •
. function to add two values as:
an wnte a
For example, we c
.. , ' . th
def sum(a, b) : ~.-hng of function defi rutio n. sum 1s e name of th e fun ti
'd f represents ththese e st c1.1
Lil'
as they deno te that it is a function. c 0n.
);!ere, ~ s ( ) are com puls ory
After this name, paren thing else.
. the pare nthe ses, we wrote two variables ,a, anct<lnd b'
-------- . . d .
not a vanable or some alle aram eters A para met . er 1s a varia ble that receives
ata fro
'abl ....____~ . -
These van es are c es from outs ide and Ill
[Link]:Ii·oonn ..-SO
. , ;,..,1-" <>fun s ction can receive two-valu - - - -__ ; those
, , , - - -
o u t s 1 d ~- '.
v~s are stored in the vanables~ ·
ts th~ ~n- ~ of the functi~ .
After parentheses, we pu~ a colon ( : ) that repr esen
g , . [Link].:. Generally, we shou]
The function body contains a group...of"-Sta~ men~
body . This strin g is called a 'docstrin d
write a string as the first statemen tin the func tion ~
ember ~st rin g is as~
that gives information abou t the function . Please rem j
function or class. Docstrings
that is written as the first statement in a mod ule,
e single quo tes. In our sum() function,
generally written inside triple double quotes or tripl
we wrote the following docstring:
""" Thi s function finds sum of two numbers
111111

'P
~,,(; t11\1 ,Int (11,tv 0 11( Uttr. l lu 1 J11ft fl
•1 ,'1
n,,
., !lh
,r} I , Al'I
'O '4
•hr r dor1tr-,ncl' o,1. o1nlo,rn1 r1
(/\ppl I{'filltl ll "'"G•a1n,11111 1111
I
w I lit \\, I
'''<'ll!lt IfII '"" ""i"
hi 11111 ,,,
Iii
I IIf flit
I' nil ,p I Ill, II 11,, 111 ,,u riv,,, fr
,,?'I " omC nnd l1nCB1111,H " ', Aln, ,,,1 li1" n
ot\ l1 • 1 1 · liq I Ir I I
ilt1{ l lf11r ltft11t1i11 111, I
~ f ' I f,,
'
•ii•' mu w,,1 ms , '"." ' .
.~ft,f. rv11M a ih~--,--
"'B• '• " """
t p, '"" 1••11,1,11111 ' i, ,1 i1 t
"'' p,i,,,, , , .,
dnCH11111 g 111 llw 11 lj •iur ,11,1111l11u l,111.,1
,,•ot111,, (t I I
1111 111 ,, 1111 11,•111 bl I
.-,nr.r n~titut<' 11w OHi( 0 I 1( 111111 111111 11 I , ,, ft ,,, Wtlt, ,,,,,, I Iii ii
~ l~ I J l - II m.f11
"111° 1 t~ i-ho\1 <, >(' w, · c llli H 111 upt, 11 11I • I " '""' I In I
"'W 111 " " llu t ,•11 , flt/1111,i
11'1
,r.n • 11 , 11 1,,1 1t11 1 "
11 't,111 , lif11111,1, w, Wt , i I ,,1f
,
f two numbt'r~. c·n t c•, llw loP,11 W111 1111
~Ir,t": ~ll 01 0• a + b
ct11tr.1
' f If I I (j llf(I I

~rint(c) , ,, ,
tcrs 'a and b rontmn llt1, vu li 11•11 wl 11
aram<' . . 1 < 1 1111 , 11d,1, d ,
111e P1 Then the result 1s d1splnyrd 1111 1r 11( 1ltt• 11 1 . () 1111 1 11 ''' 11 111111 111 ft l,u t ,
1 111 11111r 111111 1,
11, 11 ''Ii 111,, 11,11, , ,
c' . 1 h , 1
8 _ vaJues and d1sp ay l cir MU111.
ccePt ·two
into 1 1

111

ing a Function
ction cannot run on its own._It run~ only when wr n dl II . f)o, ti,, '" , 1 ,i, I' " ,,, 'oil
A~ ction using ,tsinname. While calling the function, wr """"'" ,.,., ,, "',, " "'Y
the ____ - the parentheses as:
aiuesnto the _function 1 11
V s um(lO, 15)

re we are calling the 'sum'. functiond and h passing lwo vult1ct1 1o 11 11 (1 1r; 1,,
He '. When this statement 1s execute , t e Python interpreter Ju1r1po In 11,,, 11 ,, 111111 1,,,
11
runcnon-00 d copies the values 10 and 15 info the pununctccu 'o' 11n,1 'b' 1esµr, lively11
::_: ar
defin1°-values :£
,.. e processed in, -the function body and ret:11111 h1 obtnlni·d. 'Iii,· v11li1, ,
fhese to a fun~tion are callecVarguments'. o, _10 and 15 arc orgun1c11t11. 111 l'rov,1111n I,
passed . the 3 um() funchoh-diecl!§se so far.
we are showing '\JOl..., Jo t'.._ ' f°'J"'.J.
' .k ~QJl.J /Jl•t
. that accepts two values and finds their t:1 urr1.
1· A function
,rogram ~unction to add two numbers
~ei sum(ah, s unct,·on finds sum of two numbers
T 1_b)f:
111111
111111

c = a+b
print( sum= , C)
I I

# call the function


sum(lO, 15) ) # call second time
sum(l. 5, 10· 75
Output:
c:\>python [Link]
sum= 25
sum= 12 •25
h t\.1'X'-' f , u
no t kn ow w h
n r> 1 1
th e r m e f c. oJ hn g th e furlC"t <> I t
d 91 or rn , t
in t 01 rn ay Ix- flo a,
t\1?£ 0 da ta . m ay be ,n d
!'
c f)~:>C nf do (A 19 d<'t r:rn th< n
[Link] c
dv na m 1c l.)':J)U:ig. tb
Dy na m 1c tv p1 ng ,s on e <>f th e rc
a1 ur rs of ,~
1
ro m pd e trm
~ ~ ___...."""•-" 'r::::' -; I Q ._ .~ p f
tng UB g (lake

~ n in g R e su lt s fr o m a F u n c ti o n
Retu fu nc lio n m th e u si n1.: n •,c tu , n I •tr ill
su lt or ou tp ut fro
\A( " ca n re tu rn
th e re fl
Fo r' c x: 1m pl e ,
bo d, of th e fu nc tio n t of fu n c ti on
re vu rn c • r et ur ns c va0lu e ou
re tu rn JO O * re re tu rn s 10 li st th at co nt ai n s va lu es
r P- ~u r.n J st # ~u rn th e lu es
# re tu rn s 3 va
re tu rn ~. y. c w nt <' th ,· r e t ll r n t 1
no t re tu rn a n y r es ul t , w e n ee d n o t ch L trrnrn
es r s um () fu n ct i on su
\\' he n n fu nc tio n do . w e
·11 e w rit
r
.
e ou t nc , t it
Wil l rt't
Now w1
. . d on e 1n .
m e bo dy of th e fun cn on .
I 1n g
. Th1s
1t. 1s Pr og ra m 2
ih e su m va lu< · r:a r h er t h an d 1s p ay

----=
Pr og _r a.m 2 : A Py rh
th e fu.r:h.. t..on.
on

; a f un ct i on to ad
pr og ra m to fin d th e su m of t wo nu

d tw o nu m be rs
de f su m( a , b) :fu nc tio n fi nd s su m of tw o nu m be rs
m be r s an cl r <.:t ur n tf rrs uJ t fr

"" "
ic

.... .. Th is
c "" a + b # re tu rn re su lt
re tu rn c
• ca ll th e fu nc tio n
, 15 )
x .,,. su m( lO s : ' , x)
p ,..., n t: ( • Th e su m i 5)
Y 7 su ~ ( l. 5,su m 10 .7
pr , 01: ( Th e
i s ; • • y)

(.. 1u tpu ,
C : ,p yt ho n fu [Link]
r he su m i s : 2
5
12 .2
Th ~ ~um is :
,ht nb0' re 1> t"t"gt 1' '" ' the l •!Su lt is
,., ,n'lcn' ~ tt"h. 1tn" d bv t' Zt I
pl<',.. rlr> Bllrn () f
!1 retu rn ll fl( t l(Jfl th,o
•ah .
a\1
we C the func tion ns:
,,rhc:11 sua (lO , 15)
:,c •
ult retu rned by the func tion com es
'"'e res n1to th e ..,, .
tP . as:
fvOction • sUll l(l.S , 10.7 5) o, iublc •~· S
. , i1nil nrty, wh,·n We coll thr
y rned resu lt will com e into y•.
'{'tle retu
ders tand the con cep t of func tion s .
fo un s Let' s writ e a func tion that ace tn
~aJl l. . a bett er wny we ·11 .
pr~~ h func tion defi nitio n can b e Writ te epts a ' w, WrJl<•
e . num ber ond tests h
od d · T def even _od d (num) : n as. ~• 1 t1plr of
· w <'thc r 1t 18<.:< ev
en or
bser ve that this func tion has only
mea se O
P d to [Link] W w h e ther 1t
· · 1
1s even or odd . If 'nPara, rn eter · ,
teste_ ther wise it is odd . This logi c can be Writ . . '. i.e. num ' who se- va l •.
even , o umt is d1v1sible by 2, then we cue •~ t,'. t~e
·1 f num % 2 === 0: en as: an ~dY ll tA
prin t(nu m," is even ")
e prec edin g stat eme nt, the '<>/o' oper ator is call
In th . . s1on
. . If th . d er
d
. der of d1vi e mod
retna ln e rem

ain
.
is o· '
then . ulu s oper a t or t h at gives lhe
we can d1sp
. . used in even _odd () func tion m Prog ram la th ,
10gic 1s 3• .
Y at num , .ts even . This

PfOgralD 3: A func tion to test whe ther a num


ber is even or odd .
1 a fun ctio n to tes t whe ther a number is even
def even _od d(nu m): . dd
""" to know num 1s even or odd """ or o
if num % 2 = 0:
prin t(nu m," is even ")
else :
pri nt(n um, " is odd ")
# call the fun ctio n
even_odd (12) • ·
even _od d(13 )
outp ut:
c:\> pyth on fun .py
12 is even
13 is odd
We wan t to writ e a func tion that calc ulat es facto
rial valu e of a num be r. Supp ose, we
wan t to calc ulat e the fact oria l of 4, we can writ e
as:
41 • 4 X 3 ~ 2 X 1
242 fChapter 9
SO. ,f W~ Wf:l:Ot
nl • n

calcul ~t e fa ~ 1 or i ~ l
llft'ra functio n to
):. i a1 va1 V£: ,,,w
def fact(n
,.,,,. to find faccor
prod==l
while n.>=1:
prod*.::r n
n-==l
return prod
. factor ials of first 11J number~ Ju
II d,splaf y () functio n and pass the numb~r ~ -frr/', J ~
# call act (l li)·
for i ~n r(~nF'lc,e to~ial of{} i s {} .fvrma t f i • fa ct:t'i ,1,1J
1

print ""'
Outpu t :
.Y
c: \ >PY!hon fu n,P
Factor ial of 1 1 5 1
Factor ial of 2 is 2
Factor ial of 3 is 6
Factor ial of 4 is 12420
Factor ial of 5 is 720
Factor ial of 6 is
Factor ial of 7 is 5040
Factor ial of 8 1s !0320
Factor ial of 9 ,~ ~62880
Factor ial of 10 ,s 362880 0
W e will write a. program t h at a..ccept.<, a numbe r ,c1nd. 1 te5t.e ·Nhethr: ;r it i·~ prirn~; ,.,,r :-i,, ~
" ,J -,/

r ';;rc..eo• _ .
know a prim e n u mber js a num ber that i',. not dhrhtb e oy bny 0th":;r n..,rnl,;
r nJm~;- ~ :
and itself. For e r..aJnp le, 5 is a p rime numb<: r a•,. it 1-:. not d1?b1b le by anr..,the:
1 and s d i vide t h is n o m ber as 1 dhrJdc~ any n..1r11br:r .and bn7 n..irnbe r d,-✓,,J~"
n.s-;t: •~ -.
~
and 5 n eed n o t be coun ted in d eciding the di·✓hib1fit-.1.
::h r.J•her nurr.c-,
To d ecid e wheth e r 5 is p rim e o r not, we have to di·.ride !:his nJrt1b' :r •,m
ff .5 1s dl', iS?~k: -~.;
e x cep t 1 an d 5 . Jt means, we have to d1vide th1~ n ......rnoer by 2, 3 ::,nd 4 .
2 o r 3 o r 4 , t h e n w(; can -;ay it is not prime If 5 ;!:> n<.,t div1s1b Je U'.f any
n·JmY:: r fmrr. 2 -~
r 'n' i<;. pnrne or no: :~ ~
4, then w e can say it is p rime. So, the Jog.k. to kncrH 7,he+he
r :n •his rar~e
d ivide t h at n u m b er w ith all nurnlY.: r~ rr,.,m 2 to n-l. If an_y <.1ne numbe
,t 1~ 1101 pn111c-. otherwis
/ t. thrn .. . . c 't is Pnin ,
It I in rMQcl2, n) .. fl div · C 11,1$ I
,· z,of 1~ n~i a• 0: * if div;s1dbe
~
n fro,..") Ogtccanb
1
, ,. " • • ,.
t,cr ,s d1\·1s1ble an) nttnib .
l e b "' < nurnb
Y tll'\y
to n- 1 . Wfnten
1
• ,u,n ., er , n • er 1 t
:l \'nnable "'< . On lhe otl 111c runr.,,, r
•t'' l)t<
int 0 • • . icr h . <>• rollt 1s not , r i lte
,, ,1-•t'<' tl tcs w heth er 'n ,s prune or not . C and, ,r ii is Pr 2 to n - l • •t 1sO •
t,.-f' - ,ndtrO onR1der Prog . '.tne, We keep c...., nol Ptunc enct
,-,~it rullt S ' • •• I ThUs '>,
A python function to c h eck if .
5: a g1ven n
...air-'° function to test whether a nu b Utnber is Pnn,e
,.. I a rime(n): . . rn er is Prirn or no1.
def P, .... to check 1 f n 1 s Prirne e or not
# this will be o 1·f O r not "' 111
~~~ i in ~ange(2, n): . # ~n-~rirne
if n%1 = 0: # 1f di vis~ b~ n from 2 t
x=O
break # take x as O , e by any nu~bn- 1
er
els.e :
X=l
return x # else take x as
1
t if a numb~r is .Prime not
#numte~- int(input( Enter a number: '))
or
heck if ~um is prime or not
# c lt = pr1me(num)
resu l - l ·
1· f resu t - ·, • . ,)
print(num, 1s prime
else:pr,· nt(num , ' is not prime')
output:
c·\>python [Link]
·Enter [Link]: 5
5 is prime

tion prime() that we developed in the previous program can b d.


um
The func ber series.. Suppose we want to generate the first 10 Prime numb e use to generate
th th
rune n . ers, en e
munbers starting from
P . 2, 3, 4, .. .. etc. . are passed . one by one to Prime() function. This
[unction returns 1 if the number_ is Prune; otherwise, the function returns o. When the
.
. n returns 1 ' that .number
[uncbO .
is displayed and counted . When the function returns ,
will not count it as 1t 1s not a prune number but we will pass the next number 0to
prune .
we_ () When the required number of Primes are generated, we will terminate the loop.

~to test prime or [Link] program that generates prime numbers with the help of a function

# a function to test whether a number is prime or not


def P,ri me (n) : . . not """
"'" to check if n 1s prime or
x=l # this will be O if not prime
n):
ange (2 '
r i in~r :,if$ o:
fo ·f n~,
, xc::O
break
else: 1
x===
urn x ·
ret ·me number se~~1~es do you want? , ) )
erate pr1 ('HOW manY 2
I ge: ;nt([Link]; value of primes
num # start W1 ts the no·
c:1 # t h.~ s coun
;-2 forever d. 1 ·t
# repea~ . is prime' , sp ay ,
while rru~• co: # ,f ,
if prime (') ter
priit 11 ;ncrease c~~~ number to test
c+=== # generate "exceeds num
i+===l . # if count f while loop
if 0 num, # come out o
break
output:
c:\>python fun.p~o you want? 10
HOW manY primes
2
3
s
7
11
13
17
19
23
29 b rve the following if statement
I the previous program, o se . .
n . . (')• # if i is prime, display ,t
1 f prime , ..
. t(l)
prin . d . ,.,
ailing the prime() function an passmg 1 value to it If ~•.
In this statement, we are c . thi if . . i is a
. th th function prune() returns 1. So, s statement looks like thi .
pnme number, en e s.
if 1:
print(i)
Please understand that Python treats 1 as True and O as False. Hence the above
statement reads as:
if rrue:
print(i)
Hence, the print() function is executed and 'i' value is displayed.

I
~eturning Multiple Values from a Function
' A function returns a single value in the programming languages like C or Java. But in
Python, a function can return multiple values. ·
Wt ( Ill l t

. flll\ ('th'H'\ ht\$ two p nrn tn1...' kt' $, n t llw llnw ,11' ,·1
. ~ thR~
.:11\ "' \\ll1\tJ. I h i f
w •U'tlC..'..,;'
1 , ,,_ ~ H~ . H lll H 11011 , W( ' t1lio u ld
-~ twc..
pt\:s~ 'i~ • sum_su b(l O , S)
,t, .-1 ct·t·
'·t1 lt o f au
the t't:t- l lOt\ w l \\\.'
. l '\ · ·
l$ ln ·c-· will b ' ·t . I '
- .
t,loW, . whic h is in 'd. w1\l bt' :s tor1...'d into 'y'. '\'hi$ \.is ~~he,
n h ·t 1111 0 'x' I
w9c t10 t1.
Sllb l ' ._ -
_
~ '
,
wn In · n n< 1lw
P l'()ll l'(\ tn 7

fl/!/£
,... •

.JiograsD 7 .· A Pyt hon progrnm to undc r stn nd how n function . ·t


a
1 f fun ctio n tha t ret urn s two res ult s •~ lit
.
n ~ two vn h.,c~ .
sum
de """ _su b(a~ b): .
thi s run cti on ret urn s res ult s of
add itio n and sub tra cti on of a, b """
c = a + b
d = a - b
-•re tur n c, d
# get the res ult s from the sun
X ¥ = sum._sub(lO, S)
[Link]() fun ctio n
#' di sp) ay the res ult ~ . . "
rin t( Re sul t of add itio n: , x)
1

~ri nt( "Re sul t o; sub tra cti ~n: ", y)


Out put:
c:\>python fury.~Y
Res ult of add itio n: 15
Res ult of sub tra cti on: 5
When sev eral res ults are r e tur ned , we
c an re t riev e the m from the tup le u sing
while loop . Thi s is sho wn in Pro gra m a for loop or
8 . Thi s is an exte nsio n to Prog ram 7
.
@ .
s -~
~
~d i\ on
A [Link]
tha t ,-et um s trit.1ltiple res ult
s
s b
thal rct'urtl" the rcsulta:: of ndd it, 011 · u tr ct

, a f~nction 1 di~(a b) : ~d 9it ion ,


def ~~ sh f/~uiiction mu 'ret~rn~ re~ ult s ofd1v 1sion of a b ''••~
}ubtraction, lt1phcat10n and I

c ., a -+ b
d=a- h
e ., a • b
t =a / b
return c, d, e, f on and sto re ;
I et results from sum_sub_m
ul_div() fun cti nto t
~ surn..sub~mul_d iv(lO , 5)
1
p
# display the res ult s ~s1ng for loo
J>rint('The res ult s are . )
for i in t: , ,)
pri nt( ,, end= ,
ouiput:
c:\>python [Link]
rhe resul ts are :
15, s, 50, 2.0 ,

Functions are First Class Cbjects___


rst class obj ects. It me an s we Can user
In •p..,L .1.11,J..._~ctions are considered as . ·
tho n interpr
1
eter _l ncbona
L
cre ~te a fuJ:!ct1 on,_ the _~
~ as(Perfect object In fact when we can pas. s .a fun ctio n to an oth er~a l~
fu 'J
ns are object s, we
/ I/ , cre ate s an ob' ed. Sin ce fun
ect
ctio
(or value) to a
f
unc
. Al
t10n. so, 1t 1s possible to retu.r
n~ 11
"'"' JUS t e we pas s an obj fromn a funcban
the r fun ction. Thi s is sim par to returning an object (~ value)
· from ano , a function,
owi ng pos sibilities are not ew ~rt hy:
The foH
o 1t is possible to assign a fun ction
to a variable. ' • I
. • I

-!:l It is possible to define one


function inside another function.
as parameter to another fun_..,ction.
V o n is possible to pass a function
return another functi ~n. ' 1
a It·is possible that a fun ction can Program 9' we have
ers tan d the se poi nts , we will take a few simple pro. grams .. In
To und . ction is called
a fun
.
ctio n by the nam e dis pla y() that returns a strmg. Thi s. fun
taken and
retu rne d stri ng is ass ign ed to a variable 'x'. ')
the

~
Program 9: A Python program to
see how to assign a fun ction to a
variable. '

# assign a f unc tion to a variable


def display(s tr) :
return 'Hai '+str
' 0f
nd l1C' U.J-1 n tI , ,

JO: A Python program to know how to d


111

n aefi ne a fun ct i on inst cte another function


w f disp1ay(str): ~
de def message() :
return 'How are u ?!

result= message()+st r
return result .
11 display() function
I ~a t(di spl ay("Kri s hna"))
prin
o utp\.lt:
·\>python fu~.py
~ are u~ Krishna

I~ ~=O
rarn 11, we are trying to p ass mes sage O function u!:> o parameter or rRumt-
function. Since displa~O function has to rcc<.•ivc another function 1
dis~etef.'itsnouia be defined Wlth another function 'fun ' as parnrnctP-r dS
par def display(fun):
'

~ A Python program to know how to pass a function as p~rameter to un~lhtr


fllilction.
I-functions can be passed as parameters to other fun ct ions
def dis,play~fu~);
return Hai + fun
def message(): ,
return 'How are U?
# call display() function and pass message () funct ion
print(display(messa ge()))
Output:
c: \ >python [Link]
Hai How are U?
pt«' h
, ,,,,,, ,,,,,, 1,, ,,,, ,,,
111 111 •1{1
lJI! "'' ff IIIH '

IJ J,r if Wt 1)/1 jl1

,,ul I ill HJ,I 1 /fJ l 11,, , t,,


111111 11,,11
11
"' u11 i;(J/11'' (J II I I II.
I
fl I I 11 ' f, I

11, fj I , I Vil I' , '


I f
, , v111t1 111 1 I I
, 'I ,
(\ 111( fl

It/ )1 //1/'I/ 111 1',N / I /1//JI I/II// I J I// It Ji I/ I


I l 1 I 11 ,,,
-~ 1
111 f
/\ 1 vll11111
~ ' ; i;"i 1
11
fl' l '"
,d ,,,. ,, IJ I ftt!t , '"'' I l I/ti',
It I
I If
•I
1 .
[Link]'•l 'dttt • 1 1
I 'J
I' 1 1 1111 '1 ,Ill I
II f ,1111 (
Pl d1 -.11l,1Y '
II I
J1, f
,,, 110· 11
I,,
1rl•• •••••"l '' (1 ) .,w 111 11 I /'/'

c,11 I JIii I
t : \ · PY' hO(l f IHI . PY
flOW .ti,, II I

Pass by Object Referencew Jw1, w,· p mw v1.J 1w·1 Ir, ti /1,ri, tirm, w,
I J,,vr,,
111 tlw l11111 i1 111g1•11 lil<1· ( ' 11111 '

w11y1~
LJ J'n• ,1-1 IJy v, tl,w ui ,·sill l>y v11 l11,·
u l '111Hl l>y 1dt·11•1l('I' (j/ 1·1dl 1,y J't ·Jt ·l'l ' JI( '( ' p r.1•i:,1; d to 1hr; fun 1 .
. · ·•w ill H tJt SJ I n ,·opy <JI tJH · . vmi: t1J1f: ,vt~ Jw; HI f . -tUnt.
f>tt'HI l>y VII I Ill ' IC f)II •
ll lftl vtdt1t · will 11ot r<;/k<;f .()Uf HJd(;. fh<; unct ion , l'a •,, hy f ,Jrl(j
. . ' r<; t,r·n
n n y ll) O< Ill 1c1 1I1011 11 10 ;on r,f th<; VE:.lr wl,k l(J the· funct · ,,.
rt·f't·,·t·ii <·c· 01 J1W1t 1ory uddr< ton lh
t ·
v, inl>k
. , 1. 11 ,, iJw
11,p,1·1,w,1 1:1 :H 11 1 n
vt1li1t· l:l
1 '

wdiJi<'d by tl1c furwl icm tJ·[Link]£h rn<;m<Jry Dddrc


11
-~~ ,JncJ h<•n,(• tt~
· 11t
11 · l
HO.
JllOcltfi,·d v1tlu1· wil l 1dll'C 'I 011f Hicl<- flw l1111 CIWn
fJ

l y thon . In Py th on, the'cJviduc.;s arc· Sf•nt to


1
Nt·iJl w , of tltNI<' two c·o,,,·c·pf H fr, nppl kubl< · in . .
W<; J<now t~vc; ry1 h ing JS con~1 en·cJ as an obJeq
f1tnC'I i<J II H by 11 w 11 n :➔ of' objc;d r ~Ji:·rc n cc;H ..
.dc1lcJlyp(' s like tuples
111 Py thon . All
rn1111b1·r11 un· o l>Jt·c l :-i, 1-1 t11ngH ,Jr<; obJ<.;CI H, . [Link] the
c.1 vaJu<; into a vclnabl<.; as:
111-; t M, nnd didio w,ri1 ·1-1 tff<• [Link] :w ol)jc·c tn. If we 1-1 tor<.;
X 10
111 thi:., cww, in oth1•1· pro1~rnm1r1i11g lungu ug<·s , a
wirirJ ble with ,J name ; 'x' is [Link]<:d and
so,n1 • mc•mOJy it➔ , dloc,Jt <.:cJ lo 1/w v11 1i;1bl<
.;. 'T h <·n the· va l ue 10 is stor< ;d into the vanab lt·x·
i s not the· c ase in Pyth on . In Python,
We·< 11 11 im11g i1H· 'x' n:➔ n lwx w)lt'r< · I O i s :,; tor<·d . Thi1-1
<·w1y llliug 1R nn o lJj<'('l. An ol>jc<' t can b<· iln
aginc ·d as a mem ory block wh(·rc· we can
Hi m<· :-,onH · vo lw·. rn tlli f-l rww, w 1 o l>jc·c t with
the· va lue '10' is rrcat ccJ in memory for
¥i4
•x· ,~ ot tnc h ccl{ So, 1O ic.; lh . Puncuon
nr 1 .
f\ ,,il.l ,, cc.t ~ atl' e1cntc tl on h c,, C () )JC{ l
• 11 1ne 1no rv \ 'x' 1s l ht 11 r1mC '
id' ou1 Hnt
:\t1t"' \
1 \sO, n /\ M of our com pul t' t sys t,..., J Whic·h
ol'l ,s o•' tlH:' rv•
' .1 1 t ,
',,, '- 11 I It•
np
18 11
Ver y t
or ta_g g1V{ n th
rfft'' rL"-11\· rnc•rnory . H1g, , rnC'morv th
d. ~ pr0 g cation of a n obj ec t in hC'a p ,s iw ;,1ln h k dur in at
,I • the 1o l , we can g n intir nt
l ~no"' obj ecl- For exrunp c, con side r the f ll l
'fO ,~r of an .'sc Id() fun ct,
fll~ 10 o owm g cod e on t hnt give s itl,- r1t1ty
ril :I' snip pet
~d( ~) .
, . line s of cod e ma y disp lay the follow·
rece ding
mg out put :
'f\lC F
t617
soso1 6
rl\a
bef i•• y cha nge
.
from com put er to com
.
iS J1llfl1 ernofY loc atio n wh ere obJ ect '10' is put er as it •
stor ed . is com puted dep enct ·
'{1l _:1able rn_ ts will hav e diff eren t iden
0-"ffP> t obJec tity num b in the com put er tng on thf•
differefl
ers. · 1n gen eral , two
s valu es like num ber s, stri ngs tuples
pas . ' .
Or 11s
::Thell we. are pas sed to the fun ctio ts tO f .
vw bjec ts n. To und e t a unc tion the refe
- wese ~ In Pro gra m 13 '. we are_ call ing . rs and this '
mod ify( ) functi6 n and con ~ep t,, let's takerences of
rogral11· . Insi a sma ll
P ~,ncbO,Il· - . de -this .
fun ctio n, w e are mod ifyi n th
'x' al . . pas sing x' valu e i e 10
tpat 1~- g
tiofl, we
are disp lay ing v ue and its iden tity num be valu e of 'x' as 15. 'Ins. ide . to
er, as: the
ftl11c - ·nt( X, id( x))
pr1 .
-
saU le mar iner , afte r com ing . out of the fun ction , we are ag .
IP we ow see the pro gra in and its out put . ct·
vawes- N_ am 1splaying these
~--
~ A Pyt ho~ pro gra m to pas s an inte ger to
~~:~:~~ng an int ege r to a fun ctio
n
a fun ctio n and modify it.
c;._.,,, # ~a modify (x) :
t;Yl de .,,,,, rea ssig n a val ue to the var
iab le "'"'
x==lS
pri nt( x, i d(x ))
# cal l mo dify () and pas s x
x== 10
modi fy( x) .
pri nt( x, 1d( x))
output:
c·\>python fun .py
15 161 780 509 6
10 161 780 501 6
the out put , we can und ers tan d tha t the
valu e of 'x' in the func tion is 15 and that
~:~: vail able out side the fun ctio n. Wh en is
we call the modify() func tion and pass 'x'
as:
modify(x) ·
NI(; ,[Link] ng th" c>b1-t1 t refer I f'n
do (/Jt v_, y ·· ' l '-"-' tc, tL.
'1C1 i,, ,,.fttdt{.(; nM(IC IS 7, Tr,I I being 11• rri,Jd
,,v1 ta uifrw. Pa !l{•d
t rlt'I, f/lC ti1C /;.I •c,
~~'~ r
$ I ~
.,,:a'ed 1n, memr,rJ end that ob~{;(.t
, r,JJI', 18
,1 , na c>" !;(.: 1s tn~teo in the mcm r,ry r,r,, r n
J

,1(1 ') 1
1
rJ • 'c}. ':/, m the function wh,,n
,,M""'1'•1.1t~ ~ Wt da1 tha, "~t(j l
1 r••11
""-"'- r, ,. o;'S.I e tht.: [Link] .. ion and
. display ,x va I ~Pla,J /~ '
,,. •
(; n,ill~• tne d,c1gram m figure 9.2. If lie, 11 , ~~ 1
w' ,.e l J >• , , we dis I \11111 .' •
1 , _,, ;ts;,de th<; tund1(Jn, .-,,e see different nu Pay 'h ri~.
1:. ,,," •t . fn;.d' £,1..., <1' mbers sinCei::~l(l~.
- ,,".. "'t\

- -"'J . ,
•~. j ;/

1-t\

t___..-
1: ,v)I, r·#J'J r.,,,1,.,-p'I
~

I -
0
- ,

I
,GJ
t1P~ 11.e wr,ct1<.,rr
heap memory

Figure 9,2; Passing Integer to a Function

(,,, flyni,,n inte,J,-1'';, f10£1ts, ~ngs and tue,les .are immutable. That mean8
, ,,nn•il b, ,nr1Jiti,d, °//h,m ,,,. try to change theu . . value,
. a new object is createctthe;,. datq
d d
wiJihr;1J ·,i,JtJI;, on thr: uther hand, li. sts an 1ct1onanes
odili d [Link]-table., That meanWith the
. ,. rJ,:mfP their d&tb, the ~ame ob1ect gets m 1e and new object' is s, Whe
11
YIWJ'"" ,re
14, -;;,; p,.-lng a list of numbers to modifyl) function. Whe~o~ created. 1:
r,,;-11 di:r,iv,nt t,, the lh,t, the &arne li!>t is modified and hence the modified li8 append ~
"' I,id-, Ihe I ur«11,;n &Jr.o, , t " aVaiJa1,:

•l'r6g,r,;.m 14: [Link] program to pass a list to a function and modify It.
# p~~~1nq a li~t to a function
def r/illdHy([Link]:
lflll• to add a nel'I element to list
·

111111

1:[Link]'!nd(9)
prlnt(lst, id(lst))
# call r~1dify() and pass 1st
ht ~1,2,3 4]
rMJd1f; ht) '
print( ~t. id(lst)J
I J JI 1,ut.

C: ,-p;th<,n iun .py


2 ;, 4, 9) 3776?.55?.
(l , 2: 3, 4 , 9] 377 6? 552
[l. l <1I •

1_1 th<' 1s t 1st 1s tlw 110 tn


f(llll ' , (.' llr [,111 ti
t'f''~ odifyO funrt1on , llfr ltst (0nti • h 1i,1 rcpi, s
If' th!' ffl. i1ns '1 rlcm er1ts the I
-i;1111tnS l st - (1 ' 2' 3 '4] c·nt s Hs: ist (1h1"rt Bcforr

dcrstand that the object here is Il 2


3 · referc
p\eL'scun hC functJon · I st), we or' ' , 41 anct its
as mo d'fy(l
"c call t Jnsidc the func ti on, we arc appenct·e Passing th c obJcctnee, 'narnr is 1st , Whrn
\ uoO· ble addmg • a new e1ernent to th ing a new cIcrncnt '<J' trr,rrcn, e 1~t , to th,-.
ft1J1C
Jl'luta ). b. e same ob. o the list S
[Link] - odifies the same o ~ect. When we dis l ' ~ect is Possible . incc hst,
1cthod rn 3 4 9] p ay 1st inside the f . Hrncc, "PP<'nd()
1'l [l 2, , ' unction we "a
, . g out of the function, we can s ' ' n sec··
cornin 1 ee t11e modifi d
After d So when we disp ay the list outside th f . ie list as the
rJlodifie . , 3 4 9] .. e unction, we can see· same obJect got
(1, 2' ' ' . . . '
.. shown in the diagram m Figure 9.3. If we dis 1 .
'fhtS is d outside of the function , we Will get p ay the identity numbers f h .
t e hst
inst S ~ the final point is this: in Python val
·de an . . . . same numb .
er since they refer0 t
~ . ct o, . . ' ues are pa d o same
5 If the object 1s immutable, the modified al _sse to functions by ob
ference . b' t . v ue is not . ~ect
~e~o"""and if the o ~ec 1s mutable, its modifi d . . available outside th
j't'!Jl1.,,..l'.5 e version is av ·1 bl e
ft10Ction. ,. ~ ~I i ~ ai a e outside the
., 'I:,.

Inside modlfyO function

Jst append
--

1st

outside the function


,, ~ .2,3,4
J
heap memory
Figure 9.3: Passing a list to the function.

Acaution is needed here: If we create_altogether a new qbject inside the function, then it
will not be available outside the funct10n. To understand this, we will rewrite the Program
10 where we are passing the following list to the modify() function:
r [1,2,3,4] • - •

But, inside the function, we are creating a new list as:


· 1st ·= [10, 11, 12]
It means, a new object is created in the function and that is referenced by the name 1st'.
So, inside the function, the list is displayed as:
[10, 11, 12]
" , cuon ,._ dirk n n1 H, nc t II r
... thr ,t.J 1 <rn,
t 1t''"c toad rroin the dll•grmn Jtl bP,Ulr ,, 4 "'

l II u,,dcrs
obCcs)
a new object ins,d, th,. r
Ur,, t
[Link]
d'J.

ou•ptll'
c: \;,pythOizjuni~~os976
(10, 11, 4) 29505016
[l, 2 I 3'
'd Fi1111re 9.4: (
Now, canst er &-
- inside modilYO runctJon ..; ~o, 11, 12
I
1st -

- -, ~ · 2, 3, 4 ]
ISi

I
outside t11e runctlon
heap memory

Figure 9.4: Creating new object inside a function

formal and Actual Arguments


'
When a function is defined it may have some parameters. These parameters are useful to
· en w
receive values from outside of the function. They are called 'formal arguments' Wh
· e called
ca!l the function, we should pass data or values to the function . These values ar '
'actual arguments'. In the following code, 'a' and 'b' are formal arguments and ~• and ,
are actual arguments. )
def sum(a , b): # a, b are formal arguments
c = a+b ·
pri nt(c)
# cal l the function
x=lO; y=15
sum(x, y) # x, Y are actual arguments
'jij \\It 1 In ,. f\1111 lit " ' ill I
,, I I~ ( I
, n,a
l\\fl

1,,nr11t ft
l ,\I \ll
h1r ,11 '"{ th 111\ 11111, ul il

~
• • Argun,L'nts
·t10f'u1
po5i I• ll ltll\\W ' III U p 11•1M, t\ 111 II '1111 II
h i I ItI I , II II
1ill <' ' " I f
.n,r"" , 1111 wn1·1 1111d 111.-11 p11•,11 l111 p1 111
11 1 '''•6hi,111 ,I , ,
';it' 1 ,,1 111 » II 11111,11,111,i,1 I 01' ,1, 11-"'ffi ft•
,,
\,,,,1,r., .. ,,111 \\1w1 i11\d p,1•11111111 nl lit,, " ' Ht 1111, i11, I I IIIf 111 I I"' '""' t1h1,11t,1 r, ,It ,,,,.,.., 'J
:,ti'' ,c t 11111)1\ with lw,, 111 g 111111•111 r• ,,,~ · " , •111 ' t.11 1,,, '"'.Jim ..
,, \\ ,I<' II f I IIJv u,l,,, I
(l\llt lH' f at tilth(\\, ,})
dt
, 1,,q,i·,' t:-1 two t4 t I l11nu t 11111 1110 111
t111\t' lllll 11111 1 t11 1I1
,w:i 11\ :I
tt 11' h<'~ thr
I
two ~,1111w1 Ill\ nl 111?, , Ho WI II I 1111ly Ii I'A i, l?IL11n, th,,1 th~
11 ,,,,•111
, -0 Ill p,,~~ ,,nly twn i1 t1l111~:-1 11~: I I I I 11\litt
~\
I}
1111 f1111, rJ, ri
fifr
.;11 l
.
'l''""lat tac h('New' ' I vor k I )
I t }II'

i .1, 11~ :-tnlt'nwnt diHpl11yi:i tlw followin11~ <H tll llt'1 ·,


~ctl
1'h<' pr
Nt"'york
~r wr passed 'York' flr:;t nnd tht~n 'Ntw', lhr.11 Ilic• rl'ilttll 111 "
St ippo~ ' poss mort.' thnn or Ici-is t Iinn 2 stri ngs there wl, ll b
10 ' " -v>, lf
Wt >I' {c,rytj,.. , /'I
wr tr)I · by pnsslng 3 strings us· , '! Ptt <
;rror. ,r,,r t7.:m1r,k, 1!-J,,._
ii thr function • .. -
ca attach('New', 'York', City')
re will be an error displayed.
Then t11c

~ :hon program to understand the poaitional arguments of a functJon


# ~ositional arguments demo
def attach{sl 1 s2):
"'"' to jo, n sl and s2 and di splay total string ''""
s3 = sl+s2
print('Total string: '+s3)
# call attach() and pass 2 strings
attach('New', 'York 1 ) # positional arguments
Output:
c:\>python [Link]
Total string: N~wYork
()
apter
,nents t 1dr11ti(y the p1111\IIH' l(' I R h
rd Al gt.J II~"'"""'' 11;•;,nl displnys g,o('('I y ill'm 111~,1 ""'" "
Is.t'V v,rO
~,11111
.,,,, ,,,,.of' '
. ltl
I fti ,,,.1 "' 11 I I' ~, """'• •
,, C 'r..
,(1i t'I ~ l ,(11\II I( ~I' ,.
"f'"\' th<' 1
~ • ~
"n1rlC', price)· IH\Vl' to puss two vn lues nnct w,
<' t .,, .t::-. ry{; telll' t. Jtl we c.: <•1,
f groCf .. ft1t1C IC •
~~~\
,,1,I ( I\ r
de f c.1Jl111£t t ~1:.;r r~on1plc,

t\t
tllt' (llll<'
J\lt' 1st
~
'of 'd1t1f, Fo '
, sugar
rice::::so.75)
, P . , nd its value nnd th en anothc k
\\lll1'h , ,1ocerY(item::: keyword , tern das arc nothing but the pararnetr cY\vord '
gr e1 n . cywor er n~.__ p
n rnti 00 111z:, ,e these 1< d 1• of the argumen ts as: ...,,1es tic •.
, !lft' 1 bser- the or c 11/L111
rlr'J"t', \\'t , r1t•n 5l' O change ~1
• \'illtlt ' we co 11 'l ') I
tnd it:, ,(l]tles- . tent:::: 01
' cei''t' these' . ce:::88, 00' , h order of the arguments, there Will
re grocery(pfl h we change ~ e ·de where to store that value h not be
thoug will gut . · r-ro a~
ti1s waY, c,,en [Link] names . ,1'11ents while calling grocery() function gr¾) IY 1
In t _ the par 0 rd [Link].. ·
robleJll as how to use key\1/ .
P ates
demons tr
tand the keyword arguments of a fu .
am to unders
,~-
11)..JAM"
~~~~
. nctton
.
.
prograJll 17: A rd arg uments . demo
). . ,, ""
# keY wo y(item, price 1:ven arguments
def arocer . 1ay the 9
""" to d1SP % , % item).
rint('It~m =_ Zf' %price)
P , t('Pr,ce - ·
%
prin ments
() and pas~ 2 arg~S) # ke~ord arguments
0
# ca11 g('.oc~:rsugar' ,. pn Cf'? ,;) # keyword arguments
grocery 1t~ _88 . 00, , tem= Ol
grocery(pri ce-
Output:
c:\>python [Link]
rtem = sugar
price = so.75
rtem = oi 1
price= 88.00

Default Arguments
We can mention some default value for the function parameters in the definition. Let's
take the definition of grocery() function as:
def grocery(item, price=40.00):
Here, the first argument is 'item' whose default value is not mentioned . But the second
argument is 'price' and its default vi;uue is mentioned to be 40.00. At the time of callinob
this funcnon , if we do not pass 'price' value, then the default value of 40.00 is taken. If
we mention the 'price' value, then that mentioned value is utilized. So, a default
1m nt th t Ill<
t ruigumcnt Pm1,,....,

to Under tend the•


in l 8'. A python program

~ 1 n arguments demo
~n~ aefaultr (,tem, price=10,00):
:ef ~f.?.c~oydisplay t~C Q}ven arguments ...,..
. ( ' Item~ %s % 1tem) 0

pr~nt('Price - %.2f' % price)


pr1n~ocery() an~ pas~ arguments
1 ,all t·tem='Suga r , price=S0.75) # Pa
rocerY(item='Suga r ' ) # default value f ss 2 .arguments
~rocerY or Pr1ce is used .

OlttPtl • thon fun . PY
c:\>P~ sugar
rt~m -_ so .7 5
price - sugar
It~m ==_ 40.00
pr,ce -

ength Arguments
iable L
var th programmer does not know how many Values a fu t· .
SOrnetJJ11 •
· es ' th e programmer cannot d ec1de . · rn
how many argumentsnc tionb may. receive
e
tJ,8l CllS edefutltion. For example, if o e given
. the programmer is Writing a func11on 1n two
to add th~
ftJ!lcoon write:
uJ1lbers , he can
n add(a, b) . . .
the user who is using thish function
. h may want
h to use this function to find sum of
t,hree n umbers. In that case, t . ere 1s a c ance t at the user may provide arguments to
But,
thi function as: 3
s dd(lO, 15, 20) .
tha dd() function will fail and error will be displayed . If the programmer wants to
n,en : ~nction that can accept 'n' _arguments, that is also possible in Python. For this
ose a van•able
develop . length argumen\1s used m the function definition. A variable length
purp ' . an argument that can accept any number of values. The variable length
." written with a '* 'symbol before it in the function defini tion as:
gument 1s
argument
ar def add(fa~g, ~'args):
, • the formal argument and (,1-args' represents variable length argument. We
Here,Pass or Q:lore values to this '*args' and it will store them all in a tuple. .A tuple is
'farg1 is
can . w h ere a groun
like a list .i:::
of elements can be stored. In Program 19, we are showmg how to
use variable length argument. -
\\' vuritlhl<' 1,,11grh urgurn, 111
11£111' tc> ~1,o nnd It
~"' \ I' 1h01' gtli c,in cake O or more v 1 '
den'°
pfilllj,,.gum,nt•aras
11
rt<•· ·abl • 1• 0 , I' sl' ' """ " ,,,,
!ue}3.,,~~d((at9rld
... to a
~;8en num~i:s,, farg)
argume
•forma 1
p,.,,,
t (

!,ums-0 ·n args:
for ;,~+.i f 11 numbers• '' (farg+sum) )
. (' sum O a
print d pass arguments
# ca 11 add() an
add(5, 1~) 20, 30)
add(5, 1 '
out put :.\python fun. PY 5
c. > 1 rgument:: 5
Form~f !11 numbers:: 1
sum 1 argument:: 5 65
o a11 numbers:: ,,, 1 rnent is an argument that can ac
formaf
sum
· ble Jengtb aro-· · • cept a ·
A keY"''"d var •
'd d1 in the forrna1
values provi e
' , th ~
of l«ys and values. If we want to use
. d 1are it with ** be1ore e argument as :
ny n,.
a ke"'·· 4ll)h.
J vvord ·s:r
nt we can ec '• ,,
Jength argu~e ,• (farg ••kwargs): 1,1,
def d1SP. ayall d k' yword variable argument. This• argumtnt i t
Here '**~args'. is c Ad' e
e tionaJY . the fiorm of key and va]n ernaUYr,p
stores data in
. ti aJ)' object. ,c ue Pai" - It ,,,\
a 1c on . a1 ••kWargs', we can pass multiple p • Ues ~G
d we provide v ues 1or
when arrs of Vaj ~,,.

keywords as: u'I,


display(!, rno-W) ·
. t d into 'farg' which is formal argument. 'rno' is stored as k
is s ore ey and its "ii
,Here,
1 · ·
, is5 stored as vaJue in the dic_tionaJY that 1s refere_nced by 'kwargs,
provides
10 better understanding of this concept. . . Prol:tain i

~ O: A Python program to understand keyword variable argument.

# keyword variable argument demo


def display(farg, '~*kwargs): # **kwarg can take O or more val
"'"' to display given va 1ues "'"' ues
print('Formal argument= ', farg)
for x, yin [Link](): # items() will give ·
print('key = {}, value={)' .format(x, y)) pairs of ite~

#_pass 1 formal argument and 2 keyword arguments


d1~play(S, rno=lO) .
print()
~; ~paj!y1( forma ~ argument, and 4 keyword arguments
5, rno- 10 , name= Prakash') .
ocal and Global va, 1ables
~ [Link]. n , nnnhl r m,1dc n fonctio
t\ " 'C \ \t b«,o Ill
"'b<' ~blt ,, ho~c ~C\l\>C l~ hmn('(\ onl) to n, th ,t fu1 cs a lO('n\ , nr uhle ~ l
1c a'~ \11nbl<' ,1,hll' ,~ l\\ rulnhlc on\\' 1 th t f
11 lthon '-'hert It ,~ <".... Cl( tl' n r-
1,,-;ru '
tht ~ nn,,-,111,:.. t', .,mp \e. l 1"\C Y,\11,\ bk \ , ,, "l(- I\lnttm n n1\d nut 0\lt!II ·... trd ih t n
de flf t
the ,1l) \ " f \ (' U'td m~,d f'ill
\Tl ,... in~itk lhal unctto n One\' \\C ~'t'll\, \ \ \I rt\l\ l I
ul\b"· d e m,fun<'tioi,o "' l l n
9\"t\ j front mcml,r. ,\n \t ,~ nl,t ,\\ n1l,,bk c , ( O\lt of th . un( It'll('(' It
:'Cnlo,'t"\ . . c hinctm n. thr
l,n~1rlc1 the loll \[Link] 'n ,~
' 1def local va~1a ble
■yfunction():
1A a function 111
°"
g e<xk
asl , this is local var
a+-1 J v,c r~en t it
print(a) I displays 2
,yfunctionO
print(a) # error, not available
e 1a?t statement where we are displuving ...... ..
~ th . \ <\1Ul' outs1d<' th f
ent raises an error with a message: name· •o. • is« not d fi '
statem · e med. c unction \'his

11 n a \'ariable is declared above a function it becomes I b 1


\\ e •ailable to all .the functions which are written after •t gco a "nnab k · Su<'h van,,blc:'\
art a\ 1
• ons1dcr the folio\,,
I global variable example od
· ng c c:
a=l # thi~ is global var
def myfunct,on~):.
b=2 # this 1s local var
print('a= ', a) # display globalvar
print ('b=' b) # display localvar
ayfunction()
print(a) # available
print( b) # error , not available
Whereas the scope of the local variable is limited only to the function where
it is declMcd.
the scope of the global variable is the entire program body written below
it.

The Global Keyword ·


Sometimes, the global variable and the local variable may have the same
name. In that
case, the function, by default, refers to the local variable and ignores the
glob~I vru-iabit'
So, the global variable is not accessible inside the function but outside
of it, tt ts
accessible. Consider Program 21 .
unckr~wnd glc1ha.l a nd lcx aJ ,..0 n b
nlgrum 10
011 P and loc al var iab les
21 : , Pvth for globa . 1
rroff•fl'I bal vo1
II same w,amr.s is glo
.
t th1
a!!l fun cuo nP. .1)5 loc• aldisvar
pla y loc al var
d~f my, ' · th1S a
:l { I ,r I

,-in l ( 3 ::: •
fu~ttion~) ) #di spla y glo bal var
mY. t('a = , a
prin
()tJtJ)\11. y
c:\>pyt hon fun.p
as. 2
a• 1 use the global variable inside a fu [Link]
wan ts to . . f
ariable in the begmru ng o the function bOd , he ta
When the programmer Y as: l'l i..
, lobal' before the v ~
kcyword g th '
global a . bl .s made available to the function anct e p
1 bal varta e I following program, we are showmg h rogr<lni
In this way, the go . In the ow to rt._
.h1 ·r as he wish es. Wor1
work wit . . function. i\ ~-
global variable inside a

de a fun ti
~ arn to access global variable insi c on an
~ · .
22· A Python progr
h lobal var iab le ins ide a fun ctio n dll10q,r,
Prograro ~-
# accessing t _e gl 0 bal var
a-l # this ,s g
d;f myfuncti on O: · 5 ·5 1oba1 var
gl9baI,alob!lt~~ •~ a5
# dis pla y glo bal var
~e
P~~nt #gmodify glo~al a)var #valdis
a-. (, dife d a= ' . pla y new val ue
pr, nt mo
difi ed val ue
myfuncti on O a= , , a) # dis pla y mo
prin t('g lob al
Output:
c:\>python [Link]
global a= 1
modified a= 2
global a= 2
variable nam es are same the progranun
When the global variable name and local J

ms1de a fun ction. For exam 1 er (


• •

face diffi culty to differentiate between them


lared above the function. The ~0e lliere
is:
e dec
r~
glob al vari able 'a' with som e valu
ing a local vari able with the sam e nam e 'a' with som e oth er value ins•1: f amme
writ e t e funcuc~
Consider the following code:
a=l # this is global var
def myfunction():
a = 2 # a is loc al var
,,,,,,,- grn,mn1•1 wnnts to wo,.k Witl ---.-......._~::~ ts,
/ ,nhe t)fVrd then he cnn access Only 1111 gb1nhuJ \trfl iab1, l J
,, I 1\\'0 ' I") f) HI \tfl . ' 10,,, IS t
s ~J'}{c~ rtnbtc :inct h. 1 Poss,t,Jc-? If h
i ,t,,I b•·· t c l0c.i , "•hie 1 c l1 ,
,,~• • 0 function Wl·11 so Ive th,. Problem. 'fh, ,
b
5 8 s no ""'"
g1obol nt global vanables in the forn, r • •s • bui1t
10 1
~, of ~::0 the global variable 'a', as: &loboai~f •;tionary, 11,~:":''. Wh1tb ""turn,
" csJI re able, say 'x' and the prograininer can a . Now, this v,1~ sing th,, hinttlon0
••,,~er van Work With that v I c c::in he ns~rgnc·d I<;
sJ1 -~ 23, a Ue. 11,IS is •h
~w" . "own,n

~ thon program to get a copy of &loba1 v .


,,,..-....,. ""•hie into r
I"""'.-,t.
.,t~ e name for global and local var; ab l • unction "1ld wor;
I sarn # thi~ 1s ~lobal var , es
a~l function().
def my_ 2 # a is local var
!:
globals()['a'] 1 Qet global
rint('global var a= , x) var into x
~rint('local var a= ', a)
function()
pr1n t('global var a= ', a)
mY.

output:
c·\>python [Link]
iobalvar a= 1
~ocalvar a= ~l
globalvar a=

passing a Group of E_lements to a Function


a group of elements like numbers or strings we can accept th . .
To passass the hst
. to the function . 'processing can beem
. where the requrred d into a list
p and
then p . . one. n rogram
are accepting a group of integers from the keyboard in a single . 1 . h
following
24, we statement: 1me using
te
1st= [int(x) for X·in input().split()J
The input() function takes a group of integers as a string. This string is split into pieces
where a space is found as a space is the default for splitQ method. These pieces are then
converted into integers by the int() function and returned into the list 1st'. We pass this
list of integers to the calculate() function as:
x, y = calculate(lst)
The calculate() function returns sum and average which are stored into x and y,
respectively.
I
260
pl n lt''" 'p t1f r111 111br l fl

rroe"'"' a4, A "


11.)11 11011 fll l_lfC t
f f ~•' , o, oI an" .,v•', nu•·
11
ronct I nl1 f((}l I). '" '"
"'llf c,l'llcu1etC t't<); •11 11 nd
, ii
,1vc111t1
u f ,,,. t(l f 1nc
n ~ , ,,n(hl)
!!urn9"
for 1 111 1/'
1t:
.!,Url11•
ilvg ,, surn/n
return ,sum, ,,vg
nt eger!i f rom kf'ytJo,1 r<J
f
1
# rake a grour \i,r'-' '-'"p,1rJ tcd l>Y i:,p,H"(' : ' J
printe'1ntl!r)nf~r x in input() ,sr, l ltOI
ist • [1n1(X
l t
(i
e and pas~ the list
# call calcu a )
x y calcula~e( st
printC'Total; I ,x) )
print(' Average: , Y

Output·
c·\>python fun .PY db space·
Enter numbers separat e y .
10 20 30 40 51
Total: 151
Average: 30.2 from ktybo,1 rcl ..in<1 rJ
Program 25 shows how to accept a group of string, '' 111:,/ r,
,
using display() function.

~ . d' 1 f .
Program 25: A function to 1sp ay a group o stnngs.
# a functi on t o display a group of stri ngs
di st) : the strings '""'
"""spltoay(l
def di splay
for i i n 1st:
pri nt (i )
# ~ake,a group of stri ngs from keyboa rd
~r, nt( Enter st~ings separated by comma · ' )
= [x for x in ,nput (). split( ',')] ·
st
#.call di spl ay() and pass t he li st
d1splay(lst)
Output:
C:\>pyt hon fun py
Enter st'.i ngs ~eparated b
Gaurav,v, nod visal A k' Y comma :
Gaurav ' , n 1t
Vi nod
Visal
Ankit
ft1nc.1lon I ., J.
/ 4unctions ~
r, I

Aurs .
~t,"- 1 11 c11lls t1R<'lf 1s known a~ 't<•r . .
I' t ,m1 t " lll a1vc ftinctton,
\ ftll''.111I 0f J 11g: Por example, we cnn write th,,
~,r1,1r ,.. 3 * factor; a1 (2)
ori a1( 3)
' fact factori a1(2) = 2 * factorial
:~~~'factorial(l) = 1 * factorialcd})
know tho.I the factorial(O) value is l all
if we ' lhe Pre ct·
No'''• . c the result as: ce tng statements will
~odS'v torialC3) c: 3.* factoria1(2) evaluate
fac * 2 * factorial(l)
• ~ • 2 * 1 * factori a1(0) ·
: 3•2*1*1
• 6
he above statements, we can write the formula to
fro!Tl t calculate factorial of
any number
, s·
'fl a· factorial(n) =n * factorial(n-1) ~.....,.. ~
e observe this formula, we can understand
When w f' ' al will all . that the fact 'al
1 te factorial o n v ue c itself to calculate f t . on () function to
a}cU a .
al() fu t· usmg ....._ ac onal of 'n l ' value. So, we can
c nt factori nc 10n recursion as show . Pr -
i!TlPle!Tle - - •' n in ogram 26.

""-'
progr
aJll 26: A Python program
.
to calculate factorial value . .
s using recursion
# recursive function to calculate factorial l. ,,,,.,.,,-

d f factorial(n):
e to find factorial of n """
111111

if n==0:
·· result=l
else:
result=n*factorial(n-1)
return result -
# find factorial values for first 10 numbers
fori1nr~ng e(l,.11): . ,
print( Factorial of{} is{} .format(i, factorial(i) ))
Output:
c:\>python fun.~y
Factorial of 1 is 1
Factorial of 2 is 2
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
Factorial of 6 is 720
Factorial of 7 is 5040
Factorial of 8 is 40320
Factorial of 9 is 362880
Factorial of 10 is 3628800
Let's write a program to solve the Towers of Hanoi problem through recursion. Towers of
Hanoi is a famous game from ancient China. It is believed that this game helps to develop

You might also like