Modules
Modules
Defining a module
• Modules refer to a file containing Python statements
and definitions.
• A file containing Python code, for e.g.: example.py, is
called a module and its module name would
be example.
• We use modules to break down large programs into
small manageable and organized files. Furthermore,
modules provide reusability of code.
• We can define our most used functions in a module
and import it, instead of copying their definitions into
different programs.
Let us create a module. Type the
following and save it as calc.py.
Importing Module
• We can use any Python source file as a
module by executing an import statement in
some other Python source file.
• When interpreter encounters an import
statement, it imports the module if the
module is present in the search path.
• For example, to import the module calc.py, we
need to put the following command at the top
of the script :
Import as renaming
from...import statement
# Sine of 2 radians
print(math.sin(2))
# 1 * 2 * 3 * 4 = 24
print(math.factorial(4))
# importing built in module random
import random