Explain the Python Modules with example.
217
07-Oct-2025
Updated on 07-Oct-2025
Gulab
07-Oct-20251. What is a Module in Python?
A module in Python is simply a file that contains Python code — it may include:
Modules help you organize your code logically and reuse it across different programs.
2. Why use Modules?
Using modules gives several benefits:
3. Creating a Module
A module is just a
.pyfile.Example:
my_module.py
4. Importing a Module
You can use the
importkeyword to include a module in another Python script.Example:
Output:
5. Importing Specific Items
You can also import specific functions or variables:
Or give an alias:
6. Built-in Modules in Python
Python includes many pre-installed modules.
Some common examples:
mathdatetimeossysrandomjsonreExample:
7. The
dir()FunctionYou can use
dir(module_name)to see what functions, classes, and variables are defined inside a module.Example:
8. Importing All (Not Recommended)
You can import everything from a module using
*:But this is not recommended, because it can cause naming conflicts.
9. The
__name__ == "__main__"ConceptWhen you run a Python file directly, Python sets the special variable
__name__to"__main__".You can use this to make code that runs only when the file is executed directly — not when imported.
Example:
10. Packages (Collection of Modules)
A package is a collection of modules stored in a directory with a special file
__init__.py.Example structure:
You can then import modules like:
In Summary
importmath,os, etc.)