Modules
Modules
A group of functions, variables and classes saved to a file, which is nothing but
module.
Every Python file (.py) acts as a module Test.py
program1.py
x=888
import modulename
• Note: whenever we are using a module in our program, for that module
compiled file will be generated and stored in the hard disk permanently.
Renaming a module at the time of import
(module aliasing):
• Eg: import program1 as m
• here func is original module name and m is alias name. We can access
members by using alias name m
Test.py
import program1 as m
print(m.x)
m.add(10,20)
m.product(10,20)
from ... import:
• We can import particular members of module by using from ... import .
The main advantage of this is we can access members directly without
using module name.
• 1. sqrt(x)
• 2. ceil(x) from math import *
• 3. floor(x) print(sqrt(4))
• 4. fabs(x) print(ceil(10.1))
• 5.log(x) print(floor(10.1))
• 6. sin(x) print(fabs(-10.6))
• 7. tan(x) print(fabs(10.6))
import math
help(math)
Working with random module:
• This module defines several functions to generate random numbers.
We can use these functions while developing games,in cryptography
and to generate random numbers
random() function:
This function always generate some float value between 0 and 1 ( not
inclusive) 0<x<1
from random import *
for i in range(10):
print(random())
randint() function:
from random import *
for i in range(10):
print(randint(1,100)) # generate random int value between 1 and 100(inclusive)
Packages
• It is an encapsulation mechanism to group related modules into a
single unit.
• package is nothing but folder or directory which represents collection
of Python modules.
• Any folder or directory contains __init__.py file,is considered as a
Python package.
• This file can be empty.
• A package can contains sub packages also.