Introduction to Python Modules
In Python, modules enhance modularity, allowing you to define related functions, classes, variables, and more in one file. A module is simply a file containing Python code that you can reuse across various programs by importing it using the import keyword.
Example of a Python Module
import math
print("Square root of 100:", math.sqrt(100))
Output:
Square root of 100: 10.0
Built-in Python Modules
Python comes with a vast standard library of built-in modules that provide useful functionality, such as system management, string processing, and more.
| Sr. No. | Name & Description |
|---|---|
| 1 | os – This module provides functions to interact with the operating system. |
| 2 | math – This module includes various mathematical operations. |
| 3 | random – This module generates pseudo-random numbers. |
User-defined Modules
You can also create your own modules by saving Python code in files with the .py extension. These modules can be imported and used just like built-in modules.
# mymodule.py
def SayHello(name):
print(f"Hi {name}! How are you?")
return
# In another script
import mymodule
mymodule.SayHello("John")
Output:
Hi John! How are you?
Importing Modules in Python
There are different ways to import modules and their functions in Python. You can import an entire module, specific functions, or even assign aliases to modules for easier usage.
Importing the Entire Module
import mymodule
print(mymodule.sum(10, 20))
Importing Specific Functions
from mymodule import sum
print(sum(10, 20))
Understanding Python Namespaces and Scoping
Namespaces in Python refer to the mapping between variable names and their corresponding objects. A variable can be local or global, and you can control this using the global statement.
Money = 2000
def AddMoney():
global Money
Money += 1
AddMoney()
print(Money)
Output:
2001
Exploring the __name__ Attribute
The __name__ attribute helps determine if a Python script is being run directly or imported as a module.
if __name__ == "__main__":
print("This script is being run directly")
Python Packages
A package is a collection of Python modules. It allows you to organize your code in a hierarchical manner, grouping related modules together in directories. Here’s an example of creating and using a Python package:
# In Phone/__init__.py
from Pots import Pots
from Isdn import Isdn
from G3 import G3
# In main script
import Phone
Phone.Pots()
Phone.Isdn()
Phone.G3()
Output:
I'm Pots Phone
I'm ISDN Phone
I'm 3G Phone
Conclusion
Understanding Python modules and packages is crucial for organizing and reusing your code effectively. Whether you’re using built-in modules or creating your own, Python’s modularity makes programming more manageable and efficient.
