Python Modules & Imports
PythonModules let you organize code into separate files and reuse code written by others.
Key Points
import module— import entire modulefrom module import func— import specific functionas— give an alias to a module- Python has 200+ built-in modules (math, random, datetime, os, json)
- Use
pip installto add external packages
Example — PYTHON
# Math module
import math
print(f"Pi: {math.pi}")
print(f"Square root of 144: {math.sqrt(144)}")
print(f"Power: {math.pow(2, 10)}")
# Random module
import random
dice = random.randint(1, 6)
print(f"Dice roll: {dice}")
fruits = ["Mango", "Apple", "Banana", "Grapes"]
print(f"Random fruit: {random.choice(fruits)}")
# Shuffle a list
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(f"Shuffled: {numbers}")
# Datetime module
from datetime import datetime, timedelta
now = datetime.now()
print(f"Now: {now.strftime(\"%d-%m-%Y %H:%M\")}")
birthday = datetime(2004, 5, 15)
age_days = (now - birthday).days
print(f"Days alive: {age_days}")
# Tomorrow
tomorrow = now + timedelta(days=1)
print(f"Tomorrow: {tomorrow.strftime(\"%d-%m-%Y\")}")
# JSON module
import json
student = {"name": "Rahul", "marks": 85, "city": "Pune"}
json_str = json.dumps(student, indent=2)
print(json_str)
# Parse JSON back
data = json.loads(json_str)
print(f"Name from JSON: {data['name']}") Result
Pi: 3.141592653589793
Square root of 144: 12.0
Power: 1024.0
Dice roll: 4
Random fruit: Mango
Shuffled: [3, 1, 5, 2, 4]
Now: 21-04-2026 10:30
Days alive: 8042
Tomorrow: 22-04-2026
{"name": "Rahul", "marks": 85, "city": "Pune"}
Name from JSON: Rahul
Square root of 144: 12.0
Power: 1024.0
Dice roll: 4
Random fruit: Mango
Shuffled: [3, 1, 5, 2, 4]
Now: 21-04-2026 10:30
Days alive: 8042
Tomorrow: 22-04-2026
{"name": "Rahul", "marks": 85, "city": "Pune"}
Name from JSON: Rahul