0% found this document useful (0 votes)
308 views50 pages

Working With Functions (Sumita Arora)

This document provides an overview of functions in Python, explaining their importance in managing large programs by breaking them down into smaller, manageable units. It covers the definition, flow of execution, parameter passing, and return values of functions, along with examples of how to define and call them. Additionally, it discusses different types of functions, including built-in, module-specific, and user-defined functions.

Uploaded by

akulr25
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)
308 views50 pages

Working With Functions (Sumita Arora)

This document provides an overview of functions in Python, explaining their importance in managing large programs by breaking them down into smaller, manageable units. It covers the definition, flow of execution, parameter passing, and return values of functions, along with examples of how to define and call them. Additionally, it discusses different types of functions, including built-in, module-specific, and user-defined functions.

Uploaded by

akulr25
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/ 50
Working with Functions ns Chapter 3.1 Introduction 3.2. Understanding Functions 33. Defining Functions in Pytton 34 Flow of Execution in a Function Call 35. Passing Parameters 36 Returning Values From Functions 3.7 Composition 38 Scope of Variables INTRODUCTION Large programs are generally avoided because it is difficult to manage a single list of instructions, Thus, a large program is broken down into smaller units known as functions. A function is a named unit of a group of program statements. This unit can be invoked from other paris of the program. The most important reason to use functions is to make program handling easier as only a small part of the program is dealt with at a time, thereby avoiding ambiguity. Another reason to use functions is to reduce program size. Functions make a program more readable and under- standable to a programmer thercby making program management much easier, In this chapter, wwe shall talk about functions, especially, how a function works ; how you can create your own anion tastiest functions in Python ; and how you ean use the functions actson data and often returns a created by you. value Norighs Ee 86 a COMPUTER SCIENCE HTH Petey 3.2. UNDERSTANDING FUNCTIONS In order 10 understand what a function is, in terms of a programming language, read 1, following lines carefully. ; You have worked with polynomials in Mathematics. Say we have following, polynomial - ae For x «1, it will give result as 2417 2 For x =2 it will give result as 2+ For x= it will give result as 273 and soon. Now, if we represent above polynomial as somewhat like fo) <2 Then we can say (from above calculations) that s(y=2 a) f2-8 2) {G)=18 GB) The notation f(x) «21? can be termed as a function, where for function namely f, x is its is its functionality, f¢, the functioning it performs. For to equations (I) argument ie, value given toit, and 2 different values of argument x function f(x) will return different results (refer (2) and (3) given above) On the similar lines, programming languages also support functions. You can create functions ina program, that : © can have arguments (oulues gitrn fo it), if needed © can perform certain functionality (same set of statements) © can retum a result For instance, above mentioned mathematical function f(x) can be written in Python like this = def calcSomething (x) = rezexer2? return r where © def means a function definition is starting © identifier following ‘def’ is the name of the function, ie, here the function name is caleSomething . © the variables/identifiers inside the parentheses are the arguments or parameters (valves given to function), i, here xis the argument to function calcSomething. © there is a colon at the end of define, meaning it requires a block saee 3 WORKING WITH FUNCTIONS a © the statements indented below the function, (/¢. block below def line) define thy functionality (working) of the function, This block ts alsa called hody-af-the-furetion, Mere, there are tivo statements in the body of function cateSamething. © The return statement retums the compnted result, The non-indented statements that ate below the function definition a function calcSomething’s definition, For inst Fig. 41 below: not part of the function ylven In sider We example he furron def edlesonething (x): |< efit of fare reatxe? site Sumething | 2 vey return | Baty ef the Seen mart onysenl = “QE Coonpete programm a= int (input( “Enter a nunber :*)) LeSomething a This is ora pur of function 6 print (calcSorething(a)) (Whose satements are net a tp devel vf wedetation Famtan call ale priv | ye 3.1 Python Function Anatomy 3.2.1 Calling/Inworking/Using @ Function To use a function that has been detined earlier, ve vd to write a function call statement in Python. A function call statement takes the following form : () For example, if we want to call the function caleSomething() defined above, our function call statement will be like : calcSonething(5) ayalue 5 1s being sent as argunent Another function call for the same function, could be he : as? calcSomething(a) f this time vardable a 4s being sent as argument Carcfully notice that number of values being passed iy same as number of parameters, Also notice, in Fig, 34, the last line of the program uses a function call statement, (Pritt () is using the function call statement.) Consider one more function definition given belot def cube(x) : resexee3 ft cube of value in x return res return the computed value COMPUTER SCIENCE WITH PtH «yy As you can make out that the above function's name is cube() and it takes one argument. Now, its function call statement(s) would be similar to the ones shown below : ( Passing literal as argument in function call # St would pass value as 4 to argunent x cube(4) (i) Passing variable as argument in function call fun = 10 cube (nun) # it would pass value as variable num to argument x (ii) taking input and passing the input as argument in function call ynum = int (input (“Enter a nunber :* )) cube(rynun) # it would pass value as variable mynum to arguvent x (iv) using function call inside another statement print(cube(3)) # cube(3) will First get the corputed result mwhich will be then printed ‘The syntax of the function call is very similar tothat of the declaration, except that. the key word defand colon (2) are missing. (v) using function call inside expression double OfCube = 2% cube(6) # function call's result will be pultipliedwith 2 3.2.2 Python Function Types Python comes preloaded with many func can even create new functions. Broadly, Python functions can belong to one of the following, three categories : itions that you can use as per your needs. You fund 1. Buil jons. These are pre-defined functions and are always available for use, You have Tent), typet 3, intl J, input ) vt used some of them 2. Functions These functions are pre-defined in particular modules and can only be defined in used when the corresponding, module is fimported. For exanzple, if you want modules lo use pre-defined functions inside a module, say sin(), you need to first 3. User defined functions STRUCTURE OF FUNCTIONS ~eP This PriP session is aimed at making anatomy of 1 You'll be required to practice about structure af C Please check the proctical component-book — Science with Python and fill it there in PriP import the module math (that contains definition of sin()) in your program. you can create These are defined by the programmer. As programme: your own functions. In this chapter, you will learn to wrile your own Python functions and use them in your programs. Progress In Python 3.1 D thon functions clear to you, inctions. Progress in Computer 3.1 under Chapter 3 ofter practically doing it on the computer. eo trece a | |p WORKING WITH TUNCTIONS 89° 33 DEFINING FUNCTIONS IN PYTHON ¢ you now that we write programs to do certain things. Functions can be thought of as ey-doers within a program. A function once defined can be invoked as many times av needed ty wsing its name, without having to rewrite its code, An the following lines, we are about to give the general form /.¢., syntax of writing function code. In Python, Before we do that, just remember these things, In asyntay languia item(s) inside angle brackets <> has to be provided hy the programmer. fw item(s) inside square brackets | | is optional, Le.. can be omitted. # ltems/wordypunctuators outside <> and | | have to be written as specified. Afunction in Python is defined as per following, general format : def ( [parazeters] ) : [7 " “efunetion’s docsteings” ** [xstatenent>] For example, consider some functi n definitions given below: def sum(x,y) = sexey returns Or def greet(): print("Good Morning |") Though you know about various elements ina function-definition, still let us talk about itagain. Let us dissect these functions’ definitions to know about various components. ameter imate} imi Parameter inside); Keyword def mn namie 4 ore y Keyword Sif | no argument here eta eget greet( v —* — Huncnon Utes sexty end with a colon 2) i, Pema return s™ } SS Puswetion Hoole (indented) \ See all taterent in function bly \\ Meshell finda) Fett nyo yt hive ret en Let us define these terms formally : Function Header The first line of function definition that begins with keyword def and ends with a colon (2). specifies the mame of the function and its parameters COMPUTER SCIENCE WITH PYTHON y Variables that are listed within the parentheses of a funetion header ments / indented-statements beneath function header that detingy the any value. A function retums a value th PS foaming a wae stored in varsthec eh Parameters Function Body The Hock of state action performed by the function. The function body lay of may not rebar 2 return statement gave given sm? function greet() is not retuming a value, ‘A function nat retuming any value can still have a return statement without any Eapression or value. Examples below will make it clearer fa statement (convention is four spaces) within g k have same indentation, Indentation The Mank space in the beginning of Mock. All statements within same blo Let us now have a look at some more function definitions. # Sarple Code 1 def sunOf3sult iplesi(n) = suwntlene2snrs och thee rerio ae doing the sie thing BUT return s nner eriine tears a ng Moo satenon! at seared ft printing the compute wate Sanple Code 2 we sing pos def sus0f3Multiples2(n): sentient2ene3 print(s) Consider some more function definitions: # Sarple Code 4 #Sazple Code 3 def areadfsquare (3): def areaofRectangle ( a, b) : return ata return ab # Sazple Code § # Sarple Code 6 def perinetercircle( r) = def perinetorkectangle( 1, b) return (2* 3.1459 * r) return 2*(1+b) # Sazple Code 7 def quote( ) = print("\t Quote of the Day") Print("Act Without Expectation! |") print ("\t -Lao Tzu") For all these function definitions, try identifying thei ‘ sa lk it casually, whe eng ee try ‘fying their parts. (Not as an exercise, just do it A oe detaion defines a user-defined object function. The function definition does net fee body; this gets executed only when the function is called or invoked. [nthe nving lines, we are discussing how to invoke functions, but before that it would be useful ® know the basic structure of a Python program, & 3): WORKING WATH FUNCTIONS ructure of o Python Program gencrally all function definitions are given at the top followed by t part of any functions. These statements are not indented at all, These 1 statements (the ones with no indentation). The Python 3a Ss! Ina Python program, statements which are no! are often called from the top-level jnterproter starts the execution of a programiscript from the top-level statements. The lop level statements are part of the main program. Internally Python gives a special name to statements as _iain__. top-le The structure of a Python program is generally like the one shown below : def function1( ) : def function2( ) : def function3( ) if eran roe fe fen statement statement2 Python stores this name in a built-in variable called _name__(é-<., you need not declare this variable ; you can directly use il). You can sev 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, dot pest): Petre print (“Hi there!") ‘eras of ch program fom thc sepa. 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_ BW 92 eee COMPUTER SCIENCE Wat PInoy ~ta 3.4 FLOW OF EXECUTION IN A FUNCTION CALL Let us now talk about how the control flows (ie, the flow ny ‘ the flow of execution of statemer function call. You already know that a function is ealled (or invoked, or cmculedy ola the function name, followed by the values being sent enclosed in parentheses, For ine a invoke a function whose header looks like : anes, to ef sun (x, y) the function call statement may look like as shown below : sum (3, 6) where a, b are the values being passed to the function sum) Let us now sce what happens when Python interpreter encounters a function call statement. The Flow of Execution telers to the order in which statement The Flow of Execution refers to the order in which statements ie executed during s propen are executed during a program run. Recall that a block is a piece of Python program text that is executed as a unit (denoted by line indentation). A function body is also a block. In Python, a block is executed in an execution frame. The Flow of Execution refers ta An execution frame contains : the order in which statements are executed during # program © some internal information (used for debugging) ra pon © name of the function © values passed to function © variables created within function © information about the next instruction to be executed. Whenever a function call statement is encountered, an execution frante for the called function is created and the control (program control) is transferred to it, Within the function's execution frame, the statements in the function-body are executed, and with the return statement or the last statement of function body, the control returns to the statement wherefrom the function was called, fe, as: def fune( ) = return Forczon cal wil vend Pe convotfow tome [Laat etatomont of he function | functon definition. # rain efiniton will send the contro! : back fo whozelrom the fune( ) tuncson was called. print(—) Let us now sce how all this is done with the help of an example. Consider the following program 3.1 code. yr fer WORKING WITH FUNCTIONS gue! $.1 Program 10 add two numbers through a function progranadd.py to add two nunbers through a Function nen def caleSum (x,y): Saxty ® statement 1 return s Wstatenent 2 uml « float(input( "Enter First number :") ) #1 (staterent 1) nun2 = float(input( “Enter second nunber :*) ) #2 (statement 2) sum= calcSum(nunl, nun?) #3 (staterent 3) Print (“Sun of two given nubers is", sum) #4 (statement 4) Program execution begins with first statement of _inain_ segment. (def statements are also read but ignored until called. Tt will become clear to you ina fer ww moments, Just tead Program execution beeins with on) fist statement of _moin_ : 7 ent. {Please note that in the following lines, we have put upsome —*™ execution frames for understanding purposes only, these are not based on any’ standard diogram) Sante flcting ve _rain__ (add.py) | 2| | Python Console I nat « Float (input (“Enter First munber :*)) = = [>> pnd = float(input("Enter second nucber :*)) sum = caleSum (nun, nun2) fn Enter first number : 3 print ("Sus of two piven runbers 15", sun) Data: fun = 3,0 Nutement | euvwiod — —Pain__(add.py) 3 [Python console “)) Enter First nuzbe Pond = float (input( “Enter first nurber PAZ Float (input ( “Enter second runber :* ))—f Sum calesum (nus, nun?) |Print("sun of two given nunbers 4s", sun) Enter second number : 7 a et ae COMPUTER SCIENCE WITH PrTHon _nain__(add.py) sonerts ef ealeSiumt 6 tat, wall be exrcuta rund = float(Input ("Enter first number umd # float(input (“Enter second number # ‘calcsum (x, y) sun = calcSin (nut, nun?) — = = print ("Sun of tho given nusbers 157, 549) sexy return s Data: ful = 3.0 fund = 7.0 0. Function 6 [—jasalnomory] othe Internal Memory | fea aut) calesum (x, y) return s [> statement 1 of furction jn memory Data: x= 3.0 Nad Lens f fon escent as the pi wtf the = wy Gh cha taco of fonctuon felis return statement Lvs7e sees ieee fasion Aik ich nes 00 Naruane sons Th cenplcten the euvutao of statement Sof rain ealesum (x, ¥) rain (add. py) nun « Float (input “Enter first nucber rund = Floot (input ("Enter second nurber Sexey returns Dawa: sus = caleSun (nual, nur2, x= 3.0 | —_- print ("Sum of two given numbers 16° sum) Data: puml = 3.0 wey Sum = 10.0 Python Console unl = float(input ("Enter first nusber :*)) rund » float({nput( “Enter second nunbe sun = caleSum(numt, nun2) Print ("Sum of two given nusters 15°, sun) =~ === ST ) Sum of two given numbers is 100 Data: t | nual = 3.0 t nun? = 7.0 sun = 10.0 Statement 4 excel — on concte 43: WORKING WITH FUNCTIONS, er so we can say that for above program the statements were executed as : main > main2 > main.3 — calcSum.1 > calcSum2—» main3—+ maind (As you can see that we have shown a statement as Its (eg., relurn 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, if the retumed value is lo be assigned to variable or to be printed or to be compared of used in any type of expression etc. ; whole function call is replaced with the return value to complete the statement). © léthe called function does not return any value i¢, the return statement has no variable or value or expression, then the control jumps back to the line following the function call statement. / If we give line number to each line in the program then flow of execution can be represented just through the line numbers, ¢.s- 1. # program add. py to add two nunbers through 2 function 2. def caleSum (x, y) ? # statement 1 3. S=xty 4. returns # statement 2 . 5. #1 (statement 1) numi = float (input ("Enter first number :” )) 6. ")) #2 (statement 2) 7, num = float (input (enter second number £3 (statenent 3) 8. sum=calcSum (numi, nun2) #4 (statenent 4) 9. print ("sun of two given numbers 45°, Sum) fi 96 COMPUTER SCIENCE WIN ETH), With functore-eull 1, the variables @ and in function header will receive val With fu With func nm Determining, flow of execution on paper is also sometimes known as tracing the program, As, above discussion the flow of execution for above program can also be represented as follows: 2 ai 9 + 6+ 7+ B12» 3- dl BD Jaretin callsh ad erveuio$ Line 1 is ignored because itis a comment ; line 2 is executed and determined that itis a function header, so entire function-body (ée. lines 3 and 4) is ignored; lines 6, 7 and 8 executed; line 8 hay 2 function call, sa control jumps to the function header (lie 2) and then to first line of function-body, i, line 3, function returns after fie 410 line containing, function call statement i.e, Hines and then to fine 9 Please note that the function calling, anather function is called the caller and the function bei called is the ealled function (or callee). In above code, the _main__ is the caller of caleSum) function. 3.4.1 Arguments ond Parameters Anow that you can pass values to functions, For this, you define variables to receive As ye ues via a furction call statement. For exanipl, values in function definition and you send va consider the following program def eultiply (a,b): print (a*b) ys3 multiply (12, ¥) # function call -1- rultiply (y, ¥) # function cal] -2- xaS multiply (y, x) function call -3+ You can sce thal above program has a function namely multiply( ) that receives two values. This function is being called thrice by passing different values. The tree function calls for multiply) are eultiply (12, ¥) # function call -1- multiply (y,¥) # function call -2- sultiply (y, x) # function call -3- ‘5 12 and y respectively. 2, the vanables a and b in function header will reevive values y and y respectively’ call 3, the variables a and b in function heade will receive values y and x respectively: As you can sce that there are values being passed (through function call) and values being received (in function definition). Let us define these hv types of values more formally. © arguments : Python refers to the © parameter: alues being passed as arguments and alues being received as parameters, So you can say that arguments appear in function call statement and parameters appear in functiot header, rr 4) WORKING WITH FUNCTIONS ow arguments In ython ean be one of these value type © literals © variables © expressions | yt the purumneters in Python have to be some names ic, variables to hold incoming values. gro altemative names for argument are actual parameter and actual argument. Alternative panes for patameler are formal parameter and formal argument, So vither you use the word fombinalion of argument aid paraneler of you can use the combination actual parameter and ional oranicter oF the combination actual arguments and formal arguments, “Thus for a function as defined belo} dof multiply (a,b): ie print (9 *b) ‘The values being pasved through a: function-cat! statement are called ‘orguments (ot actual porameters nultiply(3, 4) both Literal argurents Ce re ee ped header are called porometers (or eultiply(p, 5) Rone literal and Jorma! parameters or forma! one variable argurent ‘orguments), multiply(p, p+1) fone variable and tone expression argurent The following are some valid function call statements : Buta function header like the one shown below is invalid : def rultiply (9+3,b): dUlifen w hold the ineming value Please remember one thing, if you are passing values of immutable types (e.g., numbers, strings lc) to the called function then the called function cannot alter the values of passed arguments but ifyou are passing the values of mutable types (¢,g., list or dictionaries) then called function would be able to make cha yyes in ther, FUNCTIONS’ BASICS “iP Progress In Python 3-2 This ‘Progress in Python’ session is aimed at strengthening the functions’ basics like : functions’ lerminology, function anatomy, argument vs parameter and flow of execution during function calls, Science with Python and fill it there in PriP 3.2 under Choster 3 ohter practically doing it on the computer. G Please check the practical component-book ~ Progress in Computer ) t 1. Thists somewhat sinilas to function call mechanisms, which are of two types : Coll by Value and Call by Reference. In Cll by Velue rechantsr, the called function makes a separate copy of passed values and then works with thera, s0 original values femain unchanged. But with Call by Reference mechanism, the called function works with original values passed to it. thas ‘sy changes made, take place in original values only. Python, immutable types implement Call By Value mechanism and mutable typesimplement Coll By Reference mechanism. a ¥ | 3.5. PASSING PARAMETERS Uptill now you leamt that a function call must provide all the values as re definition. For instance. if a function header has three parameters named in function call should also pass tree values. Other than this, Python also prov ways of sending and matching arguments and paramet thon supports three types of formal arguments/parameter tired by functi header then the Ss SOME Oth, 1. Positional arguments (Required argumcuts) 2. Default arguments 3. Keyword (or named) arguments Let us talk about these, one by one. 3.5.1 Positional/Required Arguments Till now you have seen that when you create a fi definition, you need to match the number of arguments wi For exemple, if a function definition header is like t ction call statement for a given function ith number of parameters required, def check (a, b, ¢) = then possible function calls for this can be #3 values (a1] variables) passed check (x,y, 2) check (2, x, ¥) #3 values (1iteral + variables) passed check (2, 5, 7) # 3 values (all literals) passed function calls, the number of passed valttes (anguments) has matched with ched) position: it, second See, in all the abov the number of received values (parameters). Also, the values are given (or m wise or order-wise, fe, the first parameter receives the valuy of first argum parameter, the value of second argument and soon eg. In function call 2 above : In function call 3 above + of2; © agets value 2; In function call I above : © awill get value of x © b will get value of y © ¢ will get value of = © a gets valu © b pets value of x; © Prgets value 5; © c gets value of y © c gets value 7 Thus, through such function calls © the arguments must be provided for all parameters (Required) © the values of arguments are matched with parameters, position (order) wise (Positional) This way of parameter and argument specification is called Positional arguments or Required arguments or Mandatory arguments as no value can be skipped from the function cal or you cannot change the order ¢g., you cannot assign value of first argument to third parameter. queen 3: WORKING WITH FUNCTIONS 35.2 Default Arguments What if we already know the value for a certain parameter, eg, in an interest calculati | fonction, we know that mostly the rate of interest is 10%, then there should bes provisiwe : define this value as the default valu. ‘ sprowsion to | Python allows us to assign defaull value(s) to a function's Parameter(s) which is useful in case a matching argument is not passed in the function call statement. The ‘ specified in the function header of function definition. Following header with default values : 9: Tihs b defuslt value for parameter rate. ut a function cull, the value for rate is not provided. Python will fil the méuing walue (far rate only) sith this value The default wale is specified in a manner syntactically similar [ann to a variable initialization, The above finetion declaration | provides a default value of 0.10 to the parameter rate, en aefarl eee anne follow default argument. default values are i$ an example of function def interest (principal, time, rate=0. Now, if any function call appears as follows : si_int = interest (saoe, 2) # third argunent 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 : si_int = interest (6100, 3, 0.25) # no argunent nissing, then the parameter principal gets value 6100, fime gets 3. and i 3 the parameter rate gets value 0.15. A parameter having default value in the function header 1s Known at a default parameter. That means the default values (values assigned in function 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 vatue unless all paramecers appearing on its right have their default vulues. For instance, in the above mentioned declaration of function interest( ), the parameter principal cannot have its a value unless the parameters on its right, time and rate also have their default values. Similarly, the parameter fine cannot have its default value unless the parameter on its Tight, ée., rate has ils default value. There is no such condition for rate as no parameter appears on its right. ers should be before default parameters. Thus, required paramet COMPUTER SCIENCE WATH FeTHON ~ 100 Following are examples of function headers with default values = def interest (prin, tire, rate = 0.10) = # legal def interest (prin, tire = 2, rate) : # illegal (default parameter # before required parcneter) def interest (prin = 2008, tine =2, rate) = # illegal 4 (sane reason as above) def interest (prin, tire « 2, rate = @-10) : # legal # legal def interest (prin = 200, tine = 2, rate [email protected]) = some Default arguments are useful in’ situations where Also they provide parameters always have the same val greater leaibilily to the programmers. sult parameters are listed below Some advantages of a © They can be used to add ne functions. © They can be used to combine similar functions into one. parameters to the existing 3.5.3 Keyword (Named) Arguments The default arguments gave you flexibility to specify the default value for a parameter so that it can be shipped in the function call, ifnevded. However, stil you cannot change the order of the arguments in the function call ; yout have to remember the correct ender of the arguments, To have complete control and flexibility over the corresponding parameters, Python offers another type of arguments "of writing function calls where you can write any argument in any order function, as shown below alues sent as arguments for the eywond arguments. Python offers a ws provided you name the arguments when calling the interest (prin = 2000, tine = 2, rate = 0.10) Anterest (time = 4, prin = 2600, rate = 8.09) interest (time =2, rate «0.12, prin» 20¢0) All the above function calls are valid now, even if the order of arguments does not match the order of parameters as defined in the function 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, fine gets value as 4 and rate as 0.09. In the 3rd. function call above, prin gets value 2000, time gets value as 2 and rate as 0.12. are te Keyword arguments sc heine passed. inthe tamed arguments with assie ralues being passed, inthe fojues being passed in Ie function call statement. This way of specifying names for the v function call is known as keyword arguments, gy WORKING WITH FUNCTIONS 4 Using Multiple Argument Types Together python allows you to combine multiple argument types in a functi “ ing 5 s ‘ion call. e following function call statement that is using both jwsitional (quired) and keyword tinea the | @ ie interest (5000, time = 5) The first argument value (5000) in above statement is rey will be assigned to first parameter on the basis of its position. The second argument (lime 5) is representing keyword argument or santed ar on sument, The above function call also skips an argument (rate) for which a default value is defined in the function header, , jules for combining all three types of arguments Python states that in a function call statement : ® anargument list must first contain posit presenting a positional argument as it onal (required) arguments followed by any keyword argument, ’ s y any Keywor © Keyword arguntents should be taken from the ee en 3 required aS arguntents preferably. Nore © You cannot specify a value for an argument more than Having. pestional arguments, once. after keyword arguments wall “result into error. For instance, consider the following function header : def interest( prin, cc, time = 2, rate = 0,09) : return prin * time * rate Itisclear from above function definition that values for parameters pri 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 illegal Reason interest(prin = 3000, cc = 5) Tegal | non-default values provided as named arguments Interest (rate = @.12, prin = 5082, cc = 4) | legal | Keyword arguments can be used in any order and for the argument shipped, there is a default value Interest(ce = 4, rate = 0.12, prin = 5202) | legal | with keyword arguments, we can give values in , any order interest (se0, 3, rate = 0.05) Jegel aigrescee net tt bee Pad Snterest(rate = 0.05, 5000, 3) iegal_| heywond argument before posional arguments ___[iReresesne, prin = 366, is 3 woskING WITH FUNCTIONS sre value Being retumed can be ane of the following ealiteral a variable > an expression for example, following, are some tegal return statements ¢ return S # Literal being returned return Ges expression involving literals being returned return a # variable being returned return at*3 express ton Involving a varLable and iteral, being returned retuen (268792) /b {expression Involving varlables and Literals, belng returned returna+ b/c # expression Involving variables being returned value, the returned value is made available to the ML, {when you call a function that is returning, aller functior/program by internally substituting the function call statement. Confused 2 We don’t be. Just read on, please © suppers if we have a function : def sum (x,y)? saxty return s And we are invoking this function as : pesult = sum(S, 3)¢——— Mir ritumid vain fron warn ill pave thin fantion al After the function call to sum() function is successfully completed, (ic, the return statement of function has given the computed sum of 5 and 3) the returned value (8 in our case) will ute the function call statement, That is, now the above statement will become “8 Thu the reamed vie ss 1 te mt + accesnfal ommpletin of aver vie inside an expression ar a statement ey, for the above mentioned sum() function, following statements are using the returned value in right manner : add_result = sum (a,b) <= Me retarnad vata being wed in wsipnment statement print (sum(3, 4)) <——— Me rtumad nalind beng wel in print statement sum (4, 5) > 6 << Trial vata Ing nai prlatnal exrenn Ifyou do not use their value in any of these ways and just give a stand-alone function call, Python will not report an error but their return value is completely wasted. 104 . COMPUTER SCIENCE NIH PrTHON, © The return statement ends 2 function execution even If Gauuen! if you 60 not ng is in the mlddle of the functian. A function ends the fynction call of a te : moment it reaches a reium statement of all statements in returning some value Insc i function-body: have been excculed, whichever Occurs other expression or sistemen’ carlier, eg following function will never eeach print( ) function willbe executed but, return vatue will be wasteg s statement as relum is reached before that, Python val not repert any ed ror def cheek (a) : Ag 5 a= math. fabs(a) t returna i ths semen unrated fant print(a) ri. anzand conmred wall never reach ais sae check(-25) sure 2. Functions not retuming any velue (Void functions) The functions that perform some action or do some work but do not return any computed value oF final value to the caller are called void functions. A void function may or may nol have a retum statement, Ifa vu function hay a return statement, then it takes the following form : Fora vd stn retrace down mot ae ne uM -. <—$—_—_ retur vue eseesiot fee thatiis, keyword return without any valuv or expression, Follawing are some examples of void function Arvchr voit futcefon ws mu ert state dof greet( ): deF greeti(nane) : «<——” SPS peta (nel 102") print(*hello*, raze) def quote( ) : def prinsus (a, by c) : TPS Print ooodness counts!) print ("Sum is", asbec) return return the caller ; their for the all four above The void functions are generally not used inside a statement or expressioi function call statement is standalone complete statement in itself, ¢ defined reid functions, the function-call statements can take the form greet( ) ) greetl( ) | ¢-—__——_ what all thee futon | qvotec ) res wre standalone, prinsun(4, 6) J } The void functions do not retum a value but they retum a legal emply value of Python # | None, Every void function returns value None to its caller. So if nevd! arises you can assign this return value somewhere as per your needs, ¢¢,, consider following, program code ! these are 34.1 Returning Multiple Values / WORKING WITH FUNCTIONS ose? def greet( ): print(“helloz") a-greet() print(a) The above program will give output as : helloz None Yes, you guessed il right - helloz is Printed because “ of greet J's execution and None is printed as value stored in a because greci( ) retumed value None, which is assigned to variable a. Consider the following example: # Coded #Code 2 def replicate() : def replicatei() : print("S$$sg") return "$$$ss" print(replicate()) print(replicatel()) Here the outputs produced by above tiwo codes will be: Oulputs: Code 1 Coe 2 S5585 $8555 Nione Tknow that you know the reason, why ? So, new you know that in Python you can have following four possible combinations of functions () non-void functions without any arguments, (i) non-void functions with some arguments (ii) void functions without any arguments (iv) void functions with some arguments Please note that a function in a program can call any other function in the same program. Unlike other programming languages, Python lets you return more than one value from a function. Isn't that useful ? You must be wondering, how ? Let's find out. To return multiple values from a function, you have to ensure following things = () The retum statement inside a function body should be of the form given below : return , , . (i) The function call statement should receive or use the retumed values in one of the following ways : COMPUTER SCIENCE WITH PY y, (2) Either receive the returned values in form a tuple variable, be, a8 shown below; : satererd Tourn | , def squared (xy yo 2) een ee modulo returnx*x,y"¥sE°2 (rest hat cma mpuruind a hee pie pate etalon a a ied t= squared(2,3,4) ee eee Ot print (t) Tonle wie pried oe ant wed values of tuple by specifying the same () Or you can directly unpack the ree ‘ ing the number of variables on the left-hand side of the assignment in function call, eg., def squared(x, y, 2): return x,y ty, 2" z foo of vie differ * sauared(a yay hat te V1, v2, v3 = squared(2, 3,4) print ("the returned values areas under:") print(vi, v2, v3) Out poaKed ar The retuned values are ae under: aoe 3.3 Program that receives tho numbers inva function and returns the results of all arithmetic operations (eT 49) on these numbers, def aralc(x, ¥) = return xey, fury are in the Now the mend arabs, nye ly ty main unl + int (input (“Enter number 1: *)) pum? = int (input ("Enter number 2; *)), 244, sub, mult, div, pod = arCale (numt, nun2) print ("Susof given nusbers 3", add) print ("Subtract ion of given nunbers print(“Product of given numbers : Print (“D1viston of given nueber: Print("Modulo of given nusbers : sub) mult) div) '» 80d) Sample run of above program is as shown below : Enter nusber 1: 13 Enter nunber 2: 7 Sus of given nurbers : 20 subtraction of given nunbers : 6 Product of given nusbers : 91 Division of given nunbers : 1.8571428571428572 modulo of given nunbers : 6 OMPOSITION ye |. Vlobal Scope Sa 4 WORKING WITH FUNCTIONS, Cempesition in general refers to using an expression as part ofa larger expression; ora statement asapartof larger slatement. In functions’ context, we ean understand composition as follows: ‘The arguments of a function call can be any kind of expression : an arithmetic expression eg., greater( (445), (344) ) @ a logical expression eg, test(aorb) @ a function call (function composition) ¢g Ant(ste(S2)) Futon cal a part lay int(float("52.5") +2) ke force cat 1c oe, int(str(52) + str(10)) La ae The above examples show you composition of function calls Composition in fener (ler 12 ion ©: att of large: ion Using an expression as part of a ~a function call as part of larger function call, larger expression, of a statement asa part of larger statement, | SCOPE OF VARIABLES The scope rules of a language are the rules that decide, in which patl(s) of the program, a particular piece of code or data item would be known and can be accessed therein, To understand Scope, let us consider a real-life situation, Suppose you are touring a historical place with many monuments, To visita monument, sou have tobuya ticket. Say, you buy a ticket (let us call a tick 1) 10 Bo see a monument As long, as, you ate inside RonumentA, your ticket} is vali. Hut the moment you come out of monument, the validly of ticketd is over. You cannot use tickei to visit any uther monument. To visit monument ticket, say ticket? So, wee can say that scope of fiche nt have to buy another is monument and scope of ticket? is monumentB. S2y, to promote tourisun, the government has also launches cty-tasedtichet (Say ticket), A person having ‘iy-based chet can visit all Une monuments in thot city, So we Can say hat the scope of tichet3 is the whote ity and all the monuments within city including monuments and monuamentts, Now let us understand scope in terms of Python, In [peppy ml Programming terms, we can say that, scope refers to part(s) Pants) of program within when of program within which a name is legal and accessible. Wit Seley tetany scteiie seems confusing, | suggest you read on the following lines called scope of the nene and examples and then re-read this section. There are broadly ftv kinds of scopes in Python, as being discussed below. Arame declared in top level segment (__main__) of a program is said to havea global scope and is usable inside the whole program and all blocks (functions, other blocks) contained within the program, (Compare with real-life example given above, we can say thal ticket3 has globel scope within a city as itis sale in all blocks within the city.) COMPUTER SCILNCE YATE Foti, 2. Local Scope A name declared in a funetion-body is said to have Bape verte ay scope ic, ibean be useitonlyeithin this function and the other ARTE Be it Mocks contained unuter it. The manies of forinal arguments 10 sre said 70 have globol scope, local have local scope. evi i “te shut within 3 function (Compare with real-life example given abo, we cat say | tale Rea vithin monument ant paid to have focal, ticket ard ticket? have local scopes te monumentD respectively.) ; A local scope can be multidevel: there cant be an enclosing local scope 7 a nested loca scope of an inside block. All this would become clear to you in coming lines. Scope Example | Consider the following Python program (program 3.1 of section 3.4) : A, def calcSum(x, y) + 2 rexty # statenent -. 3. return z # statenent -2- & statement -1+ # statenent -2- # statement -3- # statement -4- 4. muni = int( input ( “Enter first nunber :”) ) 5S. mus? = §at( input( “Enter second number :") ) 6. sum calcSun (nual, num? ) 7. print (Sum of given nusbers 4s", sum) A careful look on the program tells that there are three variables mon, num and stint defined in’ the main progrant and three variables x, y and = defined in the function caleSuantl ). So, as per definition given above, antl, num and suns are global variables here and 3, y and = are local variables (local to function caleSutn() ). Let us now see how there would be different scopes for variables in this program by checking the status after every statement eaccuted. We'll check the status as per the flow of execution of above program (refer to section 34) 1, Line! : def encountered and lines 2-3 are ignored. 2 Lined (Main.1) ; Execution begins and_ global Joba Envirenaent environment is created. num is added to this rust 3 environment, _ Global. Environsent runt G3 fun2 (7 3. LineS (Main.2) : num2 is also added to the global environment. a WORKING WITH FUNCTIONS ow 4. Line (Main.3) : caleSum( is invoked, so a local environment for caleSum() is created; ferobal (nvtronment runt 3 | we? \aead Envtroment formal arguments x and y are created in local wets ‘environment. yG-7 Global Environent runt Ee 3 Local Envirennent. nun? E}=2 for ealesua( ) xQ-3 5. Line2 (caleSum4) : variable = is created in the local environment. nat 2 3 6. Line3 (caleSum.2) : value of = is returned to caller (return ends the function, hence after sending value of s to caller variable sum (when control is back to Maint3), the local environment is removed and so are all its constituents). =—— = As you can see from above that scope of names mum, num2 and stun is global and scope of names x, y and = is local. Voriobles defined outside all functions ore global variables These variables can be defined even before all the function definitions, Consider the following example : 28 echt fiz abo al ft t abo def func(a) : iylobul variable wing why ands beasa return b y= input ( “Enter nunber” ) zey+func(x) print (z) —_— 110 Scope Exnmple 2 CMPIUD LINES IDS bet py Lat us tabe one rnunee exarnple, Consider the Selleralery, ane: 1, def calcsun(a,b, 6) + a peavber a. returns A, Gal aeerane (te 101) % be wmecaleon (4, 10) “a return eal 3 Te tame tnt GeyatCMrter 4d BR, rade Sot nga Mater 2) ) o, mmbeset Unga wrter ts) ) Te. print Chverage f these renters § a statecerit -I- watatenarit -F- etaterent <1 atesent De aterent 3 aanragel cd, ed, 2)) a ctaterent Internally the global and eval envivomntracnite wensld be createed as peer Brea of erections; Be Lined: def ervenedored 5 Mines 2,3 Syzented 2. Lines : def encemnter 3. Liew? (Main Ad): eeecution of rnain progeam begins : fj num) added to it pedal enveitontnent or Closed tmatriemant \ aide) en 7 ) valet 5, Vine10 (MainA): Function averayel) is Invoked, 9 a bead envitonsent for average Viv coated; formal aryurnenin x, y and £ are created in Jocal environinent, ines 5, biped Y . Sf Gerad trasremant Ae Lines 4,9 (Main ond Main3) : add num? and mum3 to iebal eraron Gluval tnetroement rai Bes rent he remit ‘Local Environment for averace( ) 1B-3 1G-7 1s =“ | sur 3 OBIE WD INETONS ni = Local Environsent “Global tnvironsent for average( ) Local tmtrenment for ais) \N 1B yva-7[, | YErE( 253 6. Line3 (average.t) : Function calcSumn( ) is invoked, so a Jocal environment for caleSumt ) is created, nested within local environment of | average’); its formal me | arguments (a, b,c) aw Raen> nun3 GS *O-3 7B-5 oud ES yGe? seQ-i5 1538-5.8 Line10 (Main.4) : The print statement receives computed value 5.0, prints it and program is over. (with this global environment of the program will also be removed) 10, 1 5 COMPUTER SCIENCE WITH PYTHON 5p 8 another term ~ lifetime of 3 forwhicha variable The yme forwhich avaratie g name temains in mem; called Lifetime of variable, we want fo introduce variable, The lifetime of variable is the time liece in memory. For global variables, lifetime is entire program nun (ie, they live in memory as long. as the Program Fanning) and for local variables, lifetime is their fanetion’s run (ic, as long as their function is being executed.) 3.8.1 Nome Resolution (Resolving Scope of o Name) For every name reference within a program, fit when program or function, Python follows name resolution ru for every name reference, Python does the following resolve i () I checks within its Local environment (LEG) (oF fecal amiesee) if it has a variable with the Same name ; if yes, Python uses its value, If not, then it moves to step (#). (i) Python now checks the Endlosing environment (LEGD) ( thon uses its value. variable with the same name) ; tf yes, Py If the variable is not found in the current environment, Python repeats this step to higher level enclosing environments, if any. Hi not, then it moves to step (1). (88) Python now checks the Global environment (LEGB) whether there the came name ; if yes, Python uses its value, If not, then it moves to step (4 you access a variable from within Jc, also known as LEGD rule, That is, whether there is a is a variable with intains all built-in variables and tython checks its Buill-in environment (LEGH) that ne name ; if ves, Python uses its functions of Python, if there iy a variable with the =) Otherwise Python would report the error: rane ¢ vardable > not defined As you can mabe out that LEGD rule meany checking in the order of Local, Enclosing, Global, reference, (Fig, 3.2) Built-in environments (namespaces) te resolve a na | Figure 3.2 LEGH rue for name resclution (scope) _— Jp WORKING WTH FUNCTIONS oo Let us consider some examples to understand this. coe Venable in global scope but not in local scope Let us understand this with the help of following aude : ef calesun ( toa phdst vw, sexey uriahle print (nut) # staterent -2- returns F staterent -3- | muml » int(input( “Enter first number ») rand + Ant (inout ( “Enter secon number :7) ) | print ("Sum is", callcSum (must, num2)) tement 2 of function cul | Consider 4m(). Carefully notice that mum hay not been ervated in elem) and snl statement? is trying to print its value. The intemal memory status at time of execution of statement 2 of aaleSum() would be somewhat like 1. Python will first check the Lixal exzxromment of ealeSum( ) ~ for mum]; Global Lnvironment rum] is not found there. Local tnvtronment or ealesum( ) 2 Python now checks for mum, Bo the parent environment of ‘a calSumt ) wluch ws Glos! emorronment (thete ts intermediate enchning, cretuonora fetonntn, environment) Python finds mami here : s0 it picks ity value and prints it Coe 2 Venable newher in tocal sec scope What if the function is using 4 Variable which is neither in its local envitonment nor in its parent environment ? Sumple! Python will 1 fame in the following code as at not Hn error, © Python will report error for variable defined anywhere > | [ etareet 35 ee os print (hello®, nase) breet() Ce23: Some vanable nome in local scope es well os in global scope ome fe Hinde a function, you assign a valuc to a name which is already there in a higher level scope, T\thon won't use the higher scope variable because itis an assignment statement and assignment statement creates a variable by default in current envi onment. > COMPUTED SCINCE WAIN PrIME, it 114 Tor instance, consider the following code ; read it carefully + def statel( ) = — ts a nae S Ths sare en cree @ print(tigers) teers 95 local tevtroment Anes eek mame f Yor staterc CO nies gers = 95 \ gers B15, aor of mai pens print tigers ‘ statel() - print(tigers) ——— The above program will give output as : ws eau of po statement aside nel 1 fat thar len of bet gers pred 5 95 sin progr thon he of pat tigers peed That means a 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 varicble inside local scope? If you want to use the value of already created global veriable inside a local function without # modifying it, then simply use it. Python will use LEGE rule and reach to this variable, But if you want to assign some value to the global variable a without creating any local variable, then what to do ? This is lecause, if you assign any value toa name, Python will create ie etal surement Ee 3 local variable by the same name. For this kind of problem, eclaration Which holds for the Python makes available global statement. entire curtent code block It ' d : , create means that the listed identifiers | Te te 4 function that for a particular name, do not create a Be eect pane local variable but use global variable instead, you need to te eres oer write: global «variable naze> For example, in above code, if you want function statel( ) to work with global variable tigers, you nced to add global statement for tigers variable to it as shown below : def stater( ) : _—— } Hob tigers — ] This ts 29 indiccticn met 69 tigers = 15 /@lebal Environment, / cere hcl rena with int (tiger fo veers \ the aame tigers. rather woe " (teers) f teers 55 Local Environment \ 1 shtel variate tigers tigers = 95 \ B-15 for statei( ) print (tigers) \ } statei() N print( tigers: = gers) _- 4 WORKING WITH FUNCTIONS oo re above program will give output a 5 Real of i sateen inde wate) frctin, ib ers of global tigers is printed (which was muxlified ve global staternent cannot be fe 1 15 in ovina le) je na progam fn Ore nr ne le of ob tigers whic is T3 nnn) printed _ statement In Python prograrn. Once a variable is declared global in a function, you cannot undo the statement. That is, after a global statement, the | __ function will always refer to the global variable and local Although global variables can be variable cannot be created of the same name, ‘accessed throuch local scope, but i it Is not a good programming \ But for good programming practice, the use of global Practice, So, keep global variables statement is always discouraged as with this programmers elobal, and local variables focal, | tend lo lose the control over variables and their scopes. CALLING FUNCTIONS, ARGUMENT TYPES, SCOPE OF VARIABLES ~ iP Progress In Python 43 This ‘Progress in Python’ session is aimed at these concepts + cell types of arguraents, scope of variables and Name resolution ty Python, Please check the practical component-book ~ Progress in Computer (Science with Python and {ill i! there in Pri 3.3 under Chapter 3 alter practically doing it on the computer. ng oT invwking funclions, different 39 MUTABLE/IMMUTABLE PROPERTIES OF PASSED DATA OBJECTS Sonow you know how you can pass values to a function and how a function returns value(s) to its caller. But here it is important to recall following things about variables : © Python's variables are not storage conteiners, rather Python variables are like memory references; they refer to the memary address where the value is stored. © Depending upon the mutabitity/immutability of its data type, a variable behaves differently. That is, ifa variable is referring to an immutable type then any change in its value will also change the memory address it is referring to, but if a variable is referring to mutable type then | any change in the value of mutable lype will not change the memory address of the variable | (recall section 1.7). Following figure also summarizes the same. Another important thing to know here is that the seupe rules apply to the idenlifiers or the name lafets and not on the values. For example, if you pass an argument a with value 5 toa function that receives it in parameter b, then both « and b will refer to same value (ie, 5) in data space (even different scopes, they may refer to same data in data space depending upon Mulability), but, you can use name b only inside the called function and not in the calling | function. This will become clearer to you when we discuss mutability with respect to arguments and parameters in the section 3.8. 4 COMPUTER SCIENCE WaTH PrTHioy, a (Integer literals ore stored a! some predefined locations) (Number of references — & wH 148200, 143216 148232, 140245) 148264 148296 Code tists mg 3] vari = var[d] tase 200109 ! 1 vart stores the memory Listt has been allocated address 200160 where it reference of integer value 1 ‘can store memory references of its individual (io., 148216) as itis tems og. List?[0) currently stores here the currently storing 1 memory reference of integer value (/.0., 148216) ‘and List{1] stares the memory reference of integer value 3 (ie, 148248) Now if you make following changes to List and Varl : vari «vari -1 (tiow var holds value 0) Listafe] #3 (tion first item of List1 1s also 3) o @) 148200 142216 148232 148248 15263 140280 146296 77 lists memory > holding address Lista 200160°\_)) remains the same ) STH ) individual tems f $11} addresses cnange varl now stores memory = Sted et aaa The momar allocated to List, where it can hold ts data itons* (ie., 148200) remory address remains the same ie,, it still is 200160, BUT 5 the individual tems of List have changed so individual kart memory addresses stored here have ta reflect this. Thus etal and List1[1] are currently storing memory address . tho memory address of integer 3 as both List1[0] and Usti{1} currently hotd integer vatue 3 Figure 3.¢ Impact of Mutability and Immutability 43 WORKING WT FUNCTIONS, | | ; 1 Mutobilty/immutability of Arguments/Parameters and Function Calls 9 | ! When you pass values through arguments and parameters to a function, mutability/ immutability plays an important role there, Letus understand this with the help of some sample codes. also sonple Code 1.1 oe Passing an Immutable Type Value to a function. «def myFunci(a): print (*\t Inside myFunel()") 1 2 3 print(“\t Value received in ‘a’ as", a) 4 azas2 s, 6 print(“\t Value of ‘a' now changes to”, a) print("\t returning fron myFunci()") 7. # main 8. num=3 9. print(*Call ing myFunea() by passing ‘nun’ with value", nun) 1. myFunct(num) 11. print ("Back from myFunc](). Value of “nun! is", nun) Now have a look at the output produced by above code as shown below : Calling myFuncl( ) by passing ‘nun’ with value 3 Inside myFuncl( ) value received in 'a' as 3 - “The value got changed Wom te made Runcion vi 18" to @) falue of 'a' now changes BUTNOT gated. men returning from myFuncl( ) ~ Back from myFunci( ). value of ‘rum’ is 3) <- | | AS you can see that the function myFune1() received the passed value in parameter a and then | changed the value of a by performing some operation on it. Inside myFunel(), the value (of a) \ Bot changed but after returning, from myFuncl( ), the originally passed variable mum remains | unchanged. Letus see how the memory environments are created for above code (ie, sample corel). — COMPUTER SCIENCE ATH PYTHON, mh 118 Memory Environment For Sampla Code 1.1 ivan integer, an immutable type) (N Passed value (0) + reference count reve mecnacy ehironnen wi yory 0a6h Ea seated by OF t00_n10_632 seine [..[a] [4] [8] [9] Till Lines 7-9 0f codo of ~main— (2) + refsence court ex2_ tt data space At inof0 (function is called) argument Letsl urn is received in parameter a and for lines 1, 2, 3, cnvironment remains the ) Environment (myFunet 0) sane ) o 900 816 832 48H Soo, tho glotial environments fur romans unottectod fram changos to variable a of myfunet ats spoce Alte & Global Environment Loca! menvory environment yemains the same tit ine and the myfunet() guts over and contro! retums to —main- part's finest ‘and tho local environment of imytunct() is removed Local Env (myFunet()) 4 | acy aeae2) o eo _815 832648 ooo EE l= At linet, when num's value IS eo a printod Python prinis 3 as tho aun Environment Rl remained unchanged ia its SCOPE and thus always remained 3 3 WORKING YOM FUNCTIONS ng ow Python procesed an immutable data type when itis passed as argument. inside memory If you pass a mutable type such as a fist. (Recall that a asa list internally is stored asa container that holds the references of gx you justane fens ce what hopper cefoullection sui iaividtal items) Code 2.1 =o Passing a Mutable Type Value to a function-Making changes in place) 1, def myFunc2(myList): 2. print("\n\t Inside CALLED Function now") 2. print(“\t List recetved:", mytist) 4, pylist(o) 42 5s. print(“\t List within called function, after changes:”, myList) 6. return 7. List2= (1) 8. print(“List before function call: ", List) 9. myFunc2(List1) 18. print(“\nList after function call : ~, List) Now have a look at the output produced by above code as shown below : List before function cal] : [1] Inside CALLED Function now List received: [1] ‘The value got changed from {1]10 3] oe ‘i anges 3 ‘aide uncton wt change GOT List within called function, after changes : ® heres] List after function call ®) noes 7 As you can see that the function myFunc2( ) receives a mutable type, a list, this time. The passed list (List1) contains value as [1] and is received by the function in parameter mylist. The changes made inside the funclion in the list mylist get reclected in the original list passed, ic, in list! of _main_. + Sowhen you print ils value after returning from function, i! shows the changed value. The reason is clear — list is a mutable type and thus changes made to it are refelected back in the caller function. code (i.c., sample code2.1), Let us see how the memory environments are created for above 120 COMPUTER SCILNCE ¥atH pyn 104 | n Memory Environment For Sample Code 2.1 (Note (1) 6 telerence count $40 S56 $72 5M COM reed value Is a fist, a mutable type) wi a i] eae = Local Environment (rnyFuncz(o)) Global Environment Local Environment (rmyFune2( )) tunfd, (Listt10} now holds memory adores of at a rring to odtess 25000 ta {(List[0] holds memory usdros of vale 1 (590) +~ Tit Lines 7-9 of cody of _main_ {Atte tancion mye ‘ated argument List scan promotor mpList Bath row port tntass 25000. Fortes 1.23 be riroement cama the seme 1) At tines, mytistfOfs vole ‘etinngos to 3 (riyListfOy += 2) und thus tho Oth tem of myList now holds reference of value 3. BUT tho momory location of kat mnybist remains the sarme (25000). Tho change of memory address trom valua 1 (0 Value 3 has been done in place 1. af samo locaton of myist (10., 25000). Te memory enviroraent remains the samme (O° Imes §, 6 of code and then tunction returns, control _main__‘s tne 10, remaining toca! Gnuronment of function myFunc2 } we 3 (SES) in0 10, whoa Listt Is printed. 6 eurrenly holas roforenco of valu = Honco changed tit is printod (28 4 ,

You might also like