Python tutorial-Module


Module


What does module mean in Python? A module is a package or extension that you can import by using from and import keyword in to your programs. Programmers actually have a lot of programs that are developing. Some programs might have the same piece of code. For a good practice, the same piece of code needs to be put in a module in order to import it in to different programs without writing the same piece of code again and again. Python (and perhaps all other programming languages) has implemented module concept.
To create your own module, let try to create a folder in your current working directory(e.g. C:\Python25\Python_source)  and put your .py files in it. For example, we have multTable.py file that will generate a table of number multiplication. The multTable.py file contains the following code:
def genMtable():
        lst1=range(1,10)
        lst2=range(1,10)
        for i in lst1:
                for j in lst2:
                        print '%d*%d=%2d' %(j,i,j*i),
                print '\n'
        return
 
Now, let try to import it
>>> from Python_source import multTable
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    from Python_source import multTable
ImportError: No module named Python_source
>>> 
The error is raised because Python doesn’t treat you package as a module. To solve this problem, you need to add a special file:__init__.py to the package. The content of this file can be what to want to describe your module. If don’t want to write, just leave it blank. Then, try to import it again.
 
>>> from Python_source import multTable
>>> MultiplicationTable.genMtable() 1*1= 1 2*1= 2 3*1= 3 4*1= 4 5*1= 5 6*1= 6 7*1= 7 8*1= 8 9*1= 9   1*2= 2 2*2= 4 3*2= 6 4*2= 8 5*2=10 6*2=12 7*2=14 8*2=16 9*2=18   1*3= 3 2*3= 6 3*3= 9 4*3=12 5*3=15 6*3=18 7*3=21 8*3=24 9*3=27   1*4= 4 2*4= 8 3*4=12 4*4=16 5*4=20 6*4=24 7*4=28 8*4=32 9*4=36   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   1*6= 6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36 7*6=42 8*6=48 9*6=54   1*7= 7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49 8*7=56 9*7=63   1*8= 8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64 9*8=72   1*9= 9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81 >>>


Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.