Tuesday, February 4, 2020

Functions in Python

Functions (Methods)
Arranging the code into groups is supposed to be best practice in programming. Statements intended to do the same job are often grouped together to form methods(also known as functions or sub-procedures). It reduces the effort and redundancy in code as we can refer to this code by its name whenever we require to use this code again in our project. We can input some data into the function and it will return some results as output generally. We can refer to the function by its name and invoke the function whenever it is required.

The functions are created using def keyword in Python. For example
def myfunction(): #name of function
      statement 1
      statement 2
      statement 3
      .
      .
      .
     statement n
# End of the function

To invoke the function, we can refer the function by its name. So, we just need to write 

myfunction()

to refer to this function.

We can also pass the parameters to the functions. Parameters are written within parenthesis in the declaration of a function The argument is the actual value provided to the function to execute.
Example
   


When the number of arguments is not known, then we can also provide an arbitrary number of arguments to a function. This can be done by writing *args within the parenthesis.
for example

def myfunction(*arguments): #variablenumber of arguments
      statement 1
      statement 2
#End of function


A function can also be provided with some default argument value. If the user invokes the function but does not provide the parameter, then the default value would be taken by the function itself.

def myfunction(arguments=vlaue): #default value to argument
      statement 1
      statement 2
#End of function

Example



We can also pass key-value pairs to a Python function, pass a list as an argument in a function, pass arbitrary number of key-value pairs in a function using **args. If we want to keep the body of a function empty, then we can use the 'pass' keyword. It means we can create an empty function(having no content in its body) with pass keyword.