Function is a set of instructions or block of code which is written to perform a task and given
a name to be identified as what it has been intended to do. Name of function is used to call it
when it is required. It could take input parameters to perform on and could return the output.
Say for example we want to write a perform a task of adding two numbers and get the result after
print ("Hello World")
If you remember our first example was to print "Hello World" on console and there we used print function as above.
To define a function we need three things. First thing is def keyword, second thing is
function name and third one is input parameters. For example we want to
define a function which will add two integers. Lets name this function as add and parameters
as a and b . Below is the add function defined which takes two
numbers and returns the sum of both the numbers.
def add( a, b) :
General function definition construct: -
def function_name(arg1, arg2, arg3, .... argN):
In python return type is not needed to mention as in above example. def keyword is prefixed with the name of the function which is add here, then in brackets the input parameters which are a and b here.
To call a function when we need, we simply need to call it using it's name and provide required
parameters. Also if function is returning some value then we need to hold that in suitable data
storage. Lets call our add function.
sum = add(10, 20)