Python Programming
About Lesson

Module in Python is simply a file contains definitions of functions and classes and saved with .py extension so that it can be reused in another python program. Hence there no separate process exists to create a module. We can split our code into number of modules so that it can be managed easily. Splitting code into modules is useful in big projects.

The import keyword
Once a module is created and saved the variables, functions, classes defined in that module can be reused in another module. In order to do that, the respective module must be imported to our current module using ‘import’ statement.

#Example program to be saved as two separate files
#save this module as mod1.py
def func():
print(“this is separate module”)

#save this module as mod2.py
import mod1

mod1.func() #since func() is defined in mod1

Alias for Module
When you feel the name of module is lengthier you can put an alternate name in the module into which it is importing using import…as… statement.

#Example code providing alias for mod1
import mod1 as m

m.func() #since func() is defined in mod1

from…import *
When you feel discomfort to use module name prefixed each time some member of it is called you can change the syntax of import statement as from…import *

#Example code showing how to import all members from a module
from mod1 import *

func()

importing specific functions only
When you really need a specific function only instead of all the members from a module you can specify names of those members only instead of ‘*’

#save this file mod3.py
def func1():
print(“func1 code”)

def func2():
print(“func2 code”)

x=10

#code showing how to import specific members from a module
from mod3 import x,func1

func1()
print(x)

Built-in Modules
Python provides several built-in modules which can be imported whenever you need. Built-in modules are written C and interpreted through python interpreter. You have to use import sys statement in your program to use built-in modules.

Type help(‘modules’) at python shell or prompt to view the list of all built-in modules of python. You can also use same help() function to show all the content of individual module.
For example: help(math)

#code showing how built-in module ‘math’ can be used
import math

x=int(input(“Enter your number:”))
print(math.factorial(x))
print(math.sqrt(x))

You cannot copy content of this page