Modules and Packages

Modules and packages in Python are organizational units that help in structuring code, improving reusability, and managing namespaces.

Importing Modules

Modules are Python files containing Python code and definitions. You can use the import statement to bring functionality from a module into your code.

Here's an example of importing the math module and using the sqrt function:

Pythonimport math

result = math.sqrt(25)
print(result)  # Output: 5.0

This allows you to organize your code into separate files and reuse code by importing relevant modules.

Creating and Using Packages

Packages are a way of organizing related modules into a directory hierarchy. They help prevent naming conflicts and provide a modular structure for larger projects.

Here's an example of a simple package structure:

Pythonmypackage/
|-- __init__.py
|-- module1.py
|-- module2.py

You can import modules from a package using dot notation:

Pythonfrom mypackage import module1

module1.function()

Creating packages allows you to organize your code into logical units, making it more maintainable and scalable.