Product SiteDocumentation Site

Chapter 12. Modules

12.1. Introduction
12.2. Importing modules
12.3. Default modules
12.4. Module os
In this chapter we are going to learn about Python modules.

12.1. Introduction

Still now when ever we wrote code in the python interpreter, after we came out of it, the code was lost. But in when one writes a larger program, people breaks their codes into different files and reuse then as required. In python we do this by modules. Modules are nothing files with Python definitions and statements. The module name is same as the file name without the .py extension.
You can find the name of the module by accessing the __name__ variable. It is a global variable.
Now we are going to see how modules work. Create a file called greetings.py. Content of the file is given bellow.

#Bars module

def starbar(num):
    print '*' * num

def hashbar(num):
    print '#' * num

def simplebar(num):
    print '-' * num


Now we are going to start the python interpreter and import our module.

>>> import bars
>>>

This will import the module bars. We have to use the module name to access functions inside the module.

>>> bars.hashbar(10)
##########
>>> bars.simplebar(10)
----------
>>> bars.starbar(10)
**********