Function is similar to a program that consists of a group of statements that are intended to perform a specific task. The main purpose of a function is to perform a specific task or work. Thus when there are several tasks to be performed, the programmer will write several functions. There are several 'built-in' functions in Python to perform various tasks. For example, to display output, Python has print() function. Similarly, to calculate square root value, there is sqrt() function. Similar to these functions, a programmer can also create his own functions which are called 'user-defined' functions.
We have discussed that a function contains a group of statements and performs a specific task. A function can be written individually in a Python program. A function is called using its name. When a function is written inside a class, it becomes a 'method'. A method is called using one of the following ways:
So, please remember that a function and a method are same except their placement and the way they are called.
We can define a function using the keyword def followed by function name. After the function name, we should write parentheses () which may contain parameters. Consider the syntax of function, as shown below
we can write a function to add two values as:
def sum(a, b):
Here, 'def' represents the starting of function definition. 'sum' is the name of the function. After this name, parentheses () are compulsory as they denote that it is a function and not a variable or something else. In the parentheses, we wrote two variables 'a' and 'b'. These variables are called 'parameters'. A parameter is a variable that receives data from outside into a function. So, this function can receive two values from outside and those values are stored in the variables 'a' and 'b'.
After parentheses, we put a colon (:) that represents the beginning of the function body. The function body contains a group of statements called 'suite'.
A function cannot run on its own. It runs only when we call it. So, the next step is to call the function using its name. While calling the function, we should pass the necessary values to the function in the parentheses as:
Here, we are calling the 'sum' function and passing two values 10 and 15 to that function. When this statement is executed, the Python interpreter jumps to the function definition and copies the values 10 and 15 into the parameters 'a' and 'b' respectively.