Wednesday, 18 September 2013

Modules and Modular programming

If you want to develop programs which are easily readable, reliable and for which easy debugging is possible without too much effort, you have to use some kind of modular software design...
Especially if your application has a certain size. Modular programming is a  technique to split the code into separate parts. These parts are called modules.

But how do we create modules in Python?
A module in Python is just a file containing Python definitions and statements. The module name is the file name by removing the suffix ".py". For example, if the file name is fibb.py, the module name is fibb.
This is how we create modules.We save the following code in the file fibb.py:
def fib(n):
     if n == 0:
       return 0
     elif n == 1: 
       return 1 
     else:
       return fib(n-1) + fib(n-2) 
def fib1(n): 
     a, b = 0, 1 
     for i in range(n):
       a, b = b, a + b 
return a

Now save this file and open the interactive python promt. type in the following code
>>> import fibb
>>> fibb.fib(3)
2
>>> fibb.ifib(3)
2
in this way you can use modules instead of typing the code each time..

There are many inbuilt python modules also. One such example is "math"
>>> import math
>>>math.sin(0)
0.0
>>> dir(math)
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']


These are the other operations defined on the module math.
There are different kind of modules:
  • Those written in Python
    They have the suffix: .py
  • Dynamically linked C modules
    Suffixes are: .dll, .pyd, .so, .sl, ...
  • C-Modules linked with the Interpreter:
    It's possible to get a complete list of these modules:

 

0 comments:

Post a Comment