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,
[python]
>>>5**4
625
[/python]
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
[python]
>>>pow(5,4)
625
[/python]
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
[python]
>>>floor(18.34534)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name ‘root’ is not defined
[/python]
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,
Syntax: module_name.function_name
[python]
>>>import math
>>>math.floor(18.34534)
18.0
[/python]
similarly, for using the value of pi
[python]
>>>math.pi
3.1415926535897931
[/python]
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,
[python]
>>> variable=math.pi
>>> variable+7
10.141592653589793
>>> variable=math.sqrt
>>>variable(9)
3.0
[/python]
That’s it about the functions and modules, in my next blog I’ll be discussing on how to save your program and strings



