Function/Method & Scope of Variables

 

A function is a programming block of codes which is used to perform a single, related, specific task. It only works when it is called. We can pass data, known as parameters, into a function. A function can return data as a result. 

Python treats functions like a first-class member. It implies that in Python, functions and other objects are of same significance. Functions can be assigned to variables, stored in collections, or passed as arguments. This brings additional flexibility to the language. 

Advantages of Functions 

• Reducing duplication of code

• Decomposing complex problems into simpler pieces 

• Improving clarity of the code 

• Reuse of code 

• Information hiding Python function types 

There are three categories of functions:

 • Built-in functions 

• Function defined in modules 

• User defined functions. 

Built-in functions 

The functions whose functionality is predefined in Python are referred to as built-in functions. The python interpreter has several such functions that are always available for use. E.g. len(), type(), int(), input() Function defined in modules These functions are pre-defined in particular modules and can only be used after the specific module is imported.

 E.g.

All mathematical functions are defined in the module math. User-defined functions Python User Defined Functions allow users to write unique logic that the user defines. It is the most important feature in Python that consists of custom-defined logics with a set of rules and regulations that can be passed over the data frame and used for specific purposes. 

Structure of functions in Python Internally Python names the segment with top-level statements (no indentation) as _main_ Python begins execution of a program from top-level statements. 

Defining a Function A function in Python is defined as given below:

 def< function name >(parameters): 

        [“ ” ”” “ “]

        [

        …………………….. 

• Keyword def that marks the start of the function header. 

• A function name to uniquely identify the function. Function naming follows the same rules of writing identifiers in Python. 

• Parameters (arguments) through which we pass values to a function. They are optional. 

• A colon (:) to mark the end of the function header. 

• Optional documentation string (docstring) to describe what the function does. 

• One or more valid python statements that make up the function body. Statements must have the same indentation level (usually 4 spaces).

 • An optional return statement to return a value from the function. 

• Function header: 

The Header of a function specifies the name of the function and the name of each of its parameters. It begins with the keyword def. Parameters: Variables that are listed within the parenthesis of a function header. Function Body: The block of statements to be carried out, ie the action performed by the function. Indentation: The blank space needed for the python statements. (four spaces convention) Flow of execution in a function call The flow refers to the order in which statements are executed during a program run. The function body is a block of statements and python executes every block in an execution frame. 

An execution frame contains: 

• Some internal information (used for debugging)

• Name of the function 

• Values passed to the function 

• Variables created within the function 

• Information about the next instruction to be executed Whenever a function call statement is encountered, an execution frame for the function is created and the control is transferred to it. The statements are then executed and if there is return statement in the program, it will be executed and returnsto the function callstatement block. 

def message():

     print('Hello I am learning how to create function in python.') 

 def sum(a,b): 

     c=a+b 

    print('Sum of %d and %d is %d' %(a,b,c)) 

# main program

 # calling the function message

() message() 

# calling the function sum() 

sum(10,20) 

In the above program, two functions message() and sum() is declared. The message() function does not accept any argument but displays a text on the screen whenever we call it.

         On the other hand, the sum() function accept two arguments and display their sum on the screen. When the main program calls the function message(), the program flow goes to the body of the function message() and execute its codes. 

After that, it returns to the main program and then calls the second function sum() by sending it two arguments (10,20), the program flow goes to the body of the function sum(), and execute its code and again returns to the main program.

     At last, the main programs end. The function calling another function is called the caller and the functions being called is the called function or callee. Parameters and Arguments The parameters are the variables that we can define in the function declaration. 

In fact, we utilized these variables within the function. Also, the programming language in the function description determine the  type specification. The e v ri b e f ci it te the function’ entire execution. n addition, they are known as local variables because they are only available within the function. The arguments are the variables given to the function for execution. Besides, the local variables of the function take the values of the arguments and therefore can process these parameters for the final output. 

27 Passing parameters:- 

Python support three types of formal arguments/parameters: 

1. Positional argument (required arguments):- When the functions call statement must match the number and order of arguments as define in the functions definition this is called the positional arguments.

 Example:- 

def check(a,b,c): : 

Then possible functions call for this can be:- 

check(x,y,z) #3 values(all variables) passed 

check(2,x,y) #3values(literal+variables)passed 

check ( 2 , 3 , 4 ) # 3 values ( all literal ) passed. 

Thus through such function calls-

• The argument must be provided for all parameters (required) 

• The values of argument are matched with parameters, position(order)wise(positional) 

2. Default arguments:- 

A parameter having defined value in the function header is known as a default parameter. 

Example:- 

def interest(principal, time, rate=10): 

    si=interest(5400,2) #third argument missing 

So the parameter principal get value 5400, time get 2 and since the third argument rate is missing, so default value 0.10 is used for rate. 

    Default arguments are useful in situations where some parameters always have same value. Some advantages of the default parameters are listed below:-

• They can be used to add new parameters to the existing functions. 

• They can be used to combine similar function in to one.

3. Keyword(or named)arguments:-

Keyword arguments are the named arguments with assigned values being passed in the function call statement.

 Example:- 

def interest(prin, time, rate): 

     return prin * time * rate 

     print (interest ( prin = 2000 , time = 2 , rate 0.10 ))

    print (interest ( time = 4 , prin = 2600 , rate = 0.09 )) 

    print(interest(time=2,rate=0.12,prin=2000)) 

All the above functions call are valid now, even if the order of arguments does not match.

 4. Using multiple argument type together:- Python allows you to combine multiple argument types in a function call. Rulesfor combining all three types of arguments:- 

• And argument list must first contain positional(required) arguments followed by any keyword argument. 

• Keyword arguments should be taken from the required arguments preferably. 

• You cannot specify a value for an argument more than once. 

Example:- 

def interest(prin, cc, ime=2, rate=0.09): 

     return prin * time * rate 

Types of user defined function

1. No Argument No return                            2. With Argument No return 

3. No Argument with return                         4. With Argument with return 

1. No Argument No return 

def Add(): 

     a= int (input(“Enter First Number”)) 

     b= int (input(“Enter Second Number”)) 

     c=a+b print (“The Sum of inputted Numbers is:”, c) 

Add()

print(“ Executed”) 

2. With Argument No return 

def Add(a,b): 

     c=a+b

     print(“The Sum of inputted Numbers i ”, C) 

     num1= int (input(“Enter Fir t Number”)) 

     num = int (input(“Enter Second Number”)) 

 Add(num1,num2) 

Remember: The variable in main program is differ from the variable in function definition i.e. a and b should be x and y. 

In this scenario the variable passed (num1, num2) will be called argument, and when it replace with the variable defined in the function will be called as parameter. 

3. No Argument with return 

def Add(): 

    a=int (input(“Enter First Number”)) 

    b= int (input(“Enter Second Number”)) 

    c=a+b return c 

    x= add() 

    print (“The Sum of inputted Numbers is:”, x) 

Note: As return does not show the result we have to store the returned value on another variable x. 

4. With Argument with return 

def Add (a,b):

     c=a+b return c 

     a=int (input(“Enter First Number”)) 

     b= int (input(“Enter Second Number”)) 

     x= add(a,b) 

    print (“The Sum of inputted Numbers is:”, x) 

Calling function and Called function: 

• Function which is called by another Function is called Called Function. The called function contains the definition of the function and formal parameters are associated with them.

• The Function which calls another Function is called Calling Function and actual Parameters are associated with them. 

• In python, a function must be defined before the function call otherwise python interpreter gives an error. 

Difference between Arguments and parameters 

        These two terms are very interchangeable, so it is not so important to know the difference. The terms they refer to are almost identical. However, in order to sound more professional, correct terminology is important. 

Function Parameters:Variables that are in brackets when defining the function. When a method is called, the values are passed as parameters in the method.

Function arguments: Arguments are used to pass information from the rest of the program to the function. This information return a result. There is no limit to the number of arguments that can be written. Depending on the type of function you’re performing, there might even be no rgument. Use commas to separate the arguments in a function. 

Take into account the number of arguments you put in a function call. The number of arguments must be exactly the same as the number of parameters. 

In the example below, the variable name is the input parameter, whereas the value, “Arnav”, passed in the function call is the argument. 

def welcome(name): 

     print("Hello! " + name + " Good Morning!!") 

welcome("Arnav") 

Output: 

Hello! Arnav Good Morning!! 

Returning a Function If you wish to return some values from the function to the rest of the program, you can use the return statement. 

    As the name suggests, it returns a value without printing it. Executing this statement will cause the Python function to end immediately and store the value being returned into a variable. 

Scope of variables 

Scope means in which part(s) of the program, a particular piece of code or data is accessible or known. In python there are broadly 2 kinds of Scopes: 

• Global Scope                                                   • Local Scope Global Scope: 

• A name declared in top level segment (_main_) of a program is said to have global scope and can be used in entire program. 

• Variable defined outside of the all functions are global variables. 

Local Scope: 

• A name declared in a function body is said to have local scope i.e. it can be used only within this function and the other block inside the function. 

• The formal parameters are also having local scope. When dealing with Python functions, you should also consider the scope of the variables. The code in a function is in its own little world, separate from the rest of the program. Any variable declared in the function is ignored by the rest of the function. This means that two variables with the same name can exist, one inside the function and the other outside the function. However, this is not a good practice. All variable names must be unique regardless of their scope. 

Local variable: 

A variable that is defined within a function and can only be used within that particular function. 

Global variable: 

A variable that is defined in the main part of the programming and, unlike local variables, can be accessed via local and global areas. 

Lifetime of Variables: 

Lifetime is the time for which a variable lives in memory. 

For global variables the lifetime is entire program run i.e. as long as program is executing. For local variable, lifetime is their function’s run i.e. long as function is executing. 

Name Resolution (Scope Resolution) 

For every name used within program, python follows name resolution rules known as LEGB rule. 

• Local Environment : first check whether name is in local environment, if yes Python uses its value otherwise moves to 

• Enclosing Environment: if not in local, Python checks whether name is in Enclosing Environment, if yes Python uses its value otherwise moves to (iii) • Global Environment: if not in above scope Python checksit in Global environment, if yes Python usesit otherwise movesto (iv) • Built-In Environment: if not in above scope, Python checks it in built-in environment, if yes, Python uses its value otherwise Python would report the error: name notdefined. RANDOM MODULE randint() – function takes starting and ending values both randrange()-function takes only starting value and ending-1 value random()-generates decimal values between 0 and 1 but not include 1 

Comments

Popular Posts