math
, random
, datetime
, etc.from ... import
)A module is simply a Python file (.py) containing functions, variables, or classes that you can reuse in other files.
💡 Helps organize your code better and promotes reusability.
Example: Creating and using a Module
math_tools.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
main.py
import math_tools
print(math_tools.add(3, 4)) # 7
print(math_tools.multiply(2, 5)) # 10
Python provides hundreds of pre-built modules.
Module | Description |
---|---|
math | Mathematical Operations |
random | Generate random values |
datetime | Work with date and time |
os | Interact with operating system |
sys | System-Specific parameters |
json | Handle JSON data |
math
and random
import math
import random
print(math.sqrt(16)) # 4.0
print(random.randint(1, 10)) # Random number between 1-10
You can import specific function instead of the whole module:
from math import sqrt, pow
print(sqrt(49)) # 7.0
print(pow(2, 3)) # 8.0
import datetime as dt
print(dt.datetime.now())
A package is a directory that contains multiple related modules. It must have an __init__.py
file (can by empty) to be recognized as a package.
my_package/
├── __init__.py
├── math_tools.py
├── string_tools.py
Usage in another file:
from my_package import math_tools
print(math_tools.add(5, 6))
my_package/
__init__.py
math_ops.py
, file_ops.py
utilities
file_utils.py
with functions:read_file(filepath)
write_file(filepath, content)
__init__.py
to initialize packages or define what gets importedConcept | Description |
---|---|
Module | A .py file with functions/classes |
Package | A folder of releated modules with __init__.py |
Built-in | Modules like math , os , random , etc. |
Custom | Your own .py modules or package |
import | Brings in an entire module |
from | Imports specific items from a module |
Leave a Reply