Python explanation - Python Functions | Functions in real world

Pybeginner
By -
0

Python Functions | Functions in real world

Let us explain it.

You can read or watch the explanation



So far You’ve come across the term function. But, we have rather been one sided. Means we just invoked them as tools to make tasks easier and even to simplify time consuming tedious tasks. As if we take the examples from our previous tutorials when we want some data to be printed in the console, we use print( ) method,


When we want to read the input from the variable we use input( ) method which is coupled with int( ) or float( ) methods which we have seen in our last tutorial. We’ve also made use of some methods which are also in fact functions but, these functions are declared in a specific way. They have some set of predefined code and you are just running that code by invoking these methods. 


How to create your functions in Python and use them ?

Here I need your little focus and attention, because we will write several functions from the level of simple to rather complex. But, before that let us understand why we need function. It often happens if a particular piece of code is repeated many times in your program. It’s repeated either literally or with some little modifications, consisting of the use of other variables in the same program. 


What will we do during that time? We just clone that piece of code using clipboard or copy-paste options. and will place the code as  we want, and then we will modify it according to our needs. 


How many times can we do that? Doing it all the time is not correct. We will finally end up as greatly frustrating when it suddenly turns out to be an error at the cloned code. We have to modify all the cloned ones which is a tedious task.


As a programmer, we do a lot of hard work to find all the places that need corrections. 


What would be the solution for this problem? 


It is very simple. We use functions. If there is more than one piece that’s appearing in your program then just isolate that piece of code and keep it under some function and use that function instead of cloning that whole code.


Sometimes, The algorithm that you are going to implement is so complex that your code begins to grow in an uncontrolled manner, and suddenly you notice that you’re not able to navigate through it so easily anymore. 


You can cope up with this issue by commenting on the code extensively, but this dramatically worsens the situation. Many comments make the code larger and harder to read. Some developers say that a well written function should be entirely viewed in one glance. 


A good attentive developer divides the code into well-isolated pieces, and encodes each of them in the form of a function. This simplifies the work in the program, because each piece of code is encoded separately, and tested separately. The process described here is often called decomposition.


So, we use functions if a piece of code becomes so large that reading and understanding may cause a problem, so we divide it into separate smaller problems and implement each of them in the form of a separate function. This decomposition continues until you get a set of short functions which are easy to understand and test. 


Sometimes, The problem is so large and complex that it cannot be assigned to a single developer, and a team of developers have to work on it. To solve that issue, the problem must be split between several developers in such a way that more than one programmer should write the same function at the same time. So, the job has dispersed among team members. Here, not only the work is shared among the team members but also a responsibility is shared among developers. Each of them writes a clearly defined and described set of functions, which then combined into a single module and this module will be a final product


So, we use functions when we’re going to divide the code among multiple programmers, you will decompose the problem into a set of  separately writtened functions and finally those functions are packed into a single module. So that is why we use functions. Now, Let us understand 

Where do these functions come from?

We already read about it in the first blog. Let us create our first function. As a beginner in programming it would be your first function. There are some set of rules that you need to follow. 


Rules to follow to create a function :


  1. The function always starts with a keyword “def” which means define. So, we use this keyword to define the function. 
  2. After defining a function, you have to name your function the same as naming a variable i.e., you have to follow the same set of rules that you have followed while naming a variable. 
  3. After naming a function, there’s a place for a pair of parentheses.
  4. After parenthesis the line must end with a colon( : )
  5. After this line, the actual function body begins which has a couple of nested instructions. Where nested instructions are nothing but the instructions which are inside the function. These instructions are necessarily nested which will be executed every time the function is invoked. 
  6. The function ends where the nesting ends. So, you have to be careful while ending the function. 

Now we’re ready to define our own function. Let us create an extremely simple function by following the rules



def begin( ):


Let us name our function as “begin” as we have started creating our own functions. You can name your function as you wish but, do follow the rules. If you don’t follow then you’ll have trouble facing those errors. 


So, you can label it according to you. It’s time to write the nested instructions, I don’t wanna make it more complicated. I will write only one instruction which has print( ) which displays the message “This is the beginning” . 



def begin( ):
    print("This is beginning")


We are done creating the function. Now let us invoke this newly created function. In order to invoke we have to come out of the nested instructions so come out of it.



print("Here we start")
print("Here we end")


Now save it and run it.


Here we start

Here we end


The interpreter just prints 2 messages. This means that python reads the function’s definitions and remembers them, but doesn't launch any of them without our permission. In order to give the permission to python you must invoke the function that you’ve defined. So, to invoke just use the name of the function and parentheses like I’m invoking here.



begin( )


Again save it and run it.


output :


Here we start

Here we end

This is beginning


The output looks different now. When you invoke a function. Python remembers the place of invocation and jumps to the function that you’ve invoked. Then it executes the body of the function, i.e., the nested instructions and return to the place directly after invocation.  


Always remember this key concept that you must define a function before invoking it. What happens if we invoke it before defining?. Let me show you.



begin( )

def begin( ):

    print("This is beginning")


I’m modifying the code where I’m trying to invoke the first line itself before defining. 


Traceback (most recent call last):

  File "C:/Users/Girl Coder/AppData/Local/Programs/Python/Python38/fundemo.py", line 1, in <module>

    begin( )

NameError: name 'begin' is not defined


We got a name error because the interpreter runs the program line by line and if you invoke the function before defining then it will not understand where to jump and finally it generates an error. So, Don’t try to force python to look for functions that you didn’t deliver at the right time. 


Note : don't give the same name to a function and a variable. 


Let us  give the same name to the function and variable and understand what happens at the side of execution. Everyone knows that the interpreter executes the code line by line. So, first it reads the begin function and understands that begin is a function… After reading it… It reads the begin variable and it changes the role of begin from function to variable. 


And now we are invoking the beginning function. But, the interpreter understood it as a variable. Logically, can we invoke a variable. It generates an error saying that 


TypeError: 'int' object is not callable


traceback (most recent call last):

  File "C:/Users/Singam raju/AppData/Local/Programs/Python/Python38/fundemo.py", line 5, in <module>

    begin( )

TypeError: 'int' object is not callable


You are free to mix your code with functions and you are not obliged to put all your functions at the top of your source file. But, remember that the function must be defined and then only it should get invoked. It may look strange, but it is completely correct and works as intended. You can invoke the function as many times as you want after defining the function. 


Even if you get any error. You can solve it by just modifying the definition of the function and this modification reflects in all invocations. 


So far we have learned:


  1. Why do we need functions in this real world of programming?
  2. How to define our own functions
  3. How to invoke those functions.

See you in the next blog.


Post a Comment

0Comments

Post a Comment (0)