Python Function - In our recent articles, we have discussed on loop statements -
while-elseloop. In this article, we will be learning about what functions are, how we can create our own function and how we can use it.
Functions in any programming language is a group of statements, identified by a name, that perform a specific task. Whenever we want to re-use these statements in the code, instead of writing them all every time, we can invoke them using the name specified. This will not only save our copy-paste efforts but also reduce the code redundancy in the program. Also, for any correction to be made to any statement in the group, one need not correct every occurrence of it. Instead, it would be sufficient to make appropriate corrections in the defined function. Things will be clear when we go through some examples of functions. But to start with, lets learn how functions are created or defined.
To define a function, Python has a keyword
def, which gives us a
functiontype or an object of class
function. Please have a look at the basic syntax first, then we will try to unfold everything.
def function_name(): # Block of code starts ... ... ... ... # Block of code ends
In the syntax above, the line starting with
defis often called as function header and it consists of the keyword
def, the name of the function and a pair of parenthesis. In the parenthesis, we can mention zero or more parameters, which we will discuss about later. After that, we have an indented block of statements, which we can call as 'function body', that will be executed at every run of the function. So, if we were to define our own function
myFirstFunctionwhich does nothing, we can have a
passstatement in the function body as shown below:
>>> def myFirstFunction() : ... pass ...
Congrats, you've just created your first Python function. Had we replaced the
print 'Hello World', it would have printed
Hello Worldon the screen. Shall we check the what type object a Python function is? We require a Python built-in function for this, which is
>>> type(myFirstFunction) <type 'function'>
As I said earlier, the resultant object is of
functiontype. Now, we have created a function, but how to use it? Lets see this in following section.
A function call is nothing but making use of the function you have created. Well, to do this, you just need to mention the function name followed by a pair of parenthesis. Remember, with the
defkeyword, you just created a function. Unless you create a function, you cannot call it. So, the function definition must come before the function call or you will face an error message. Lets try defining a function
myFunction, that prints
Congrats! You have just executed a function, and calling it.
>>> def myFunction() : ... print "Congrats! You have just executed a function" ... >>> myFunction() Congrats You have just executed a function
As mentioned above, in order to call a function, we just mentioned it's name followed by the parenthesis and we have the function executed. Next, we need to know about two important terms related to Python functions, which I might have mentioned earlier, but have to be understood in detail - Function Argument and Function Parameter
Function Argument and Function Parameter
We have already used some functions like
len()in our previous articles, in which
lenare the function names. We have used them to get a list of attributes and methods associated with the object and to find length of the object respectively. So, in order to get the attribute list of a list
myList, we would use
dir(myList)or to find its length, we would use
len(myList), where we call
myListas an Argument to
dir()and len() functions. With an argument, we send some information, in the form of variable or a value, to a function. On the other hand, function receives these values using another variable, declared in the function header, which is called as a Parameter.
To understand this, lets take an example of any Python built-in function, say
dir()function. The built-in functions are defined somewhere in the Python library and they must be defined in somewhat similar syntax as seen earlier. So, the dir() function might look like :
def dir( param ) : .... .... .... ....
Thus, the variable
paramis the parameter of the function. When we actually use the function as
dir(myList), by providing an argument
myListto that function, the function reads the value stored in the variable
myListand assigns it to the variable
param. After some processing on it, we finally get appropriate output. Take a look at below examples.
Example 1 : Table of a number
>>> def table(myNum) : ... print '1 * ' + str(myNum) + ' = ' + str(1 * myNum) ... print '2 * ' + str(myNum) + ' = ' + str(2 * myNum) ... print '3 * ' + str(myNum) + ' = ' + str(3 * myNum) ... print '4 * ' + str(myNum) + ' = ' + str(4 * myNum) ... print '5 * ' + str(myNum) + ' = ' + str(5 * myNum) ... print '6 * ' + str(myNum) + ' = ' + str(6 * myNum) ... print '7 * ' + str(myNum) + ' = ' + str(7 * myNum) ... print '8 * ' + str(myNum) + ' = ' + str(8 * myNum) ... print '9 * ' + str(myNum) + ' = ' + str(9 * myNum) ... print '10 * ' + str(myNum) + ' = ' + str(10 * myNum) ... >>> table(5) 1 * 5 = 5 2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25 6 * 5 = 30 7 * 5 = 35 8 * 5 = 40 9 * 5 = 45 10 * 5 = 50
In above example, we have created a function with name
tablewhich prints the table of a number provided as an argument. It uses the parameter
myNumto store the number. After some operations on
myNum, we print the result. We also checked calling it with number
5as an argument and it prints the table of 5. Now, in order to print the table of 7, we need not write the statements again, just call the function as
table(7)and you are done. Conclusion - Functions improve the re-usability of the code and reduces redundancy.
Example 2 : Power of a number
>>> def power(base, exp) : ... print str(base) + ' to the power of ' + str(exp) + ' is ' + str(base ** exp) ... >>> power(2, 3) 2 to the power of 3 is 8 >>> power(3, 4) 3 to the power of 4 is 81 >>> power(6, 3) 6 to the power of 3 is 216
In this examples, we have created a function with name
powerthat has two parameters
baseto store the value of base and
expto store the value of exponent. This function will calculate the
expth power of
baseand print it on the screen. While calling the function, we have mentioned two arguments every time and got appropriate results in the output.
In this way, we have come to an end of this discussion of this article. This article was intended to provide you very basic knowledge about functions, in which we studies to define a function and call a function. Meanwhile, we also learned about arguments and parameters and used them in our function definition and function call. Although, we are not finished with functions, I recommend you to practice on whatever we have studied and start writing some functions of yours. Please write your reviews and feedback in the comment section below. In the next article, we will cover scope of the variables. Till then, stay tuned. Thank you.