Python Modules
Modules are Python files containing code that can be imported and reused. They help organize large projects and share code across files.
💻 Importing Modules
# Import entire module
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.14159...
# Import specific items
from math import sqrt, pi
print(sqrt(25)) # 5.0
print(pi)
# Import with alias
import numpy as np
import pandas as pd
# Import everything (not recommended)
from math import *📝 Creating Modules
# mymath.py
def add(a, b):
return a + b
def multiply(a, b):
return a * b
PI = 3.14159
# main.py
import mymath
result = mymath.add(5, 3)
print(result) # 8
print(mymath.PI) # 3.14159🎯 Key Takeaways
- import: Use external code
- from...import: Import specific items
- as: Create module aliases
- __name__: Check if module is main program
- pip: Package installer for Python
- Standard library: Built-in modules (os, sys, datetime)