Function:
Why do you I need to care about function?
Large program usually have may functional units, for example whatsapp has many function such as chat, file sharing, video chat, audio recording and sharing, status etc. Its not a good idea to write every thing in one large file and execute everything from top to bottom(normally program are executed linearly from top to bottom). Now if we have a mechanism to split the large code into segments(pieces) and use the code segments on need basis, the application becomes more manageable and efficient. This is where function comes into existence
What is function in python programming language?
Def: A function is a named unit of a group of program statement. This named unit can be called/ invoked using is its name from other parts of the program. Function is also known as subprograms or subroutines
Advantages:
1. Modularity: function allows to divide the program to modules ans use them on need basis.
2. Complexity: large program written with function are less complex to handle
3. Code reuse: function can written once and imported into different program and used without rewriting them.
4. Debugging: A program divided into function is easier to remove errors(i.e. debugging)
5. Code maintenance and Implementing new features becomes easy
Disadvantages:
1. Adds complexity for small code(so they are not to be used on small program)
2. Makes the program slow as the called function will be loaded into the primary memory and only then its can be executed
How to use function in python.
The usage of function needs two steps:
1. Defining the function:
Syntax:
def function_name(parameter1, parameter2.....):
“““ doc_string “““
Statement1
Statement2
.
.
.
StatementN
return object
Note:
* def is keyword and must be included
* function_name follows the rules of identifier declaration
* parameters are optional and are used to supply object/values from outside into the function
* doc_string is optional and is used to create documentation for a function
Which can be accessed using help() function
* a function must have one or many statements with proper indents, for an empty function pass has to be written in the function
* return is optional and used to provide/ return object to the calling program
2. Calling a function:
A function can not execute on its own and it has to be called in order to run it
Note:
* the function must be called by exact name and its case sensitive
* if the function has parameters then its must be supplied
Example
|
def add(a,b): # function declaration
"""
-> this function can calculate the sum of two number
-> takes two argument, only in numeric format i.e. integer and float
-> return the value in float
"""
val=float(a)+float(b)
return float(val)
su=add(10,30) # function call with arguments
print(su)
|
More on function ->
Reference:
1. Core python programming - R. Nageswara rao
2. Computer science with python - Sumita Arora