You are on page 1of 60
Working with Functions iy Wis Conte 3.1 Introduction 3.2. Understanding Functions 33. Defining Functions in Python 34 Flow of Execution in a Function Call 35 Passing Parameters 3.6 Returning Values From Functions 3.7. Composition 3.8 Scope of Variables INTRODUCTION it is difficult to manage a single list of Large programs are generally avoided because it is diffi : : instructions. Thus, a large program is broken down into smaller units known as ioe function is a named unit of a group of program statements. This unit can be invoked from o' Parts of the program. ( ; i all The most important reason to use functions is to pak ao ae jeariiae cola i i i voi , reasot Part of the program is dealt with at a time, thereby aa aac ae functions is to reduce program size. aaee a ‘nahagement much easier standable to a programmer thereby m : we shall talk about functions, especially, Fruncrion In this chapter, how a function works ; how you can a your own Aruna “ functions in Python ; and how you can use functions sa often returns created by you. en 94 3.2. UNDERSTANDING FUNCTIONS seve as pring gn aly yhat a function is, in In order to understand wi ines carefully. sec oatmes, ae es with polynomials in Mathematics. Say we have following polynomial : You have worl 2x? 2 For x=1, it will give result as 2x1? =2 2 = For x=2 it will give result as 2x2? =8 For x =3 it will give result as 2x3? =18 and so on. ; Now, if we represent above polynomial as somewhat like fs) = 2x? Then we can say (from above calculations) that fay=2 (1) fQ=8 2(2) f(3)=18 3) The notation f(x)=2x? can be termed as a function, where for function namely f, xis its argument ie, value given to it, and 2” is its functionality, ie., the functioning it performs. For different values of argument x, function A(x) will return different results (refer to equations (1), 2) and (3) given above). On the similar lines, programming languages also support functions. You can create functions in a program, that : © can have arguments (values given to it), if needed can perform certain functionality (some set of statements) © can return a result For instance, above mentioned mathematical function f(x) can be written in Python like this : def calcSomething (x): Pa2*y ee return ion definitic 7 © identifier follow: on is starting caleSomething © the vatiablesidentitier i identities inside ty Biven to function), i¢ hj © Parentheses are - io ie Reese ; 1 © there isa colon at the eng he atBUMent to fan a/Suments or parameters ( end of def line, Meaning i 'on calcSomething. : 8 it requires a block is t - the name of the function, ie, here the function name ® 3.2 © the statements indented below 95 functionality (workin, the function, (i, Here, there are two Cee This ee aes ee def line) define the in the bos called body-of-the-function. di © The return statement retums ly of function calcs the com IcSomething. puted result. e non-indenté ‘The non-indented statements that are below the fu | To see are not part of the function caleSomething’s definition eon oma in ation 8's definition. For instance, ig. 3.1 below : aE consider the example-function given in Fi ame of the function ——— ooo a \ ue aa on Cote def calcSonething (xx): | ——— ion offs ele Samting ra2t*xer2 = return r Body ofthe function caleSomethir os oe ly ofthe function caleSomething return computed | a . “aE Complete progam a= int(input( "Enter a number :")) “4—— Mis is not a par of fanetion caleSomething. | (These statements are not indented and hence ‘at top level of indentation.) print (calcSomething(a)) Function call inside print( ) | Figure 3.1 Python Function Anatomy | 3.2.1. Calling/Invoking/Using @ Function To use a function that has been defined earlier, you need to write a function call statement in Python. A function call statement takes the following form : efunction-name> () For example, if we want to call the function calcSomething( ) defined above, our function call statement will be like : # value 5 is being sent as argument calcSomething(5) ‘Another function call for the same function, could be like : as7 : calcSomething(a) # this time variable @ is being sent as argument it is ters. Carefully notice that number of values being passed is same as number of parameters. ti 5 a function call in Fig. 3.1, the last line of the program uses ome Ao i function call statement.) patton statement. (print () iS using the “ee a we aaa Consider one more function definition given belo a “ew 3 #ecube of value in * eat return return the computed value ee return res es COMFUIrR NS iy a ee eee” takes one argument. yg, .bove function Jnown below ‘As you can make out a el id be similar to the ones sl its function call statement iteral as argume @ —— i # it would pass V4 cut int in function call ue as 4 to argument x in function call (a Passing variable as argument in func num = 18 cube(num) nt x # 4t would pass value as variable num to argume i {tin function call (ii) taking input and passing the input as argument i ; é ")) = int (input ("Enter a number :"). atx e(eyrum pee pit vould pass value as vardable mynum to argumet ii it function call inside another statement So a (3) will first get the computed result print(cube(3)) # cube #which will be then printed ‘The syntax of the function call is very similar to that f (e) using function call inside expression the declaration, except tat double OfCube = 2 * cube(6) ‘the key word def and colon # function call's result will be multiplied with 2. (+) are missing. 3.2.2. Python Function Types Python comes preloaded with many function-definitions that you can use as per your needs. You ~~ can even create new functions. Broadly, Python functions can belong to one of the following three categories : }. Builtsin functions These are pre-defined functions and are always available for use. You have ~~ used some of them = len), typet J, int), input ) ete. 2. Functions These functions are pre-deti i ; cei ead eens ate predefined in particular modules and can only be ponding module is imported. For example, if you wart inctions inside a module, say sin(), you need to first th (that contains definition of sin( ) ) in your program. «modules _ to use pre-defined fur import the module mat 3. User defined fonctions your own functions” the programmer. As programmers you can create In this chapter, i 5 You will I i them in your programs, “© “Tite Your own Python functions and us? ~ STRUCTURE OF FUNCTIONS ~riP Progress In Python 3-1 making anatom You'll be \y of Pythe : "u'll be required to practice about structure of ae functions clear to you. lons. Please check the practi Practical Science with Pyth component-b, Yhon and fill it there 1 COOK ~ Pro. Practically donee I.PrP 3.1 undor Oh combuter i und it on the computer. Chapter 3 after D DD oece DEFINING FUNCTIONS IN PYTHON 7 2 Ny i Tewrite its code, In the following lines, we are about in Python. Before we do that, just r Ina syntax language : to give the general form ie, femember these things item(s) inside square brackets [ J is opti : ional, i.e., can be omit | items/words/punctuators outside <> and Met C1 have to be written as specified, A function in Python is defined as per following general format : def ( [parameters] ["" " [] For example, consider some function definitions given below: def sum (x, y) : s=xty returns Or def greet( ): print ("Good Morning!" Though you know about various elements in a function-definition, still let us talk about it again. Let us dissect these functions’ definitions to know about various components. Parameters inside( ): Parameters inside( ) Function name jo argument here Keyword de Funetion name ore Keyword def + i _eperg Sarde def sum (x, y) = — ~ Facies Heke print("Good Morning!") ( ends wit : se=xty return s\n Boy Geet in function body (See all statements in function (eet same level of indentation) statement Function may or may not have @ retire ater ks define these terms formally + ae def and ends with a colon Z of and end Aanction Header The first line of Lm» Ma COMPUTER SCIENCE WITH PrTHey 98 oe sn 8 antheses of a function header Variables that are listed within the parenth aaa ao ents be! function header th. tements / indented-statements beneath fun tt dt action performes return any The function body may or may NO unction returns 2 J turn statement, €.g~, above given ‘sum() is returning, ed in vara function greet( ) is not rel ‘A function not returning expression or value. Examp _Aindentation ‘The blank space in the beginning block, All statements within same = Body The Block of my by the function value. A function returns a Value thy, ough turning, a value, i HI have a return statement without, any value can stil vee below will make it clearer. of a statement (convention is four spaces) with block have same indentation. ing Let us now have a look at some more function definitions. +# Sample Code 1 def sumof3multiplesi(n) = sen¢ien*2+n*3 a One oth these functions are doing the same thing BUT on -_ + return s {first one is returning the computed value using return statement and second function is printing the computed value 4 Sample Code 2 a using print( ) statement def sunoF3Multiples2(n ) : sen*1en*2en*3 print(s) Consider some more function definition: # Sample Code 3 def areaofsquare (a) : # Sample Code 4 returna*a def areaOfRectangle (a, b) : : return a*b ‘## Sample Code 5 def perimeterCircle( r) ; return (2* 3.1459 * n) # Sample Code 6 def perimeterRectangle( 1, b) : turn 2 * # Sample Code 7 —_— def Quote( ) : print("\t Quote of tf int" he Day" print(“Act without Beet Print("\t -Lao Tzu") . For all these funy ® function defini casually, while reading them)” "Y entifying thei ; it parts. (Not as an exercise, just 40" A function definition defines a user o 43! structure of a Python Program 9 The structure of a Python shown below : Program is generally like the one “Hemera prog main. * def function1( ) : def function2( ) : def function3( ) : Python names the segment with top-level ‘statements (no identation) as _ main Python begins execution of a program jrom # top-level statements here >, the top-level statements i. from statement1 ' ain statement2 ‘ea Python stores this name in a built-in variable called _name__(ive., you need not declare this variable ; you can directly use it). You can see it yourself. In the _main__ segment of your program if you give a statement like : print( _name__) Python will show you this name. For example, run the following code and see it yourself. The top-level statements, i the _main_, def greet( ) : sega of hs Po rao Sohn caccutin ofthis program from the segment print("Hi there!) print (“at the top-most level right now") ay print("Inside” ,__name_) Upon executing above program, Python will display © At the top-most level right now Inside __main, ee = ie word *_main_ in Seen en Thins the result of tterent interpreter print. —eaie_) COMPUTER SCIENCE WITH PATON 100 7 TION IN A FUNCTION CALL flows (ie. the function is call Iues being sent enc flow of execution of statements) in ca Se 0f, ied (or invoked, or executed) by provig Tosed in parentheses. For instance ety 3.4 FLOW OF EXECU out how the control ready know that 2 followed by the val we header looks like = Let us now talk abs function call. You al the function name, invoke a function whos def sum (X,Y) = the function call statement may Took like as shown below = sum (a, b) jon sum( )- where a, b are the values being passed 0 the functi ‘ow see what happens when Python interpreter TT ratement. ‘The Flow of Execution refers the order in “which wae | are executed during Spas Let us n encounters a function call st ‘The Flow of Execution refers to the order in which statements are executed during a program run Recalll that a block is a piece of Pyth executed as a unit (denoted by line in body is also a block. In Python, a block is execute on program text that is \dentation). A function din an execution frame. The Flow of Executic An execution frame contains : the orde ‘ich aaa are executed during a program © some internal information (used for debugging) © name of the function = © values passed to function © variables created within function © information about the next instruction to be executed. Whenever a functi created and the aye is sonnet an execution frame for the called functionis frame, the statements in control) is transferred to it. Within the function’s execut 7 the function-bod: the function’s execution statement i ly are executed, and wii oe of function body, the control returns to tht ‘ith the return statement or thelast, led, ie, as: e statement wherefrom the function def func( ) : return #_main__ tied print(..) x to ts m ng ram 10 add 60 numbers through « fun, unction prog program add. py to add two numbers th | a def calcSum (x,y) : "OUR a Funct, | Wrage | ~ saxty scion returns # statement 1 ay | # statement 2 et : fe & unit eee Enter first number :» Sean un = Float (input "Enter second nunber » = sum = calcSum(num1, num2) a): yy Peat) print ("Sum oF tH given numbers is", suqy cae > Sum) fenent 3) im execution begins with first statement of Progr ements a main, res. coe Se ve also read but ignored uni |) ant ewill become clear to you ina few moments, just read Just reay al | oI . ' in aoe oe | pease note that in the following lines, we have put up some we specution frames for understanding purposes only; these are AMoased on any standard diagram.) Number indicating next statement to be executed J _main__ (add.py) 2 Python Console enter first number : 3 1+ float(input("Enter first number :")) — gi float(input("Enter second number :")) I ells the currently ‘executing statement sa=caleSum (uml, num2) | | vrit("Sun of two given numbers is", sum) Statement 1 exeuted — This is datgpart of _main_ python Console | _nain__ (add. py) 3 Meg y Feat “Enter first number :" )) | enter tg. atlinput( “Enter second number + | *alesum (ny um, Sy 1um2) | m r °f tho given numbers is", sum) Enter first number + 3 second nunber 7 conpureR SCI 102 ‘caleSumt Pum eateSumt main (204.PY) Ninth a ht 4 ; oy) ; senter First number numa = Float neue per") csum (x, y) | enter second number * ca on num2 = float (input ("E ne --- Lo vom = calesum (ound, 9UR2) ~~~" saxty | prine("sum of two given numbers °°" | return 5 Data | = 3.0 =7.0 Internal Memory Jamon eaeSumt Pam oy LA ge + 7.0=10.0 > TS statement 1 of cin sexty- body executed ~ in memory ee lion body, control returns to the point wherefrom the ih st statement of func in ee if last statement of function body is a return statement x= 3.0 tion was called. Since the ee Jaton es yale ois ven back 10 _rnin__ which sores 0 rer mpees the execution of sialement Sof main a _main_ (add..py) Le uml = float(input("Enter first number : una = Float(input("Enter second number : “sum = caleSum (num, nun2) N= | print(“Sum of two given numbers is", sum) ccaleSum (x, y) sexty | return s - — Data: | numl = 3.0 (um = 7.0 aes sum Reirun value ofealeSumt ) gers stored in sum variable of _ ain 10.0 main ee | — - —nain__(add.py) | | Python Console ‘num = float (input("Enter first number :")) nun2 = float input( “Enter second nunber :*)) sum = calcSum(num, nun2) |: Print(*sun of two given nunbers is" is", sum) "Data: - > Sum of two given numbers 0? uml = 3.0 | Le t ‘fum2 = 7,1 \ dil anes 100 | sree | eet yor So we can say that for above program the « TENS Were ex a Ye Program the state rent " S Were executed *main2 > main3 + catesum Sum2—> main3 + mains in, ‘alcSum.1 lc (As you can see that we have shown a stateme: Now that you know how execution: NE AS its «statement ) unctions are executed int Tally, let us discuss about actual flow of Ina program, Python starts re. ‘ading from line time, in order from top to bottom, Wane em om. While exe, © Execution always begins at the © Comment line: a downwards, Statements are executed one ata SUN 4 Program, Python follows these guidelines : first statement of the S (lines beginning with a # non-blank lines are executed. VR # 4) are ignored, ic, not executed, All other © If Python notices that it is a fun s ct executes the function header line ee to determi it skips/ignores all lines in the function eee that it proper function header and © The statements inside a function-body are Program. ion definition, not executed until the function is called. © In Python, a function can define another function inside it, But since the inner function definition is inside a function-body, the inner definition isn't executed until the outer function is called. ® When a code-line contains a function-call, Python first jumps to the function header line and then to the first line of the function body and starts executing it. © A function ends with a return statement or the last statement of function body, whichever occurs earlier. © If the called function returns a value ie, has a statement like retum (e.g., return a or return 22/7 or return a +b etc.) then the control will jump back to the function call statement and completes it (eg, ifthe returned value is to be assigned to variable or to be printed or to be compared or used in any type of expression etc. ; whole function call is replaced with the return value to complete the statement). oe © Ifthe called function does not return any value i¢, the retur statement has no variable oF value or expression, then the control jumps back to the line following the function ca statement. i ited IF we give line number to each line in the program then flow of execution can be represent just through the line numbers, ¢.8-, as through a function Te! \dd. py to add two numbers "poder 2 derealesim (> atone g : : ement 2 4. returns # state ar . #1 (statement 1) QR Code inter first number :” » numt = float (input ("E 2") #2 (statement 2) cone .cond number :" )) 7. num2 = float (input ("Enter se ee) 8. = calcSum (num, num2) ; 2 Ee °. a it ("Sum of two given numbers 3 print OARNCE HTH PTO Computer 7 tracing the p es known as tracing the program. A er is also sometimes spe execution on PaPtr above program can also Pe represented as follows Determining flow of pave discussion the flow of execution 2767 7 8723 32.4 3839 ed and executed executed and determined that itis a function is a comment ; line 2 is ody (ie, Hes 3 and 4) is ignored: Fines 6,7 and 8 executed; line 8. ine 2) and then to first line of fhe function header ( * line 4 to line containing function call statemen, function el Line 1 is ignored because header, so entire function-t ‘2 function call, so control jumps to # function-body, i, line 3, function returns afte ie., lines and then to line 9. called the caller and the function being that the function calling another function is main__is the caller of caleSum(, Please note ‘allee). In above code, the _/ | called is the called function (or function. 3.4.1, Arguments and Parameters you define variables to receive | |As you know that you can pass values to functions. For this, Values in function definition and you send values via a function call statement. For example consider the following program : def multiply (a,b): print (a*b) 2 ys3 multiply (12, y ) # function call -1- multiply (y, y ) # function call -2- x=5 multiply (y, x) # function call -3- You can see that above program has a function namely multiply receives two values. tiply() that This function is being called thrice by passing different values. The three function calls for multiply( ) are : multi mately (ay) # function call -1- ae a ) # function call -2- | 7 px) # function call -3- | ith function-call 1 i | l, the variables a and b i —— in function header will receive oe e values 12 and y respectively. the variables a an db in function header will receive values y and y respectively With function-call 3, the y, pectivel the variabl i *s @ and b in function header will receive r | values y and x respectively: As you can see th : at there received (in function definition ee ees ition). 4 © arguments: Python refers yi us defi e WORKING WITH FUNCTIONS 105 Arguments in Python can be © literals. one of these value © variables But the parameters in Python have types © expressions 'o be some names i, variable: hold incoming values, . les to hold incoming v. ter and actual argument. Alternative argument. So either you use the word the combination actual parameter and ar, Thus for a function as defined below - tal def multiply (a,b); print (a*b) ‘The values being passed through a The following are some valid function call statements : “function-cail state . @rguments (or actual parameters multiply( 3, 4) #both literal arguments acta organs The ve = feeeived in the function défntion/ | Treader are called parameters (or multiply( p, 5) #one literal and feeb eee or ‘ermal # one variable argunent “arguments multiply(p,p+1) — #one variable and # one expression argument But a function header like the one shown below is invalid : def multiply (a+1,b): : Eno! A function header cannot have expressions. tea have just names or idemifes to hold the incoming values. Please remember one thing — if you are passing values of immutable types (e.g., numbers, strings etc) to the called function then the called function cannot alter the values of passed arguments but if you are passing the values of mutable types (e.g. list or dictionaries) then called function would be able to make changes in them’. FUNCTIONS’ BASICS Progress In Python 3-2 a wning the functions’ basics like : functions’ ion is aimed at strengthe ‘o lw of execution during function calls. This ‘Progress in Python’ sessi terminology, function anatomy, argument vs parameter and fl ji t-book — Progress in Computer Please check the practical component-book » Progress 9 Compare Science with Python and fill it there in PriP 3. : practically doing it on the computer. ppoecce : 1d Call by Reference. In Call by similai i £ two types Call by Value an‘ Incl isi il jon call mechanisms, which are o! a Fists somewhat similar to function Oe Tes a separate copy of passed values arte oh sae ivi main ag a Call y Reference mechanism, the called function wo unchanged. But wit ; ; any changes made, take place in original sai oO on In Python, immutable types implement Call By Value types implement Call By Reference mechanism. and mutable’ 106 RS PASSING PARAMETE! call must provide all the values as required by fang, 35 fee ers named in its headey Uptill now you learnt ae etunestcn header has three Paramete a ned es then cae Fe ahoall aso pass three values. Other than this yt simone all should a Cee aa recading and matching ase uner a and pai oe eee | arguments/parameters ena?’ Python supports three types of Forma! 2 8 7 Fe 1 Positional arguments (Required arguments 2. Default arguments 3. Keyword (or named) arguments ie Let us talk about these, one by one. os, 5.1 Positional/Required Arguments 3.5, function call statement for a given funcin hat when you create a Till rou have seen tl efnition h the number of argument definition, you need to mate! ; For example, if a function definition header is like : ts with number of parameters requiey def check (a, b, ¢) ? then possible function calls for this can be : check (x, y, Z) #3 values (all variables) passed check (2, x, y) #3 values (literal + variables) passed check (2, 5, 7) #3 values (all literals) passed See, in all the above function calls, the number of passed values (arguments) has matched witt the number of received values (parameters), Also, the values are given (or matched) position- wise or order-wise, i,, the first parameter receives the value of first argument, second parameter, the value of second argument and so on C8, ‘ In function call 1 above : In function call 2 above : In function call 3 above ° ; will get value of x © a gets value of 2; © a gets value 2; © b will get value of y © b gets value of x; © b gets value 5; © cwill get will get value of z © c gets value of y © c gets value 7 Thus, through such function calls, © the arguments must be Provided for all param i © the values of arguments are matched aA en Position (order) wise Positional oo This way of para aM meter and ay Positi Tgument specification j. onal arguments or Required ne is called “# * Mandatory arguments as no value cay © skipped from the inction cal $No value can be sk; Ped from the functi n call i order of first argument to third Params 2°8CANMOt assign value " sfoull Arguments 2 De 107 57 at it we alteady Know the value for g certain wh yn, we know that mostly th Par fart" | 'y the rate of inter, ameter, ¢ e this value as the default val est is 10%, 8» in an interest ¢ defi tue. then there should ben pattlating vision to def interest (principal, time, nate =a » Pate = 0.16 This és default value for para in a function cal, the value for rate value for parameter rate, : ite. in non cat, or rate "0% Provided, Python wil the missing © (for rate only with his value The default value is specified in a manner syntactically cir. to a variable initialization. The above fanetion decent ieee ion provides a default value of 0.10 to the parameter rate Non-default arguments . npumerts rte Now, if any function call appears as follows : fellow default argument, ee si_int = interest (54¢e, 2) # third argument missing then the value 5400 is passed to the parameter principal, the value 2 is passed to the second parameter time and since the third argument rate is missing, its default value 0.10 is used for rate. But if a function call provides all three arguments as shown below st int = interest (6100, 3, 0.25) #no argument missing Co ex principal gets A then the parameter principal gets value 6100, time gets 3 and the parameter rate gets value 0.15. A parameter having. default value in the function header i That means the default values (values assigned in function __{nown asa default parameter. header) are considered only if no value is provided for that parameter in the function call statement. One very important thing you must know about default parameters is : Ina function header, any parameter cannot have a default value unless all parameters appearing on its right have their default values. ; vf function For i a zntioned declaration 0 ees instance, in the above met ss default interest( ), the parameter principal can " f having 2 default : Pa et, time and rate alsO parameter i Value unless the parameters on its right, # veer time yoke neon header the para “pecomes optional in function have thei imilarly, : We their default values. Similarly, © rameter on is Em et oF cannot have its default value unless *é mach condition ees ye fork Tight, ie, rate has its default value. There is n° 1 its right. for rate as no parameter appears on its rig! fore default parameters Thus, required parameters should be Ps . eaders with default values ples of function Following are exam] pice) rin, time, rate = 9.10): # illegal (default paramete, oe a ing time =2, rate) ? # before required parameter) ! def interest (prin : 1 : # illega. ! det interest (prin= 2000, time = 2» a # (same reason as above) i = def il # legal = 0.10): Da ges anterest (prin, tine 2, rate = 68 ey aee get interest (prin = 200, tine = 2» 7 is here some eons = wit arguments are useful in stustions ner ovide aa eee caramels e the same valu ee ee F listed below parameters are considered oq Some advantages of default parameters are I ' parame conto 2 & They can be used to add new parameters t0 the existing parameter in the function ca ons. statement. | functions. ; © They canbe used to combine similar functions into one. 3.5.3 Keyword (Named) Arguments The default arguments give you flexibility to specify the default value for a parameter so that it can be skipped in the function call, if needed. However, still you cannot change the order ofthe arguments in the function call ; you have to remember the correct order of the arguments. To have complete control and flexibility over the values sent as arguments for the corresponding parameters, Python offers another type of arguments : keyword arguments Python offers a way of writing function calls where you can write any argument in any order provided you name the arguments when calling the function, as shown below : interest (prin = 2000, time = 2, rate = 0.10) 5 (interest (time = 4, prin = 2600, rate = 0.09) interest (time = 2, rate = 0.12, prin = 2000) Ea All the above function calls are valid now, even if the ord the order of parameters as defined in the func Se tion header. In the Ist function call above, Prin gets value 2000, time gets value as 2 and rate as 0.10, In the 2nd function call above, Prin gets value 2600, time gets value as 4 and rate as 0.09. In the 3rd function call above, named arguments with es valties being passed in function cal statement. ee ea y 4 Using Multiple Argument a python allows you t. Types Together 109 ython allows You to combine mut following function call s 1 ultiple argu, 8 Statement that is using both oe joee® 8 Function call. c interest (5000, time = 5) Positional (required) and yond oe the irguments gules for combining all three types of arguments Python states that in a function call statement: argument. " Positional (required) arguments followed by any keyword © Keyivord arguments should be tak 8 en fi 7 arguments preferably. ae Caras ® You cannot specify a value for an argument more than Having a postonal arguments once. after keyword. arguments : result into error. For instance, consider the following function header : | def interest( prin, cc, time = 2, rate =@.09) : return prin * time * rate Itis clear from above function definition that values for parameters prin and ce can be provided either as positional arguments or as keyword arguments but these values cannot be skipped from the function call. Now for above function, consider following call statements : Legal / \ Function call statement itegal Reason i values pr ed arguments i interest(prin = 3000, cc = 5) Tegal _| non-default values provided as named argument | keyword arguments can be used in any order and interest(rate = 0.22, prin = 5800, cc = 4) | les for the argument skipped, there is a default value ‘with keyword arguments, we can give values in interest(cc = 4, rate = 0.12, prin = 5000) | legal eee Ieres(son, 3, rate = 0.05) ipl pineal ea ae tional arguments interest(nate = 0.05, 5000, 3) illegal _| keyword argument = ea : sn = interest(5ea0, prin = 300, cc =2) illegal Multiple werent and again 2 Keyword argument illegal ndefined name used principals not a pararste) ‘ sing. interest (5000, principal = 300 ¢¢ Tegal | A required argument (cc) is mis as ae interest(5e0, time = 2, rate COMPUTER 110 reates and Now consider the following program that discussing so far ssinga function interest( cis pecify default value late simple interest ie interest. DO Sk 3.2 Program to calcul "i and ate and returns calculated simp! fogom 2 years vespectvell =0.10) : def interest(principal, time =2» rate = 0-10) return principal * rate * time # main : prints float (input (“enter principal amount :")) ; print("Sinple interest with default ROI and time values 35 interest (prin) sit print("Rs.", sil) roi « float (input(“Enter rate of interest (ROL) » ‘time = int (input( "Enter time in year: print("Simple interest with your provided ROI and time values is :") interest (prin, time, roi/100) » sil print("Rs.", si2) Sample run of above program is as shown below : Enter principal amount : 6700 Simple interest with default ROI and time values is : Rs. 1340.0 Enter rate of interest (ROI) : 8 Enter time in years : 3 Simple interest with you i ur pr i sae your provided RoI and time values is : RETURNING VALUES FROM FUNCTIONS Functions in Python may or may ly Hoo types of functions in Python : some comp ed usin, iS ret return 6 es | value in : . = : ea va al, Python will ot f0FE A ypcon turing 3 UE We, jive a stand-alone func , sce fruitful functions. : ue is completely wasted. also known as tio error but their return val nz seution even ction! 100 46 0h tatement ends a (ancHn er vrady the function call «f+ funeteg he return state ction. 6 ee gents I returning rm vale the middle of the Tr rry r al otat tnher expression or sigue ee hres a return hichever occur Waterson ramen it each ecuted, 0 function will be executed pat " have been ¢ each paint) ong funetion-body tion will never! return vale i be vm 1, following, fel jut Python will not repo aera & earlier, (8+ ached! before et " 00" sep a tatement as serait 4 ae def check (a) ae math. fabs(a) Iuabe because eheek) function return a will newer cearh thi ae all ead withe cotirnt ane cameo check(-15) (Void functions) ion or do some work but donot return any compu; functions. A void function may or may ny ment, then it takes the following 2. Functions nol returning any value The functions that perform some act + caller are called voi value or final value to the caller oi ; cnt, Ha void function has a return state fave a return stat form Fare wid function, return statement dees mot have any eturn <—————nefespression being returned. that i, keyword return without any value or expression. Following are some examples of vid functions Another void funetion with no eetursstaeen veld funtion but ‘nore tener def greet ): def greeti(name) : — APS print(‘helloz") print("hello", name) void fasion with ret stsemen def quote( ) : def prinSum (a, b, c) : SPS print ("Goodness counts! !") print("Sum is", a wore) return return Another void fustie swith a reuur tae The void functions are generally not use function call statement is standalone defined void functions, 'd inside a statement or expression in the caller ; helt complete statement in itself, e,g., for the all four abo" the function-call statements can take the form : * greet () greet1( ) A eS 2 00 ca se that all these faction ea ae 01 part of any other expresion or satement The void functions d lo not return a val None. Every void fun, eee ne a 'Y return a legal ue of Py" vem Every returns value None to j fase " ts caller. So if need arises you can assis" uted, Y not Wing void tion heir ove jeer his jan 2 MORKING WITH FUNCTION i 3 def greet( ): print (*helloz") n3 reet( ) print(a) tre above Program will give output as helloz None yes, you guessed it right ~ helloz is ri as value stored in a because greet( a inted because of gree returned value None, (0's execution and None is printed Consider the following example : which is assigned to variable a. ie 1 ay # Code 2 ef replicate() : def replicater() : print ("$3835") return "$$555" print (replicate()) Print(replicaten()) Here the outputs produced by above two codes will be Outputs: Code 1 oo ooo sssss None Iknow that you know the reason, why ? So, now you know that in Python you can have following four possible combinations of i) non-void functions without any arguments 1) non-void functions with some arguments tA void functions without any arguments vi void functions with some arguments Please note that a function in a program can call any other function in the same program. 36. Returning Multiple Values Unlike other programming languag function, Isn’t that useful ? You must return more than one value from a thon lets you pute Now 7 Let’ find out be wondering, how i re following things : To return multiple values from a function, you have to ensu i¢ Id be of (9 The return statement inside a function body shou! able1/expression>, the form given below : eyalue2/variable2/expression??, ~ return 7 num3 E+ 5 8 Proved vel) value 5.0, prints it and program {ll also be removed.) Nee © POHG My o mt? _ lifetime of 4 ther term ~ li : vant to introduce another os Here we want rt me for which aVAriaBle The ee or yheh gy varie Telietimeof te sabes Or trime is entite name vemamr nt lives in memory. For global TT tong asthe programs salled fete ansmerey | | Iregean an (hey vem MEMOTY 3 owen = Fanning) and for local variables, lifetime is their "| on is being executed.) (e,, as long as their functi fa Name) 3.8.1 Nome Resolution (Resolving Scope ©! ie, when you access a variable from wig ence within a program, i, ‘a Python follows name resolution rule, also known as LEGB rule. Tha, Python does the following to resolve it: 1 environment (LEGB) ( or local namespace) if it has a var its value. able For every name refer program or function, for every name reference, () Tt checks within its Loca with the same name ; if yes, Python uses i If not, then it moves to step (ii). {i Python now checks the Enclosing environment (LEGB) (eg., if whether there variable with the same name) ; if yes, Python uses its value. a If the variable is not found in the current environment, Python : repeats thi higher level enclosing environments, if any. ee D Ifnot, then it moves to step (ii). (iil) Python now checks the Global enviroi 4 ment (LEGB) whether there is a vari the same name ; if yes, Python uses its value. d ee If not, then it moves to step (i0). (io) Python checks its Built-in envi uilt-in environment (LEGB) that contains all built-in variables and functions of Python, if i ‘ say 'ython, if there is a variable with the same name ; if yes, Python uses is Otherwise Python would report the error : name < variable > not defined. ay . conte: 3: WORKING WITH FUNCTION Let us consider some exam, amples to Understand thi ‘gy s. case 1 : Variable in global scope buy . Let us understand this with the help def calcSum (x, y) ; Print (numa) Penida 2 ‘arab mum sas | return s statenent -2- arable # statement -3- } num = int (input( "Enter Fin. num2 = int(input( “Enter sec print ("Sum is", calesum (nus st number :*) y ‘ond number ») m1, num2)) 1. Python will first check the Local environment of calcSum() for num! ; ff Aobal Environment num1 is not found there, (sees Local Enviroment 2 : ue ronson d 2. Python now checks for num, ——> pees 1 the parent environment of ene > Geie —S calcSum( ), which is Global \ environment (there is not any ro ci bead intermediate enclosing environment (attempt) environment). Python finds num1 here ; so it picks its value and prints it. Case 2 : Variable neither in local scope nor in global scope oe What if the function is using a variable which is neither in its local environment: ‘nor inl Parent environment ? Simple! Python will return an error, ¢g., Python will report error name in the following code as it not defined anywhere : ‘This would retur eror as nar is neither in def greet( ): enroll enone print("hello", name) greet( ) globo! scope ahigher level scope, i as well os in Cose 3 ble name in local scope : Same variable ae ent statement and i there in inside a function, you assign a value to aname which is already Ifinside a Y i use it is an assignm Python won't use the higher scope variable bectire A coment. _ aaa assignment statement creates 4 variable by default in COMPUTER SCIENCE WITH Prt, For instance, ler the following code read it carefully consid iB ‘or i , tatel( ) : oe Global Environment pee nee) ees eee ‘Tis statement will create a for statei( ) local variable with name eae Celene Cho see stmais pogum. print tigers statel() print(tigers) ‘The above program will give output as = Result of print statement inside statef() function, 95 tes se of alegre is rine. | 15 95 Result of prin statement inside main program, ee age rd That means local variable created with same name as that of global variable, it hides the global variable. As in above code, local variable tigers hides the global variable tigers in function statel(). What if you want to use the global variable inside local scope? If you want to use the value of already created global variable inside a local function without modifying it, then simply use it. Python will use LEGR rule and reach to this variable. But if you want to assign some value to the global variable | without creating any local variable, then what to do ? This is PMO Ese because, if you assign any value to a name, Python will create y , Pytt The global statement & | a local variable by the same name. For this kind of problem, declaration which hold fr 3 Python makes available global statement, entire current code biock © To tell a function that for a particular name, means thatthe tated ert local variable but use global variabl " are part of the global nam — al ariable instead, you need to ‘or global environment. do not create a global For example, in aby P you need fo add global anna You want function statel( ) to work with global variable ges ‘ment for tigers variable to it as shown below : def stater() : > Blobal tigers = ‘This isan indication not to tigers = 15 a : Toca Mme / St cm slobal variable tiger, tigers =95 f Heers 36 Local Environs t Bis for statel( Print(tigers) \ state1() \ print tigers) | Xu 7 WORKING WITH FUNCTIONS ponte ‘te above Program Will give output ag ich was modified i The global statement ol ee ch nd pt! Rae he Boa i815 now) is printed, “atement in Python mean once a variable is declared global in a funct indo the statement. That is, after pene ae EIRP Pe: function will always reer tothe global variable sad fog variable cannot be created of the same name tecosea ey rales n be Accessed trough ual eaee ee But for good Programming practice, the use of global __*,8,00.* 600 proarmmig statement is always discou raged as wit Practice. So, keep global variables ith this pr a : tend fo lose the control over Saciatas” Programmers global, and local variables eat and their scopes, CALLING FUNCTIONS, ARGUMENT TYPES, SCOPE OF VARIABLES 0 Progress In Python 3.3 This ‘Progress in Python’ session is aimed at these concepts : calling or irooking function, diferent ‘apes of arguments, scope of variables and Name resolution by Python. Science with Python and fill it there in PriP 3.3 under Chapter 3 after practically doing it on the computer. voobece 39 MUTABLE/IMMUTABLE PROPERTIES OF PASSED DATA OBJECTS ow a function returns value(s) to ¢ Please check the practical component-book — Progress in Computer » Sonow you know how you can pass values to a function and h netion its caller. But here it is important to recall following things about variables : © Python's variables are not storage containers, rather Python ae are like memory references; they refer to the memory address where the value is stored. i lifferently © Depending upon the mutability/immutabilty ofits data tyPe, a variable behaves differently ir change in its value will also is i sutable type then any chany eso daieseneeeteets meee but ifa variable is referring to mutable type then. itis ‘ if the variable change the eae type will not change the memory address ofthe vari any change in the value of mut me. a (recall section 1.7). Following figure as9 ios apply tothe identfs or the name ae i vv ig that the scope rules PI ue 5 to a function ange «se know here is that int a with value 5 1 ae ew yor example, ou pas aR are me value (ie 5) in data space Is and not on the values. Ta and B il fe 1 8m ing upon (rn at cet pen hey a en with different scopes, ide Mutability), but, you can use name b ony we discuss mutal ition, This will become clearer £0 YOUN" and parameters in the section 3.8 summarizes the s bility wi COMPUTER SCIENCE WITH Prtticy, 124 me predefined locations) dat so! Is are store’ (Integer literal or of ferences — aes 148264 148260 148295 Nun a pe gia ref Code Lista = [1, 3] vai Lista 200160 oT t iT Listt has been allocated address 200160 where it ‘can store memory references of its individual items e.g., List[0] currently stores here the memory reference of integer valuet (i.e., 148216) and List[1] stores the memory reference of integer value 3 (ie, 148248) vart stores the memory reference of integer value 1 (ie., 148216) as itis currently storing 1 ‘Now if you make following changes to List] and Varl : vari=vari-1 (Now vard holds value @) Listt[o] =3 (Now first item of List is also 3) a 148232 3 aguante 148264 148280 148296 = Lists memory < holding address Liser 2001602) remains ite so" 9 zy addresses | vart now stores a Address of integer 0 The mem the, 14820 ory allocated to List1, where it can hold its data items memory a ; ae india mains the same ie,, it still is 200160, BU items’ memory adi items of List? have changed so individual both Listt[o) ana dresses stored here have to reflect this. T™® 148248, the mer Ustt[1] are currently storing memory rd ust Address of integer 3 as both List1[0] Currently hold integer value 3. Figure 3,4 Impact of M ind Immutabitity ~ Of Mutability and 1 iti i »y Let us understand this with the help of some sample codes semple Code 1.1 sample COCE = | Passing an Immutable Type Value to a function 1. def myFunci(a): 2 print("\t Inside myFunc1()") | 3. print ("\t Value received in ‘a' as*, a) 4 azat2 | 5. print("\t Value of 'a' now changes to”, a) 6. print ("\t returning from myFunci()") 7. #_main_ 8. num=3 9. print("Calling myFunc1() by passing ‘nun’ with value", num) 18. myFunc1(num) 11. print ("Back from myFunci(). Value of ‘num’ is”, num) Now have a look at the output produced by above code as shown below : Calling myFuncl( ) by passing 'num' with value 3 Inside myFuncl( ) Value received in 'a' as 3 The value got changed fon 308 inside nation returning from myFuncl¢ ) : Back from myFuncl( ). Value of ‘num’ is @) €- passed value in parameter a and then Inside myFuncl(), the value (of a) As you can see that the function myFunc1() received the passed variable mum remains changed the value of a by performing some operation on it : Bot changed but after returning from myFunc1\( ), the origin. unchanged. ted for above code (ie., sample codel). i ts are creat Let us see how the memory environmen! mory E at For Sample Cod Memory Environment FOr 98 eis an integer, an imm' able type) Iue is an integer, (Note : Passed val e count pemony adaresses wil yar 033? (rere count nha man aso soo 816 032048 tne | trontloaded [3 3) [6] ata spoce | Global Environment Till Lines 7-9 of code of ~main.. (2)« reference count 332064 — ae wom IT) At line10 (function is called) argument | rum is received in parameter a and ty ines 1, 2, 3, environment remains the Environment same (myFunct0) eto epace topo — See, the global environments ‘num remains unaftected from changes to variable a of mytinct Aline 4 Local memory environment remains the same til line6 and te myfunc1( ) gets over and cont returns to —main— part's line! and the local environment of myfunc1() is removed. Local EnvmyFunet( )) a(va=a+2) sum's vate § Aline, winen num printed Python prints 3.45 0g remained unchanged it iS and thus always remain® -. oN * 3, WORKING WITH FUNCTIONS, sa 127 go, you just saw how Python process, oe pe ceed Fite le data type wen sequence/collection such as a fist internal YOU pass a mt 'S Passed as argument, can tfPe Such aa Hct. Rect fer, is st ¥ 'S stored as a container that holds the references of individual items.) sample Code 2.1 1 Passing a Mutable Type Value to g Function-Making changes in p ) s in place) 1. def myFunca(myList): 2 print("\n\t Inside catep Function now" a print("\t List received: > myList) a myList[o] += 2 s. print("\t List within called function, after changes:", myList) e return 7 1) at 8. Ast before function call : *, List) 9. myFunc2(List1) 38. print(*\nList after function call : *, List1) Now have a look at the output produced by above code as shown below List before function call : [1] : Inside CALLED Function now List received: [1] Uist within called function, after changes : List after function call @< ‘The value got changed rom [1] 0 [3] Inside function and change GOT REFLECTED to_main_ witable type, a list, this time. The As you can see that the function myFunc2( ) — pee ees fei A pe a 7 “ m ist eet reelected in he original st passe, ie, in insi ion in the list mi changes made inside the function in list] of _main_. tn a ion, the changed value. The i function, it shows ns it returning from t are refelected back in “ason is clear — list is a caller function. ironm Let us see how the memory environ ents are cr above code (ie., sample code2.1). eated for ab (ie, code2.1) COMPUTER SCIENCE wi 128 Ce Wm Prion | oy Memory Environment For Sample Code 2.1 (Note + Passed value is a list, a mutable type) (1) «reference count 72508608 . eS ———_ Morr) adasses ‘atrermemory |. 0} 1) [2] [3] [4] on 28h computer an ateratons : Yon foreach seat FF at ts mene asin ey 2 z 0 540558 572 588 _ 604 25000, At line, tuncti Luneton myFune2 Caled argument ith cof parameter myList. Both now poiny ‘ ‘adress 26 IMA Ee 4 0. For ines 1,23 ‘environment remains the same Global Environment d . ee Local Environment (myFunez(0)) At lines, myList changes to 3 (myst 2) and thus the Oth tro ImyList now holds referee of value 3. BUT the mer location of ist myst remains the same (2500 The change of mency ‘adress from value 1 value 3 has been done in place i. same location of mylist (i@ memory environment remains the sa lines 5, 6 of code and then funcion ru controi_main_'s line 10, remaining environment of function myFu (Ust1[0] now holds memory address of value 3 (588)) (rmyFune2()) imyList At ine 10, when List is pied referring to address 25000 31 currently holds reference OF VOR Hence changed list is printed (®5°°° sag WORKING WITH FUNCTIONS cis" 129 address 25000 fo: r both lists (argume , the very essence of mutable oe 7 f so changes in memory references occurred at the same “ej parameter) and hence got reflected in — main. similarly, if you make other changes such as addin, a or deleting it ‘ull also get reflected back as both the passed list creument = tems from a passed list, these with the same memory address where changes are done in place. oan Eee list work ck follow Watput ~ changes are reflected back in __main. ing code and its ample Code 2.2 . Passing a Mutable Type Value to a function ~ Adding/Deleting items to it) 1. def myFunc3(myList): 2 print("\t Inside CALLED Function now") 3. print("\t List received:", myList) 4 myList .append(2) s. myList.extend([5,1]) 6. print("\t List after adding some elements:", myList) 7 myList.remove(S) 8. print("\t List within called function, after all changes: ", myList) 9. return 3@. Listt= [1] 41, print("List before function call :", List) 12. myFunc3(List1) | 13, print("\List after function cali :"s List) Now have a look at the output produced by above code as shown below List before function cat + [1] Inside CALLED Function now List received: (11 List after adding some eTemen List within called function, ts: (1, 2, 5) after all changes List after function call COMPUTER SCIENCE WITH Pry, 130 nent For Sample Code 2.2 ue “0 196 e190 vy aj 13) (a) 13) (8 tl L4 a J custo} nots — Inemory address of value 118, 316) ( oe Till Lines 10-11 of code of Mg 464 360.396 At ine 12, function myFuncq called : argument Listt is eco! in parameter myList. Both List ard myList point to same address Le., 38100, Environment remains t fires 1, 2, 3 Global Environment Local Envitonment (imgeunest)) At line 4, statement myListap- pend(2) gate executed, £0 2 now ment (index) is appended to mylss same memory address 38100 This new element now references value2. OT Mutable types act tke tainers. Container era unchanged, however, is > Global Environment © Local Environment ») myFune3() Nance even after appending a new element the lists ‘adaress 1s the same /e., 38109. It, however, now ‘accommodates place to hold new valve. a » lence het 316232 MB 364380396 ao sess overall address remains 37]. same as ts the conse” 7 address _ eviroment At lineS, the list is extended fa row elements (Listen The lst'smyList) menoY 29 sil remains the same 18: ty However, t now 2000! to hold two new elemens Environment remains $2 6100. lst of Local Environment | myst (myFune3()) a Meno'Y Environment For Sample Code 2.2 2 316 332348364 380 Lines 7.9 1 eee (Contd...) a 2) [3] [4] [5] Ale, staan ImyListremove(s) removes sem 5 fom ft ard ts ony ee elements are lett in List(myLisg) Bu the memory arse it (tis) romaine te ama oe afer changes int canon The envionment emai to some tna 9 and ton cont rouse inet Lista Global Environment Local Environment myList (emyFunea()) be —— At line 13, after returning from ‘myFunc3{ ) the local environment ‘is removed. The list. Litt is stit referencing the address 38100 with all the changes intact. Global Environment Sample Code 2.3 Passing a Mutable Type Value to a function - Assigning parameter to a new value/variable. ei 2 3. 4, 5. 6. 7 8 18, nl. 2. def myFunc4(myList): print("\n\t Inside CALLED Function now") print("\t List received:", myList) new = [3,5] myList = new myList.append(6) print("\t List within called function, Parameter list get assigned a new value (a list here) _ after changes:", myList) return Lista =[1, 4] print("List before function cal myFunc4(List1) a print("\nList after function call : » List1) 13: . COMPUTER SCIENCE WITH PYTHON Now carefully look at the output produced by above code as shown below : List before function call: [1, 4] Inside CALLED Function now List received: [1, 4] List within called function, after changes Isn't this uneypected, the passed value is of a mutable type, alist. Right ? But still the change, made in the function do not get reflected back to _main_. Why ? No worries. Lets find ou. But first have a look at the memory environments created for above code. The value got changed om [7 (3.5, 6linside tuncton and cag DIONOT GET REFLECTED 6 se List after function call Memory Environment For Sample Code 2.3 (Note : Passed value is a list, a mutable type) ee sl qa) [St se su Sh sos o2 (CF EGR oe th addresses of values they hold Global Environment Till Lines 9-10 of code of _main_ Lines 11, 1-3 At line 10, function myFunc!l) gets called argument Listt is received in parameter ™) Both List1 and myLis po same memory address ie» 4 Environment remains the for lines 1, 2, 3. ronment For sample “ 564 ch 580. a 596 ode 2.3 Local Evironment (myFunea()) 133 At ine 4, 2 new list by th "am@ News created or wich ‘memory is alocated at 50110 wn Listt ana mye Bot fo memory adiess 40115 13s memory address a rm om 50110, 532, 564 580 Tr = — 4016. sono 4) (2] [3] [4] [5] fe oT tT ———— ral ' = 5 Gtobal Environment | sy Environment mytist (myFunea() | At line 5, myList is as: signed new, which means it ‘now points to same address as new ie, 50110. wil ‘Local Environment i iu} MM © 40116 0110 7 —o 4 Co i 2 [4] [5] 3 Cel} tt 3 7 Al line 6, statement i t (myListappend(6)) a ‘adds value 6 af the end Global Environment of myList. Since myList is printing to address 50110, value 6 gets added to this (myFuned() | new 40116 0. Global Environment ‘container. Thus when you print iyList's value, it shows [3, 5. 6) Environment remains the same til lie 8 and then function returns ‘control to_main__at line 12. ‘Aner myFunc4(,) gets over, the local Snvronment is removed. The list, Chath i sil efering to address 40716 ‘and prnts whatever is contained af ane very adaress [6 (1, 4) Changes thst were made to aaaress S110 372 not refected. ¥ 2. Which of the following keywords marks 3. What is the area of memory called, (0) a heap —(b) storage area iP Progress In Python 3.4 (a stack (@ an anay 4. Find the errors in following function | ae ‘This ‘Progress in Python’ session is aimed at these concepts? (a) def main( ) 31 ‘That means, we can say that : ‘© Changes in immutable types are not reflected in the 1. If return statement is not used inside " tion at all. the function, the function will return: oo +. (@o (@) None object © Changes, if any, in mutable types (6) an arbitrary integer ™ are reflected in caller function if its name is nat (@ Enor! Functions in Python must assigned a different variable or datatype. () def func2() : COMPUTER SCIENCE WT Pie, pove code that the moment you make the pa, i the memory environs of a : am fate by asigninga different variable name, it oes the address of hen wero ano a io it So, whatever changes are made to it post this will not get ref , sriinel argument even though it was mutable because the addresses became differen, ow cin summarize the mutable behaviour as summarized below : Mutable Argument (say A) assigned to mutable parameter (say P) Soe ot 285 ny cl 100 ITP is assigned a new name or diferent IFP isnot assigned any new name or i in 7 diferent data ype vale then changes data type value (e.g., P = diferent_variabie in P are performed in place and GET then any changes in P are not reflected) | REFLECTED BACK to_main_ BACK to_main_ | (refer same codes 2.1 and 2.2) (refer sampie code 2.3), | That is, A will show the changed data That is, A will not show changed data Figure 3.5 Mutable types’ behaviour with functions. ‘have a return statement. ™ are not reflected in the caller function if it is assigned a different variable or datatype. the beginning of the function block? | (a) fane (&) define (c) def (2) function which stores the parameters and local MUTABILITY/IMMUTABILITY variables of a function call ? OF ARGUMENTS Mutability/lmmutability of the arguments, parameters m4 print ("hello") their behaviour in various situations, print (2 +3) pooihcce (©) def compute ) : print (x + x) (@) square (a) return asa hort? oe * see ee et US REVISE 135 A Function is @ subprogram that acts on data inctions make program handling easier a Only a small part of the program ‘eal with a atime, thereby avoiding ambiguity. ; a ith at ai : Ind often returns a value By default, Python names the segment with top-eve tatem Ir ve tents (main program) as | Aunction is executed in an execution frame ‘main | 7 4 The values being passed through a function, : tion-call state arguments). iment are called arguments (r actual, Parameters or actual ‘+ Python supports three types of formal arguments : parameters A parameter having default value in the function header is known as a default parameter. 4 A default argument can be skipped in the function call statement, # The default values for parameters are considered only if no value is provided for that parameter inthe function call statement. * Keyword arguments are the named arguments with assigned values being passed inthe function call statement. * A function may or may not return a value. A function may also return multiple values that can either be received in a tuple variable or equal number of individual variables. A function that returns w non-empty value is a non-void function. Functions returning value are also known as fruitful functions. * A function that does not return a value is known as void function or non-fruiful function. % A void function internally returns legal empty value None. * A function in a program can invoke any other function of that program. a particular piece of code or a data value (e.., variable) can be accessed is known © The program part(s) in whi ‘as Variable Scope. In Python, broadly scopes can either be global scop Python resolves the scope of a name using LEGB rule, i. ee ic al variable in its function. * A local variable having the same name as that of @ global variable, hides the i een ioned variable is to be used from glo! The global statement tells a function that the mention: er ape * e or local scope. t checks environments inthe order : Local, Enclosing, i. an identifier is The global statement cannot be undone in a code-block ie. once reverted to local namespace. : alues. A function can also return multiple ¥' errs Mutability of arguments/parameter affects the change of

You might also like