Functions

Functions 

 

What is Function?

 

A Statement Block which is needed to be reused with different sets of Data at various times is defined as a Function.

 

These Functions can be called from any location within the program by passing the Data to the function and also return Data from the function. This reduces the program length thus reducing software cost and also makes it more readable.

 

The main difference between Loops and Functions is, while the Statement block in the loop is repeated continuously, the Function block is called at various parts of the program with different set of Data.

 

Generally , There are 2 types of Functions in any Programming Language

-Built in Function

-User Defined Function

 

Built in Function are those Functions which are system Defined, either we can refer them directly or include the Library File in which it is defined into our program and use them.

 

User Defined Function (UDF) are those which are Defined, Declared and Used whenever it is required by the User himself.

 

In Python, UDF consists of 2 Parts one is Definition Part and the other is Reference or Usage Part. Since in Python we do not require Declaration, this is omitted.


User Defined Function

 

Syntax

def <Function Name>(<list of parameters>):

     <body>

 

Here, def is the keyword used to represent it is Function Definition. It is followed by Function Name, which follows the rule for variable Names. Normally the function is given a name related to its task for which we are defining. The List of Parameters if any is to be enclosed within brackets. It is optional , there can be no parameter also, but brackets are must even if empty. Then comes the Body of the Function  which  contains the actual statement block. There can be up to 256 parameters that can be used in Function definition, if required.

 

A Return statement is included in the Body of the function, at which points the control returns to the called place. A function can return either one value or no value. If no value is returned then the return statement is not required. There can be multiple return statement in the Body of the function but only one will be executed.

 

Example

 

def sum(a,b):

#sum is the name of the function and a and b are parameter list (Formal Parameters)

#This is a sample Function body which defines it

     c=a+b

     return(c)

 

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

y=int(input(“Enter another Number”))

z=sum(x,y)      #function call

print(“The addition result is”,z)

 

Scope of the Variable

 

Variable’s Life Time depends on where it is defined. If it is defined inside a function then the life is limited to function only. We will discuss in detail .

 

Types of Parameters

 

There are multiple ways in which we can define the Parameters being used in Definition part. They are,

     -Positional Parameter

     -Default Parameter

     -Keyword Parameter

     -Arbitrary Parameter or *args

     -Keyword Arbitrary Parameter or **kwargs

 

Positional Parameter

 

As the Python doesn’t have declaration of Data type, the only condition for the Formal parameter and Actual parameter is the count should match. Also, the values from the Actual parameter list is copied on to the Formal parameter list in the same order given

 

Example

def sum(a,b):

   --

   --

c=sum(x,y)

d=sum(z)

 

While the first function call is accepted, the second call will generate an error as the parameter count doesn’t match in definition and reference point. In the first call, value of x is copied to a, and y to b.

 

Default Parameter

 

If at all we want to call the Function with variable list of parameters then the parameter which we are going to omit should have a Default value defined in the Function definition. When we omit a certain parameter then the Function will consider the Default value given to the Parameter during definition as the value for it.

 

Example 1

 

def sum(a,b=100):

-    #here a is positional parameter and b is default parameter

C=sum(x)

D=sum(x,y)

Both the statements are allowed for C -> b will be 100 and for D -> b = y.

 

Example 2

 

def sum(a=50,b):

The above kind of definition is not allowed because all the Positional parameters are to be defined first and then only the Default Parameter can occur.

 

Keyword Parameter

 

Here, the values are passed to the function from the calling point, using the Parameter name used in definition itself.

 

While maintaining the order for Positional parameter is compulsory, it is not so for Keyword parameters, i.e., the order can be changed.

 

Example

 

def my_function(course3,course2,course1):

print(“The Shortest course is”+course3)

my_function(course1=”HDCA”,course2=”DCA”,course3=”DMO”)

 

Again if we are mixing both Positional and Keyword then the Positional arguments should appear at the start only.

 

Arbitrary Parameters

 

If you do not know how many parameters or values will be passed into your function , add a * before the parameter name in the function definition.

 

Syntax

def <fn name>(*params):

 

In the Formal parameter use * symbol to denote the parameter . The number of values can vary for every call.

 

This way the function will receive a tuple of parameters, and it can access the items accordingly:

 

Example

 

def my_function(*courses):

    print("The Shortest course is"+courses[2])

my_function("HDCA","DCA","DMO")

 

Output

The Shortest course isDMO

 

Pass Statement

 

As already discussed in Control Statements, Pass is a dummy statement in Python. The function definitions cannot be empty, but if you need, for some reason to have a function definition with no content, then put in the pass statement to avoid getting an error.

 

Example

 

def my_function():

   pass

 

Recursive Function

 

This is Special Function type where the Body of the Function will have a Function call that refers to itself. But care should be taken to have a proper termination of the recursion, otherwise the recursive call may be indefinite.

 

Example

#Factorial program

def fact(x):

    if(x==1):

        return(1)

    else:

        return(x*fact(x-1))

 

n=int(input("Give a Number for which you want to find factorial"))

print("The Factorial value is ",fact(n))

 

Output

Give a Number for which you want to find factorial6

The Factorial value is  720


In the above example in the fac() function we have 2 return statements , but only one will get executed per call of the function based on the value being passed to the function. While the value of x is getting decremented in every recursion call, the if statement will get executed only when the value of x reaches 1, otherwise the else part only gets executed.

 

Solved solution to find Factorial of 5

 

fac(5)

 

1st call         return(5*fac(4))

2nd call        return(4*fac(3))

3rd call         return(3*fac(2))

4th call             return(2*fac(1))

5th call             return 1, therefore once the                       value is achieved it travels back                 in reverse order as shown                     below

 

     2 * 1

     3 * 2 * 1

     4 * 3 * 2 * 1

     5 * 4 * 3 * 2 * 1

 

Thus we get the answer as 120.

 

Lambda function

 

It is also called as Anonymous function. It is single line function where the statement is normally an expression. The Function will not have any specific Name too.

 

Syntax

 

lambda <arguments>:<expression>

 

There can be any number of Arguments passed , but the expression can be only one. It is evaluated and returned back to the called point.

 

Example

 

x=lambda a:a+10

print(x(5))

 

Output

15

 

here 5 is passed to the function and copied to a. Then it is added to the value 10 and returned back.

 

Another Example

 

#Python code to illustrate square of a number

#showing difference between def() and lambda().

 

def square(y):

                return y*y

lamb

da_sq=lambda y:y*y

#using the normal defined function

print(square(5))

#using the lambda function

print(lambda_sq(5))

               

Output

25

25

No comments:

Post a Comment