Python Modules

Modules in Python

Python Modules

      In the last article we had discuss about" Python Modules", like modules definition ,
what are the" STANDARD LIBRARY MODULES " then how to import a module in
Python, Now in this article we will discuss how to define a module and how to import
that in our program .In one module we can have functions ,variables, classes
and we can access all of this by just importing that Module .


    User can easily create as many modules as user want, You will be surprised  to know that we are already been doing that ,Every Python program is a module ,that is every file  that user saveas .py extension is a module .for example

def show():

     print("Hello")

     print("Module name " , __name__ )

show()

OUTPUT: 

Hello

Module name __main__



     So Python allow user to create a module separately or in a same program ,and use it anywhere in other programs as well 

We will take an example of calculator ,for that we have to define four  basic functions of math
in a separate module i.e. .py file  name that file as calculator .

def add(a, b):
   c=a + b
   print(c)

def sub(a,b):
   c=a-b
   print(c)

def multi(a,b):
   c=a*b
   print(c)

def div(a,b):
   c=a/b
   print(c)

Python Modules


Now to import calculator (Module) we have to use" import module name " syntax or simply
 use "from module name import *" then call any of the functions from it .

from calculator import *

a=10

b=5 

add(a,b)

sub(a,b)

multi(a,b)

div(a,b)

OUTPUT:
15
5
50
2.00

Python Modules

The dir() Function :

This is an inbuilt function of Python. dir() function lists the identifiers from module ,these
identifiers include functions, class and variables .
example :

Python Module:


We have discuss that module is a file that contains some definition and  statements .when a
 python file is executed directly ,it is considered the main modules of a program Main modules
 are given special name "__main__" .The main module may import many modules but other
modules can't import main modules.

Advantages of modules :

Python modules provide all the benefits of modular software design. These modules provides
 services and functionality that can be reused in other programs . The standard Library contains a 
set of modules .It allows you to logically organize the code so that it becomes easier to 
understand and use .


Key Points to remember :


1.A module can import other module
2.It is customary but not mandatory to place all import statements  at the beginning.
3.A module will load only once 



                                   Thank u 😊