• A group of functions, variables and classes saved to a file, which is nothing but module. 
  • Every Python file (.py) acts as a module. 
  • A module is a Python object with arbitrarily named attributes that you can bind and reference.
  • a module is a file consisting of Python code. 
  • A module can define functions, classes and variables. 
  • A module can also include runnable code.
  • A module is saved file of python.
  • A module is a collection of variables, functions and classes. It allows you to logically organize your python code. Grouping related code into a module makes the code easier to understand and use


x = 999

def add(a,b):

    print("The Sum:",a+b)

def product(a,b):

    print("The Product:",a*b)
  • demo module contains one variable and 2 functions.

If we want to use members of module in our program then we should import that module.

  • import modulename

We can access members by using module name.  
  • modulename.variable  
  • modulename.function()

How to use modules?

  • With the keyword import you can import one or several modules.
  • You can use import anywhere in your code. But you should put your imports at the beginning.
import math, random
x = math.sin(math.pi/2)
y = random.random()


  • After importing a module, it's content is available in a namespaces.
  • You can access all its function, contants and classes using the fully qualified name.
  • Eg:  math.sin()
  • In this case "math" is the namespace.

The Keywod form

  • If you want to use functions or classes directly, import them with the from __import__ syntax.

from math import sin
x = sin(3.1415)
  • In this example, only the function sin was imported. All other function, constants or classes from math were not imported.

The Global Namespace

  • It's also possible to import everything from a module to the global namespace, that means you can access e.g. the function without using the fully qualified name.
from math import*
x = sin(pi/2)



Post a Comment

Post a Comment (0)