A function is a block of code that performs a specific action and returns a result.
How functions make your life easier?
- Functions let you write code only once.
- The decrease in the unnecessary complexity from the user. In my last blog I discussed about exponents as a function. i.e,
this can also be done by a function . How we do that is by first writing the function name followed by the parameters the function would need. A parameter is pretty much like what a function will need to do a task. So taking the above data only,we have
likewise, there are others like abs() for absolute and all.
Apart from functions, we have similar functionality called a Module. A Module is a text file which stores the python codes, in other words in makes the collection of similar type of tools in it and is organised in a particular manner. We can make a module available to another program by just importing it, please note here that import is a keyword.
Syntax: import module_name
Say for example we want to use a function floor() which rounds up the variable
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ‘root’ is not defined
we get an error message. Well this is because we didn’t import the function floor(), python will not understand this and will raise a question, which we call it as an error. So what we need to do is import the tools of math, please note here that math is a module . So, to access a function via module we have,
similarly, for using the value of pi
In short, import is actually expanding the content of a file which will result into more tools for a user.
Lets go the Lazy way, this is what I call for the shortcut. If we have long module name and function name it will be hectic to call them all the time so what we do is assign it to the variable. Consider the following example you will understand then,
That’s it about the functions and modules, in my next blog I’ll be discussing on how to save your program and strings