Introduction:
Module is a file that is contain Pyhton definitions and statements. It defines functions, classes and variables and includes runnable code also. Functions are group of code and Modules are group of functions.
Steps:
Module is a file that is contain Pyhton definitions and statements. It defines functions, classes and variables and includes runnable code also. Functions are group of code and Modules are group of functions.
Steps:
- Create a python file with one or more functions and save it with .py extension.
- Include the import statement.
- The import has the following syntax:
- import [module1,module2,........,module N]
- When the intrepeter comes across an import statement, it imports the module if the module is already present in the search path.
- A search path is a list of directories that the interpreter searches before importing a module.
- Module is loaded only once, even if multiple imports occur.
- Using the module name the function is accessed using dot(.) operation.
The from....import Statement:
- For a module involving hundreads of functions, from.....import Statement is recommended to save loading time
Syntax:
from python_file import function_name
- Multiple functions can be imported by separating them using the commas.
Syntax:
from python_file import function_name 1, function_name 2
- Use the astrisk (*) symbol to import eveything
Syntax:
from python_file import *
The Built-in Modules:
There are plenty of built in modules, just as built in functions. The most useful are:
- Random
- Math
- Calender and date-time
1. Random:
This module generates random numbers. If a random integer is needed, use the randint function. randint accepts two parameters: a lowest and a highest number. If a random floating point number is needed, use the random function. Choose a random element from a set such as list, called choices.
Try Yourself:
import random as rd
print rd.radint(0, 10)
print rd.random()
print rd.random()*10
data = [156, 89, "Vikram", 22.33, True]
print rd.choice(data)
2. Math:
The math module provides access to mathematical conatsnts and functions.
3. Calender & Date-time:
Python's time and calender modules help in tracking dates and times.
Try Yourself:
import calendar as cr
cal = cr.month(2017, 5)
print "May month calendar of the year 2017"
print cal
import time as tm
ticks = tm.time()
print "Number of ticks since 12:00am, January 1, 1970:", ticks
localtime = tm.localtime(tm.time())
print "Local current time:", localtime
#Formatted time
localtime = tm.asctime(tm.localtime(tm.time()))
print "Local current time: ", localtime
Comments
Post a Comment