DEV Community

varatharajan
varatharajan

Posted on

Modules

Modules :

Every python file is a module.
To create a module just save the code you want in a file with the file extension .py
Modules have special variables.
example:
file (file---->The file path of the module)
name (name---->Name of the module)
doc (documtation string of the module) ("""abcd""" or '''abcd''')

input

#current module name - vara.py

""" The nature is beautiful"""
print(__name__) 
print(__file__)
print(__doc__)
Enter fullscreen mode Exit fullscreen mode

output
__main__
C:\Users\Lakshmipriya\OneDrive\Desktop\VARATHARAJAN\vara.py
The nature is beautiful

The import statement
The import statement in Python is used to bring code from one module into another.
example :

#num.py

def add(no1,no2):
    print(no1+no2)


def subtract(no1,no2):
    print(no1-no2)


def multiply(no1,no2):
    print(no1*no2)


def divide(no1,no2):
    print(no1/no2)
Enter fullscreen mode Exit fullscreen mode

input

#vara.py

import num

num.add(10,20)
num.subtract(50,25)
Enter fullscreen mode Exit fullscreen mode

*output *


30
25

If we need specific functions alone from one module means then no need to import whole module,instead we can use "from" to take specific function

example
input

#vara.py

from num import add,subtract

add(10,20)
subtract(50,25)
multiply(10,20) #this function is not defind
Enter fullscreen mode Exit fullscreen mode

output


30
25
Traceback (most recent call last):
File "C:\Users\Lakshmipriya\OneDrive\Desktop\VARATHARAJAN\vara.py", line 7, in <module>
multiply(10,20)
NameError: name 'multiply' is not defined

help()
To see all details about the particular module like functions, file location, including documentation string.

num.py

''' This module contain some functions'''

def add(no1,no2):
print(no1+no2)

def subtract(no1,no2):
print(no1-no2)

input

import num
print(help(num))
Enter fullscreen mode Exit fullscreen mode

output

NAME
    num - This module contain some functions

FUNCTIONS
    add(no1, no2)

    divide(no1, no2)

    multiply(no1, no2)

    subtract(no1, no2)

FILE
    c:\users\lakshmipriya\onedrive\desktop\varatharajan\num.py


None
Enter fullscreen mode Exit fullscreen mode

Top comments (0)