What is a 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.
Generally, There are 2 types of Functions in any Programming Language
- User Defined Function
- Built in Function
User Defined Function(UDF)
These are the Functions which are Defined ,Declared and Used whenever it is required by the User himself.
In Python, UDF consists of 2 parts
- Definition Part
- Reference or Usage Part
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) #-> calling the function, x and y are Actual Parameters print ("The addition result is ", z)
Output:
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 in later chapter.
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 param- eter 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:
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 an to be defined first and then only the Default Parameter can occur.
Keyword parameters
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 parameters is compulsory, it is not so for Keyword parameters, ie., 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")
Output:
Again if we are mixing both Positional and Keyword then the Positional arguments should appear at the start only.
Arbitrary parameters
If 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 <Function 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:
Keyword Arbitrary parameters
If we use ** in the formal parameter name, it is taken as passing of Keyword Arbitrary parameter list, shortly called as **kwargs.
This way the function will receive a dictionary of parameters, and can access the items accordingly:
Example:
def my_function(**course): print("The Course Duration of ", course ["Name"], " is ", course["dur"]) my_function(Name = "DCA", dur = "6 Months")
Output:
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 myfunction(): pass
Recursive Function
This is a 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:
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 specífic 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:
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 lambda_sq = lambda y: y*y # using the normally defined function print(square(5)) # using the lambda function print(lambda_sq(5))
Output: