In this section, i would like to describe how to create and import a module in python.
Defining module
A module is a file which consists of Python code. It organizes the python code logically. By grouping related code into a module makes the code to understand easily. A module can define functions, classes and variables including runnable code.
Creating module
To define a module, simply use your text editor to type some Python code into a text file, and save it with a “.py“ extension; any such file is automatically considered a Python module.
Importing module
We can import a module by using the following three statements.
import statement
The from…import statement
The from…import* statement
1.import statement
To import a python module we use import statement and we can access the definitions inside it using the dot operator. We can import a module as shown in below:
The dir() built-in function returns a sorted list of strings containing the names defined by a module.The list contains the names of all the modules, variables and functions that are defined in a module. Following is a simple example:
The following is an example that depicts how to import a module.
>>> import math
>>> import factorial
enter a number: 5
120
Another way to import a module is by using any one of “.py” extension file. For instance I am using “factorial.py” file while importing a module.
number=int(input("enter a number:"))
factorial=1
for i in range(1,number+1):
factorial=factorial*i
print(factorial)
When you execute the above code it produces the following output
enter a number: 5
120
Note: We can reload a module only once. If you try to re-import the same module it displays nothing.
>>> import factorial
enter a number: 5
120
>>> import factorial
>>>
2.The from…import statement
This statement allows you to import specific attributes from a module.
Syntax
from modname import name1[, name2[, … nameN]]
Ex
>>> num_items=int(input("enter the number of items purchased:"))
item_list=[ ]
for i in range(1,num_items+1):
item=int(input("enter the cost of item %d,"%i))
item_list.append(item)
print(item_list)
sum=0
for x in item_list:
sum=sum+x
print(sum)
>>> from purchase1 import item_list
enter the number of items purchased: 5
enter the cost of item 1, 10
enter the cost of item 2, 20
enter the cost of item 3, 30
enter the cost of item 4, 40
enter the cost of item 5, 50
[10, 20, 30, 40, 50]
150
If you observe the above example we are not importing an entire module but specific portion of that module is imported.
3. The from…import* statement:
If you want to import all the names from a module into the current namespace you use the following import statement.
from modname import *
This provides an easy way to import all the items from a module into the current namespace.