Name of Module
Every module has a name. We can find the name of a module by using the __name__attribute of the module.
Actually, for every standalone program written by the user, the name of the module is _main_.
print("Hello") print("Name of this module is:",__name__)
Hello Name of this module is: __main__
Making our own modules
We can easily create as many modules as we want. Actually, every Python program is a module; that is, every file that we save as .py extension is a module.
Actually, Modules are placed in the same directory as that of the program in which it is imported. It can also be stored in one of the directories listed in the sys.path.
We are writing some codes in a file and save the file as john.py:
def display(): # function definition print("Welcome") str="Welcome to the world of Python!!!" # variable definition
Now, we are opening another file (main.py) and write the lines of code given as follows:
import john print("str=",john.str); john.display()
After running the above code, we get the following output.
str= Welcome to the world of Python!!! Welcome
Standard Library Modules
Python supports the following types of modules:
- Those written by the programmer.
- Those that are installed from external sources.
- Those that are pre-installed with Python.
Modules that are pre-installed in Python are together known as the standard library. Some useful modules in the standard library are string, re, datetime, math, random, os, multiprocessing, email, JSON, PDB, argparse, and sys.
We can use these modules for performing tasks like string parsing, data serialization, testing, debugging and manipulating dates, emails, command-line arguments, etc.
import math a=4 b=3 c=math.pow(a,b) print("C=",c)
import string # string module constants print(string.ascii_letters) print(string.ascii_lowercase) print(string.ascii_uppercase) print(string.hexdigits)
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789abcdefABCDEF
import datetime x = datetime.datetime.now() print(x)