History of Fortran Programming
History of Fortran Programming
i(
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 . $,
'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
~ 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
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
~to test prime or [Link] program that generates prime numbers with the help of a function
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/!/£
,... •
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 ,
~
Program 9: A Python program to
see how to assign a fun ction to a
variable. '
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):
'
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 '
,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
(,,, 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.
Jst append
--
1st
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] • - •
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
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'
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,,....,
~ 1 n arguments demo
~n~ aefaultr (,tem, price=10,00):
:ef ~f.?.c~oydisplay t~C Q}ven arguments ...,..
. ( ' Item~ %s % 1tem) 0
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 ~,,.
,-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
output:
c·\>python [Link]
iobalvar a= 1
~ocalvar a= ~l
globalvar a=
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