0% found this document useful (0 votes)
17 views13 pages

Function

It's very useful for me

Uploaded by

abi129962
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
17 views13 pages

Function

It's very useful for me

Uploaded by

abi129962
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 13
Tan After the called function is executed, the control is retumed back to the calling program. sn ce hah ane x ll oo Ry, sun el ar any ton gt 2 any tines est wars For example faction call placed within forloop eg wile, lap hey ol me funtion lie times until the ondition holds tn: of wring these instructions everywhere they are require, better way isto place these instructions in a fuetion an el ht Function wherever require. Figure 8. expitns this concept 5.2 FUNCTION DEFINITION ‘Any fmetion can be compared to back box (hat is used for an nity having unknown implementation) that takes in np, processes itand then sptsout the result However, we may also havea fetion that does ot take any input all, or that does not retam anything st all While using fanctions we willbe using the terminology given below, Functon funet() ald twice ram he main module + A function, / that uses another function i known as the calling fanction and gis known asthe cal! futon + The inputs thatthe Function takes are known as arguments/parameiers. + When called function reums some result hick to the calling funtion, tis said to rem that rest + The calling function may oc may not pass parameters to the called function, Ite called function accepts arguments, the calling function wil pass parame, ls noe * Function declaraion is a delaration statement ht identifis a function with ts name, ist of arguments that it acces, and the spe of ats ets + Function definition consss of «function header that ieatifes the fantin, followed bythe body ofthe function containing the exooutable code for tat fnction. Prion ives fnction st lass treatment and gives them equal status vith other objers. There are fo base pes of fictions, bulin mcions and user defined ones. The bili functions eome a a part oth Python lange. Foe examples, ir, Tent), arabs(). The ‘er defined fanctions, on the oer hand, ae fanctons created by wers inthe programs using the deF keyword. ‘Asa Python programe, you ean write any numberof futons in your program. However, define @ jon, you mst koep the following pois in ming ncn block starts withthe keyword df ‘The keyword is followed bythe function name and parentheses ()), The neon nae is uscd to uniquely ‘demtify the fetion * Alter the parentheses aeolon (is placed * Parameters or arguments ht the function accepts are placed within parentheses. Though hese parameters Yalu are passed to the finetion, They are optional Incase no values are to be passed nothings placed within the parenthesis. The frst statement ofa funtion can be an optional stalement—the documentation string ofthe function or daring desribe what the function does. We wll discuss this tr inthe book, Functions and Modes ln the aforementioned code, name ofthe function js fune, It takes no arguments, and prints “HelLo Worta” four times. The funtion is first defined before being called) The statements inthe Function ae executed only when the Fntion i called 53 FUNCTION CALL ‘Defining 9 fimction moans specifying its name, parameters that are expected, gudtinammemmeisesiamt, principle, that is, Don't Repeat Yourself principle. Once a function is written, it 6a 00 Cae ne aly, a bad. eth the sme or by a ferent program wherever Ks functionally 8 required. Conespondingls 2 Teptlive soe abides bythe WET principle, ic, Irie Everything Twice, or Me Enoy Typing ‘Chesca program that excuts ant of insrction repeatedly mines, though not continous In ‘Gow the lures to Be repeated continuously frm ies Hy can tt be placed within & +The code block within the function i propery indented fo form the Block cos. 1 Aincion may have a returaf expression] statement. Thats herctum statements optional. Fitexits, ‘t pases back an expression tothe eller, Aretam saerent with no arguments ithe same as eum None, «Yorn esiga the function name to a variable, Doing this wil allow you to call he same function wsing ‘the name of tht variable. of two pats: + Function header + Function body “The syntax af function definition canbe givens: (HEISE wre con at pte asin psy * Parameters or arguments thatthe function accepts ae placed within parentheses. Though these parameters ‘alu ae pase to the function. They are optional. In case 99 values are tobe passed, nothing i placed in dhe parenthesis * The fst statement ofa function can be an options sttemeat—the documentation string ofthe Ranetion or dosing desribe what the function des. We will suse his ltr in the book Functions and Moxiee @ Inthe aforementioned code, name of te function is une, It takes no arguments, and prints “Me1i0 orld” four times. The function i first defined before being called. The statements in the function ace executed only when the Function i ale BRB i ig street etnias you si vars ore ham 53 FUNCTION CALL Defining a function means specifying its name, parameters tha are expected, nd the sto nsietions. Once the base structure of anction i falc fan be exceuted by ealing i The uneton ell statement invokes the Function When unstions invoked, the program contol jumps othe aed function to exceute the statements that apart ofthat function. Once te cle function is executed, the program contol passes back to the elling function. The syntax of cling a function that doesnot accept parameters i simply the name of the tion followed by parenthesis, which s given as, “fonction oa Function call statement has the following syntax when it acceps parameters (Function Nane(varlabiex, variable, ‘When the fonction i alle, the interpreter checks tha the comect number and type of arguments ae wed ‘the fnetion cal, also checks the type ofthe returned value (it retusa value to the calling function) ES cals known a she etal parameter int The atl parameter Ise may be variable rames,expressons.orconstans. Beall ay 53.1 Function Parameters ‘A funeton can tke parameters which are nothing bt some vas thit re pest it 0 ta the function cen ‘mnipalte them to produce the desired result. These parameter ace nom vars witha small differnce fia th values of hese variables are defined (ntalzed) when we cll he fnction and are then passed to te fiction, Parameters are specie within he aif parentheses inthe function defirton and ae separate by commas, Key points to remember while calling the function + The eton nae and he mamber of argue éetnion fy mistake the parameters passed to fancton ae more than that it is specie te acep, then an enor will ke returned, REMI Pen scronsen he mine betwen finn pre an rumen nel -_ MerintChetto dort, 5. 4) is inthe fancton call mst be same asta given inthe Function Funcom ties GN + Arguments may be passed inthe form of expressions tothe called funetion. In sch « case, arguments | __ ar first evaluated and converted wo the typeof formal parameter ard then the body ofthe function yes exccuted. Program to demonstrate that the arguments may be passed in the form of expressions to the called function, ieee fey points to remember while calling the function ‘The function name an the numberof arguments inthe fancton cll must be same stat given inthe ftion Aiton, by mistake the parameters passed oa function are more than that itis specified o accept, then an error willbe returned, Program to demonstrate the mismatch between function parameters and arguments | + Arguments may be passed in the fom of expressions tothe called fntion, In such ease, arguments efit evaluated and converted tothe typeof formal parameter and then the Body ofthe Function gets exoouted, (HEED P2222 10 drone tat he ngumens may b ase inte frm of expressions ‘oie cal ction +The parameter list must be separated with commas. + the funtion reruns value then it may be assigned Wo some variable inthe calling program. For example, Letus now ty program using fines Program add wo integer ising functions {the function totat() used in the above program, we have declared a variable result just ike any other Variable, Variables declared within a faction are called Focal variables. We wil ead more about in the ext seston. 34 VARIABLE SCOPE AND LIFETIME racton oneness GI ‘Table 5:1 Comperison Between Global and Local Variables (HEMMER cr demons mismatch tewcon da yes of ft parameter an aeons soca + Scope of the variable Prof to program in which a arabes accesible salle its sep: {Lifetime of the variable Duration for which the variable exit i cae it iene. 5.41 Local and Global Variables Global variables are those varisbles which are defined inthe main body fof the progr fil. They ace visible throughout the program file, As 8 {good programming babi you mus ty to avoid the use of global variables ‘Decause they may get allerod by mistake and then result in eroncous ‘ufput But this doesnt meaa that you should nor use them ata. Asa goln rle, use only those variables erbjcts that are ment to be used globally, ike funedons and classes, shouldbe putin the global section of the program (above any her funtion o line of col). Comspondingly, «variable which is defined within Sanction is local wo that function. local variable can be acesned fon he pont ofits definition imi the end of the fmetin in which itis defined exists as {on a the foneion is exceuting, Function parameters behave like Local variables in the Function, Moreover, Whbscer we use the esignment operator (-) inside a function, a new leal variable is eestd (provided & ‘Variable wit the same name snot defined inthe local scope). (EEMNIERID ron ose te iene heen nd lb vais Programming Tip: Varables ‘an ery be used alr the pont liner decrson “The fllowing Table 5.1 lists the difeenees between global an focal varbles. + In ease of nested funetions (function inside another Faneton) the inne funetion can access variables defined in both outer 25 ‘well a inner fetion, bat the outer function can acces variables ‘efined only inthe outer function. The folowing code explains this concept, (RENMEI) revramiodemonsate aces of variables in me nd outer functions La) ron (REIMER) Proxrat demonsttes using vale deinen global ramespace ‘You cannot define lot variable withthe same name as tet of lobal variable Ifyou want odo ha, you nist use the global alemert. The code given below illustra this concept. (REREAD esr tit demonsis sing aoa vrnle wih sane ase a hat of lob 5.5 THE return STATEMENT ‘nal uruesions writen above, nowhere we have used he retury | ‘aterent. ut you wil be surprised o now that every function has ‘an implicit etum stacment as the last insrtion inthe funeton| ‘body This implicit retuen statement returns nothing ots ale, 50 itis sid to rum None, where None meas nothing. But you can change tis deeult behavior by explicily ‘sing the retura statement o return some value back t heels, The syntax of return saterent is, ‘The expression is written in beackets Because itis optional. th expression i rise itis evaluated and the resultant vali etumed othe ealing fnetion. However, fo expression i speied then the function will ern None ‘The return statement suse for to tings + Resima value tothe caller + Toend and exits function and go back tis caller isconsed inthe previous section, scope defines the visibility of «name within a block, I lea variable defined in a block, its cope is tha parhcuar block (Fits defined in a function, thea is scope sal locks ‘within that nction When a variable name is used in a code block, iis resolved “sing the nearest enclosing spe. Ifo variable ofthat name is then a naneError ie aised. Inthe code given below, str 1 plbal string because thas been defined before calling the nce sora GE (HEIR) reer to wre snc witout a retrn statement andy opin seam aie ‘Asmctioned carer, sch incon ould ret one Itshould be note that in the output None i returned fom the fancion. The retum value may or may not be signed 10 another variable in the calle. (HEN) 02:22 to write anoer action whic resus an integer to the caller Key points to remember +The rtm statement must appest within the incon. * Once you retura vale from 8 function itimmediatly exits that function Threore, any code writen afer the etm stafement i never exeoued. The program given inthe following example states his concept rogram to demonstrate flow of eontrel after the return satement the resultant value is returned to the calling function. However, if no expression is specified then the functiot wallet None BBR Ancona orp nopreurmasane, The in tees se vo igs + Retuma vale tothe caller + Tend and exits function and go back tis caller TERR errno 5.6 MORE ON DEFINING FUNCTIONS ‘Wehave already discussed in the previous section, the technique to define and calla funtion In this section, ‘we wll go step forward and lear some more ways of defining a funtion, All these features makes Python ‘wonderful language, Some of thee features include * Required arguments + Keyword argumenss + Default arguments ‘+ Vasable-ength arguments 5.6.1 Required Arguments ‘We have already been sing this type of formal argument. Inthe regired arguments, the arguments are ‘passed fo function in conect positional order. Also, dhe number of arguments inthe funtion call sould ‘exacly match withthe numberof arguments specified in the function definition. Look at thee dierent versions of display() given below and observe the outpa. The fanston displays the string only when number and type of arguments in the function call matches with tht specified in the fiction definition, othersise a Typeteroe is retuned 5.62 Keyword Arguments ‘When we el «function with sme vale, the vals are asined 0 the arguments based on ther position, Python alsa alls factions te called using keyword arguments in which the ord (0 postion) of| ‘hearguments can beckanged. The valves ae nocasigned 0 arguments econo their poston but base on their ame (or keyword). ‘Keyword arguments when used in function calls, helps the function to identify the arguments by the parameter name. This is especially beneficial in to cases, + Fin ifyou skip arguments + Second fin the finction cll you change the order of parameters. Thais, nanyorde diferent fom tht specified inthe function dfiton. a ‘The deft value to an agiment is provided by using the assignment operator (=), Users can specify a ofl vale fr one or more arguments, ‘Program to demonstrate flow of control after the return statement | In both the cases mentioned above, Python interpreter uses keyword provided inthe funeton call to mate the values with parameters HMMMEED cram to dnote keyword argues (ENIIEED onsicer moter program or keyword arguments in which ring ition cll we Se cexigtmen op Or fangs les Econ prance wang ot vrais Guindof abe, ‘Key points to remember + Allthe keyword arguments assed should match on of the argument accpied bythe fiction. + The order of keyword arguments snot important Ino eate an argument should rooeive a vale more than 5.6.3 Default Arguments Python allows uses to specify function angurcnsthat can have deful values, This means that a function ean be {aledvan erat an sce ve. Tht ite non cot ie pram, a fincion St pevid iy eo puncte te ti uremia he ea end oper) au. 0 ee entscssos CR 5.64 Variable-length Arguments Tn some sisiations, itis not known in advance how many arguments willbe pasted toa function, In such «cases, Python allows programmers to make function calls with arbitrary (or any) numberof arguments. ‘When we use exbitrary arguments or variable-length arguments, then the function definition wees an 5.62 Keyword Arguments ‘When we call faction wit sre vals, the values are asaned to the arguments based on ther poston, Python als alls fncton te called using keyword arguments in which the ode (oe position) of| theurguments can bechanged. The valvesarenotasigned argunens ccoing wo their poston but bso on thei ame (or keyword) ‘Keyword arguments when used in function calls, helps the function to identify the aguments by he parameter name. This is especially beneficial in evo cases, + is ifyou skip angumens. + Second fin the function cll you change the onder of parameters. Thais, in any ord diferent fom tha specified inthe function definition. a “The defalt value to an argument is provided by using the assignment operator (2) Users can specify a otal value for one or more argumen's. (HEI) vera tat ss det argent In the above coe, the parameter nane does nos havea default Value andi therefore mandatory. That, you ust specify a value for this parameter during the ction cl. But, paaraeter course as already boen given default val, sits optional. fale is provided, it wll overwrite the default vale and in ens «value is ‘ot speci ring function ell. the ene provided in the function dein asthe defeat value wil be use, Key points to remember “+ You san specify any number of default arguments ia your funtion. * Ifyou have default arguments then they must be writen afer the now-deaul arguments. This means that ‘non-fat arguments cannot follow defult arguments. Therefore, the line of code given nthe following ‘example will roduce an err (REMIIEED Program to demons def agunets [RR Pree pono functions, Le, they are just needed where they have been created and can be used anywhere a function is Se AE a ae are0d SERENE PRES SACS ALES SNS CS Se ae eee +The order of keyavord angurents snot important. + Inno ease an argument could receive a value more than one. 56.3 Default Arguments ‘Python allows users to specify function arguments that can have deft values. This means that a fiction can be ‘ali wih fever angen hans eiacd bre Tht the incon set te rent, bi fncion ‘Sl povides ely arguments, then thi parameter wl be ase he dtl (ead specie) value | 5.6.4 Variable-longth Arguments In some situations, it is not known in advance how many arguments wil be pated to a function, In such «ass, Python allows programmes to make function ealls wih arbitrary (or wy) numberof arguments ‘When we use arbitrary argument or variable-length arguments, then the faction definition uses a9 asterisk (+) before te parameter name, Syntax fra function using variable arguments can be given as, {athe above program, inthe function definition, we have tvo paramcters one is nae ad the oars ariabe- Jength parameter fay_subjects. The functions called dee tines with 3, 4, and parameters) respectively, ‘The first value is assigned to name and the other values ae assigned to parameter Fav_subjects. Everyne can have any numberof favorit subjects and some can even hve none. So when the tcl s made, Fv ‘subjects has mo value and hence the For loop will nat execute thre sno subject available in fen subjects, Koy points to remember + The arbitrary numberof arguments passed tothe fiction basically Fon ple (taste discussed ner inthis boo) bot bei ped ito the fenton + Inside the calle funtion, for loop i se to acces the arguments, * The variable-length arguments if preset in the function definition should be the lst nthe list of format parameters + Aay formal parameters writen afer the variable-length arguments must be heywordnly arguments ~~ 57 LAMBDA FUNCTIONS ORANONYMOUS FUNCTIONS, Lamba oF anonymous fnetions are so calles! because they ate not declared as other functions'ing Ihe de keyword, Rather, they are coated using the anbds keyword, Lambda functions ae throw-avay Funders endvecsios EIN (GERM recta od sate of wo abr sing Lon Stn 5.10 RECURSIVE FUNCTIONS ‘Arecrsive faction is fined fanetion tat calls iself to sole smaller version ots tsk unt al calls made which does not require alto tse. Every recurve soliton has two major cases, which ate as fll * hase cose in which the problem is spl enough obe solved rely without making any arth clls othe same incon, * recursive casein which fit the problem at hand is divided into simpler sub-par. Second, the function cals ite but with sub-part ofthe problem obtained in theft step, Tht he results obined by cone ‘ining the solutions of simpler sub-parts. wesc that rcusin willed divide anc conquertechnige of problem solving. Dive and conquer is a method of solving a given problem by dividing it into two or more smaller instance, ach those smaller instances is recursively soled, and the solutions are combined to produce a sluton he ‘ginal problem, Therefore, recursion i used for defining large and complex problems te mane ofa ler and more easly solvable problem. In a recursive function 4 “Sompicated problem is defined in tems of sper problems andthe est problem s given exp. To understand recursive factions, let us take an example of ‘aleuaing factorial of a number. To caleulate 1, what we have to ‘ois mtiply the number with factorial of number thats les than ‘hat number: In eer words al = X (8-2)! ‘Letus sy we neat ind he vale oF ‘Step 4: Call the fanetion onthe sub-problem, ‘Step $: Combine the rests ofthe sub-problms Sep 6: Return the rest of the etre problem, Mss es rererrsere Sh=Sxaxsx2xa = 320 ‘Thiscan be writen as 51= 5X41, where aie ax ‘Therefore, si esxaxat Figure 5 Recursive facoi uncon Similarly, we en also write, SI =x 4x3 x21 "Expanding fuer Sl aSxaxsx2xi Weknow, 11 «1 “Therefor, te series of problem and solution canbe given as shown in Figure 55 "Now iyou Took atthe prcblem earefily, you ean see that we can wnt a recursive function to exculate the factorial of number Noe that We have sid every recursive function must havea base case and a recursive sae, For the factorial function, + Base ease is when n-1, osause in = 1 the ret sknown tobe as) = 2. 1 Recursive cae ofthe factorial unction wl call tselbut with smaller vlue ofthis case canbe givens (HEIR) Forum to colsunte eFctva ofa mer scusively rom the aforementioned example, lt us analyze the basic steps ofa recursive program. ‘Step 1: Specify the bate case which wil top te Sanction fiom making illo set ‘Sep 2: Check to soe whether the curent vale being processed matches withthe value ofthe base yes, proces and etumthe vale Sep 4 Divide the problem ino a smaller or simpler sub-probem

You might also like