Modules in Python:
- Python application is a collection of modules.
- Module is a python source file(.py)
- Application a collection of program files(called modules)
- Python library providing number of pre-defined modules
- Some of the modules contain only functions.
- time
- date
- calendar
- re-regular expressions
- Some of the modules contains classes
- threading
- tkinter
- ….
- We must write modules in lower case only – naming rule to identity modules easily.
import:
- It is a keyword.
- It is used to connect the modules to access their members.
Working with pre-defined modules:
calendar:
- month() is belongs to calendar module.
- It is used to display the specified month in the year with pre-formatted layout
Code:
import calendar
print(calendar.month(2017,5))
Output:
May 2017
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
math:
- Ceil(x) : returns the smallest integer >= x
- Factorial(x) : return the factorial value of x
- Floor(x) : Returns the largest integer <= x
- Pow(x,y): returns x raised to power y
- Sqrt(x): return square root of x value
import math
print("sqrt(16) :", math.sqrt(16))
print("pow(2,3) :", math.pow(2,3))
print("ceil(2.3) :", math.ceil(2.3))
print("floor(2.7) :", math.floor(2.7))
Output:
sqrt(16) : 4.0
pow(2,3) : 8.0
ceil(2.3) : 3
floor(2.7) : 2
A list of re-defined modules:
- threading : To implement Parallel processing
- gc : For Garbage collection
- tkinter : To implement GUI programming
- time : To find system time and data and to display in different formats
- numpy : One, two and Multi dimensional
- re : Regular expressions
- mysql : Python – MySQL database connectivity
Custom modules:
- A programmer can also define custom modules.
- We can connect modules(python source files) using import statement.
- Module contains only functions – no object oriented programming
- For example, in following source code(module), we define only functions
- Module contains classes – in object oriented programming.