In Python, a module is a file with Python code. This Python file may contain function definitions, variables, classes, and executable statements that can be included in the application.
A module is usually created to split a longer program into several files for easier maintenance.
To create a module, simply create and save a Python file with .py file extension.
def add(a, b): result = a + b return result def substract(a, b): result = a - b return result
To use any function from a module, you simply need to import the module in your code by using the import statement followed by the module name.
import my_module x = my_module.add(10, 40) y = my_module.substract(10, 5) print(x) print(y)
A module file name can be anything but must have .py file extension. A module file name must start with a small letter and if you want to use multiple words then each word should be separated by _ underscore.
You can call your module with a different name by using the as keyword while importing the module.
import my_module as md x = md.add(10, 40) y = md.substract(10, 5) print(x) print(y)
You can import only some functions, classes, or variables from a module instead of importing the entire module by using the from keyword.
import add from my_module x = add(10, 40) print(x)
You can also import multiple parts from a module separated by , comma.
import add, substract from my_module x = add(10, 40) y = substract(10, 5) print(x) print(y)
There are several built-in modules in Python that you can use anywhere in your code.
The dir() function is a built-in function in Python that returns a list of function names and attribute names of the object it is called upon.
import my_module x = dir(my_module) print(x)
The len() function is a built-in function in Python that returns the length of a string, array, tuple, list, dictionary, etc.
x = "Hello Buddy" y = [11,23,54,74,54] x_length = len(x) y_length = len(y) print(x) print(y)