Python Modules – Brief Introduction
Python Modules use to enhance the capabilities of Python Programming Language. Though Python functions are very much there to help us a lot. A lits of built-in Python functions are as follows
Python module contains the reusable functions for different needs. In order to use a function of a Python module, import that function
import <module_name>
Importing Whole Modules
import math
Import module and rename it
import math as m
import single function from a module
import math.factorial or from math import factorial
How to find out modules
Use help command like this at python prompt to display all the available modules in Python
>>>help('modules')
When the above code is executed, shows
if you want to know the functions available in any modules
>>>import math >>>dir(math)
Now this is a huge collection of functions. it is almost impossible for anyone to learn all this information by heart. so to know the functionality of any module function, use the help function again
import math >>>help(math.factorial)
The output of the above help function is
>>> help(math.factorial) Help on built-in function factorial in module math: factorial(x, /) Find x!. Raise a ValueError if x is negative or non-integral.
How to use the module function in Python Program
There are several methods to use module functions. Some of them are as follows
1st method: Import whole module, use the function with the module name.
import math n = int(input('Enter any number :')) result = math.factorial(n) print(' Result :',result)
2nd method:- Import module as a new name
import math as m n = int(input('Enter any number :')) result = m.factorial(n) print(' Result :',result)
3rd method: Import only a single function
from math import factorial n = int(input('Enter any number :')) result = factorial(n) print(' Result :',result)
4th Method: import single function
import math.factorial n = int(input('Enter any number :')) result = factorial(n) print(' Result :',result)
Note : In the above cases 3 and 4, there is no need to write module name before function.
Python modules not only contains Python functions but also have some constants like pi and e. They are used a similar way as a function but without brackets.