- What are inbuilt modules — Python's ready-to-use tools
- math module — mathematical functions and constants
- datetime module — working with dates and times
- os module — interacting with the operating system
- sys module — system-specific parameters
- json module — handling JSON data
- random module — generating random numbers
- collections module — specialized data structures
What are Inbuilt Modules?
Python comes with a rich collection of inbuilt modules that provide ready-to-use functionality for common programming tasks. These modules are part of Python's standard library and are available without any additional installation.
Think of inbuilt modules like a well-stocked toolbox. Instead of building your own tools from scratch, you can reach into the toolbox and grab exactly what you need. From mathematical calculations to file handling, from working with dates to generating random numbers — these modules have you covered.
💡 Key concept: Inbuilt modules are Python's standard library — a collection of modules that come with Python. They provide essential functionality for everyday programming tasks, saving you time and effort.
math — Mathematical Functions
Mathematics Made Easy
# The math module provides mathematical functions and constants
import math
# 1. Basic mathematical functions
print(f"Square root of 25: {math.sqrt(25)}") # 5.0
print(f"Factorial of 5: {math.factorial(5)}") # 120
print(f"Power 2^10: {math.pow(2, 10)}") # 1024.0
print(f"Absolute of -10: {math.fabs(-10)}") # 10.0
# 2. Trigonometric functions
print(f"sin(π/2): {math.sin(math.pi/2)}") # 1.0
print(f"cos(0): {math.cos(0)}") # 1.0
print(f"tan(π/4): {math.tan(math.pi/4)}") # 1.0
# 3. Logarithmic functions
print(f"log(100): {math.log(100)}") # 4.605...
print(f"log10(100): {math.log10(100)}") # 2.0
print(f"log2(8): {math.log2(8)}") # 3.0
# 4. Rounding functions
print(f"ceil(4.3): {math.ceil(4.3)}") # 5 (round up)
print(f"floor(4.7): {math.floor(4.7)}") # 4 (round down)
print(f"trunc(4.7): {math.trunc(4.7)}") # 4 (truncate)
# 5. Constants
print(f"π: {math.pi}") # 3.14159...
print(f"e: {math.e}") # 2.71828...
print(f"τ: {math.tau}") # 6.28318... (2π)
print(f"∞: {math.inf}") # infinity
print(f"NaN: {math.nan}") # Not a Number
# 6. Practical example: Calculating circle area
def circle_area(radius):
return math.pi * radius ** 2
print(f"Area of circle with radius 5: {circle_area(5):.2f}") # 78.54
# 7. Practical example: Distance between two points
def distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
print(f"Distance between (0,0) and (3,4): {distance(0, 0, 3, 4)}") # 5.0
math module key features:
- Basic functions — sqrt(), pow(), factorial()
- Trigonometry — sin(), cos(), tan(), asin(), acos()
- Logarithms — log(), log10(), log2()
- Rounding — ceil(), floor(), trunc()
- Constants — pi, e, tau, inf, nan
Quick Check: Which math module function would you use to find the square root? (Answer: sqrt())
datetime — Date and Time
Working with Dates and Times
# The datetime module helps you work with dates and times
import datetime
# 1. Getting current date and time
now = datetime.datetime.now()
print(f"Current date and time: {now}")
print(f"Current date: {now.date()}")
print(f"Current time: {now.time()}")
# 2. Creating specific dates
today = datetime.date.today()
print(f"Today: {today}")
new_year = datetime.date(2027, 1, 1)
print(f"New Year 2027: {new_year}")
# 3. Creating specific times
time_morning = datetime.time(9, 30, 0)
print(f"Morning time: {time_morning}")
time_evening = datetime.time(18, 45, 30)
print(f"Evening time: {time_evening}")
# 4. Working with timedelta (differences)
today = datetime.date.today()
next_week = today + datetime.timedelta(days=7)
print(f"Next week: {next_week}")
yesterday = today - datetime.timedelta(days=1)
print(f"Yesterday: {yesterday}")
# 5. Date and time formatting
now = datetime.datetime.now()
print(f"Formatted: {now.strftime('%Y-%m-%d %H:%M:%S')}")
print(f"Date only: {now.strftime('%B %d, %Y')}")
print(f"Time only: {now.strftime('%I:%M %p')}")
# 6. Parsing strings to dates
date_string = "2026-08-02"
date_obj = datetime.datetime.strptime(date_string, '%Y-%m-%d')
print(f"Parsed date: {date_obj}")
# 7. Practical example: Age calculator
def calculate_age(birth_date):
today = datetime.date.today()
age = today.year - birth_date.year
if (today.month, today.day) < (birth_date.month, birth_date.day):
age -= 1
return age
birth = datetime.date(1995, 5, 15)
print(f"Age: {calculate_age(birth)} years")
# 8. Practical example: Countdown to an event
def days_until(event_date):
today = datetime.date.today()
delta = event_date - today
return delta.days
event = datetime.date(2027, 1, 1)
print(f"Days until event: {days_until(event)} days")
datetime module key features:
- Date objects — date(year, month, day)
- Time objects — time(hour, minute, second)
- DateTime objects — datetime(year, month, day, hour, minute)
- Timedelta — difference between dates/times
- Formatting — strftime() for custom output
- Parsing — strptime() to convert strings to dates
Quick Check: What would you use to find the difference between two dates? (Answer: timedelta)
os — Operating System Interface
Interacting with the Operating System
# The os module provides functions to interact with the operating system
import os
# 1. Working with directories
print(f"Current working directory: {os.getcwd()}")
# os.chdir('/path/to/directory') # Change directory
# os.mkdir('new_folder') # Create a new directory
# os.rmdir('folder_to_remove') # Remove a directory (must be empty)
# 2. Listing files and directories
print(f"Files in current directory: {os.listdir('.')}")
# 3. Checking if a file or directory exists
print(f"Does 'main.py' exist? {os.path.exists('main.py')}")
print(f"Is 'main.py' a file? {os.path.isfile('main.py')}")
print(f"Is 'main.py' a directory? {os.path.isdir('main.py')}")
# 4. Working with file paths
file_path = "/home/user/documents/file.txt"
print(f"Directory name: {os.path.dirname(file_path)}")
print(f"File name: {os.path.basename(file_path)}")
print(f"File name without extension: {os.path.splitext(file_path)[0]}")
print(f"File extension: {os.path.splitext(file_path)[1]}")
# 5. Joining paths (platform-independent)
folder = "my_folder"
file = "my_file.txt"
full_path = os.path.join(folder, file)
print(f"Full path: {full_path}")
# 6. Getting file information
file_info = os.stat('main.py')
print(f"File size: {file_info.st_size} bytes")
print(f"Last modified: {file_info.st_mtime}")
# 7. Environment variables
print(f"PATH: {os.environ.get('PATH', 'Not set')}")
print(f"HOME: {os.environ.get('HOME', 'Not set')}")
# 8. Practical example: Creating a file with a timestamp
def create_timestamp_file():
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"log_{timestamp}.txt"
with open(filename, 'w') as f:
f.write(f"File created at {datetime.datetime.now()}")
print(f"Created: {filename}")
return filename
# 9. Practical example: Listing all Python files in a directory
def list_python_files(directory="."):
python_files = [f for f in os.listdir(directory)
if f.endswith('.py') and os.path.isfile(os.path.join(directory, f))]
return python_files
print(f"Python files: {list_python_files()}")
os module key features:
- Directory operations — getcwd(), chdir(), mkdir()
- File operations — listdir(), path.exists(), stat()
- Path manipulation — path.join(), path.basename(), path.dirname()
- Environment variables — environ.get()
- Platform independent — works across Windows, Linux, macOS
Quick Check: Which function would you use to get the current working directory? (Answer: getcwd())
sys — System-Specific Parameters
System Information and Utilities
# The sys module provides system-specific parameters and functions
import sys
# 1. Python version
print(f"Python version: {sys.version}")
print(f"Python version info: {sys.version_info}")
# 2. Platform information
print(f"Platform: {sys.platform}")
# 3. Command line arguments
print(f"Command line arguments: {sys.argv}")
# 4. Python path
print("Module search paths:")
for path in sys.path[:5]:
print(f" {path}")
# 5. Standard input, output, error
# sys.stdout.write("Writing to stdout\n")
# sys.stderr.write("Writing to stderr\n")
# 6. Exit the program
# sys.exit() # Exits the program
# 7. System-specific settings
print(f"Default encoding: {sys.getdefaultencoding()}")
print(f"File system encoding: {sys.getfilesystemencoding()}")
# 8. Recursion limit
print(f"Recursion limit: {sys.getrecursionlimit()}")
# sys.setrecursionlimit(2000) # Increase recursion limit
# 9. Size of Python objects
numbers = [1, 2, 3, 4, 5]
print(f"Size of list object: {sys.getsizeof(numbers)} bytes")
# 10. Practical example: Command line argument parser
def parse_args():
if len(sys.argv) < 2:
print("Usage: python script.py ")
return
name = sys.argv[1]
print(f"Hello, {name}!")
# Uncomment to test with command line arguments
# parse_args()
sys module key features:
- System information — version, platform, path
- Command line arguments — argv for accessing arguments
- Standard streams — stdin, stdout, stderr
- Python settings — recursion limit, encoding
- Exit program — sys.exit()
Quick Check: Which attribute contains command line arguments? (Answer: sys.argv)
json — JSON Data Handling
Working with JSON Data
# The json module helps you work with JSON data
import json
# 1. Python dictionary to JSON string
data = {
"name": "Alice",
"age": 25,
"city": "New York",
"hobbies": ["reading", "coding", "hiking"],
"is_student": False
}
json_string = json.dumps(data)
print(f"JSON string: {json_string}")
print(f"Type: {type(json_string)}")
# 2. Pretty printing JSON
pretty_json = json.dumps(data, indent=4, sort_keys=True)
print(f"Pretty JSON:\n{pretty_json}")
# 3. JSON string to Python dictionary
json_data = '{"name": "Bob", "age": 30, "city": "London"}'
python_data = json.loads(json_data)
print(f"Python data: {python_data}")
print(f"Type: {type(python_data)}")
# 4. Reading JSON from a file
# with open('data.json', 'r') as f:
# data = json.load(f)
# 5. Writing JSON to a file
# with open('data.json', 'w') as f:
# json.dump(data, f, indent=4)
# 6. Working with nested JSON
nested_data = {
"user": {
"id": 1,
"name": "Alice",
"profile": {
"age": 25,
"city": "NYC"
}
},
"posts": [
{"id": 101, "title": "Hello World"},
{"id": 102, "title": "Learning Python"}
]
}
print(f"Nested data: {json.dumps(nested_data, indent=2)}")
# 7. Practical example: API response handler
def parse_api_response(response_string):
try:
data = json.loads(response_string)
return data
except json.JSONDecodeError:
return {"error": "Invalid JSON"}
response = '{"status": "success", "data": {"id": 1, "name": "Alice"}}'
parsed = parse_api_response(response)
print(f"Parsed API response: {parsed}")
# 8. Converting custom objects to JSON
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def to_dict(self):
return {"name": self.name, "age": self.age}
person = Person("Charlie", 35)
json_data = json.dumps(person.to_dict())
print(f"Person as JSON: {json_data}")
json module key features:
- Serialization — dumps() to convert Python to JSON
- Deserialization — loads() to convert JSON to Python
- File operations — dump() and load() for files
- Pretty printing — indent parameter for readability
- Common use — APIs, configuration files, data storage
Quick Check: Which function converts a Python dictionary to a JSON string? (Answer: json.dumps())
random — Random Number Generation
Generating Random Values
# The random module generates random numbers and choices
import random
# 1. Random integers
print(f"Random integer between 1 and 10: {random.randint(1, 10)}")
print(f"Random integer between 0 and 100: {random.randint(0, 100)}")
# 2. Random floats
print(f"Random float between 0 and 1: {random.random()}")
print(f"Random float between 5 and 15: {random.uniform(5, 15)}")
# 3. Random choice from a sequence
colors = ['red', 'blue', 'green', 'yellow', 'purple']
print(f"Random color: {random.choice(colors)}")
# 4. Random sample (without replacement)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sample = random.sample(numbers, 3)
print(f"Random sample of 3: {sample}")
# 5. Shuffle a sequence
deck = list(range(1, 53))
random.shuffle(deck)
print(f"Shuffled deck first 5 cards: {deck[:5]}")
# 6. Random seed (for reproducibility)
random.seed(42)
print(f"Reproducible random: {random.randint(1, 100)}")
print(f"Reproducible random: {random.randint(1, 100)}")
print(f"Reproducible random: {random.randint(1, 100)}")
# 7. Random weighted choices
items = ['apple', 'banana', 'cherry']
weights = [0.7, 0.2, 0.1] # 70% apple, 20% banana, 10% cherry
random_choice = random.choices(items, weights=weights, k=10)
print(f"Weighted choices: {random_choice}")
# 8. Practical example: Password generator
def generate_password(length=12):
characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*'
password = ''.join(random.choice(characters) for _ in range(length))
return password
print(f"Generated password: {generate_password()}")
# 9. Practical example: Random dice roll
def roll_dice(sides=6, rolls=1):
return [random.randint(1, sides) for _ in range(rolls)]
print(f"Dice roll: {roll_dice(6, 2)}") # Two 6-sided dice
random module key features:
- Integers — randint(), randrange()
- Floats — random(), uniform()
- Choice functions — choice(), choices(), sample()
- Shuffle — shuffle()
- Seed — seed() for reproducible results
Quick Check: Which function would you use to select a random element from a list? (Answer: random.choice())
collections — Specialized Data Structures
Advanced Data Structures
# The collections module provides specialized data structures
from collections import Counter, defaultdict, OrderedDict, deque, namedtuple
# 1. Counter - Count occurrences
words = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
counter = Counter(words)
print(f"Counter: {counter}")
print(f"Most common: {counter.most_common(2)}")
print(f"Count of 'apple': {counter['apple']}")
# 2. defaultdict - Dictionary with default values
# Regular dictionary
# d = {}
# d['missing'] # KeyError
# Default dictionary
dd = defaultdict(int) # int provides default value 0
dd['count'] += 1
dd['count'] += 1
print(f"Default dict: {dd}")
# Default dict with list
dd_list = defaultdict(list)
dd_list['group_1'].append('item1')
dd_list['group_1'].append('item2')
dd_list['group_2'].append('item3')
print(f"Default dict with list: {dd_list}")
# 3. OrderedDict - Remembers insertion order
# Note: Regular dicts also remember insertion order in Python 3.7+
ordered = OrderedDict()
ordered['first'] = 1
ordered['second'] = 2
ordered['third'] = 3
print(f"Ordered dict: {ordered}")
# 4. deque - Double-ended queue
dq = deque([1, 2, 3])
dq.append(4) # Add to right
dq.appendleft(0) # Add to left
print(f"Deque: {dq}")
dq.pop() # Remove from right
dq.popleft() # Remove from left
print(f"After operations: {dq}")
# 5. namedtuple - Tuple with named fields
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(f"Named tuple: {p}")
print(f"x: {p.x}, y: {p.y}")
print(f"Index access: {p[0]}, {p[1]}")
# 6. Practical example: Word frequency analysis
def word_frequency(text):
words = text.lower().split()
return Counter(words)
text = "The quick brown fox jumps over the lazy dog"
freq = word_frequency(text)
print(f"Word frequency: {freq}")
# 7. Practical example: Grouping data
def group_by_key(items, key_func):
grouped = defaultdict(list)
for item in items:
key = key_func(item)
grouped[key].append(item)
return grouped
data = ['apple', 'banana', 'orange', 'apricot', 'grape']
grouped = group_by_key(data, lambda x: x[0]) # Group by first letter
print(f"Grouped by first letter: {dict(grouped)}")
collections module key features:
- Counter — count occurrences of elements
- defaultdict — dictionary with default values
- OrderedDict — remembers insertion order
- deque — double-ended queue
- namedtuple — tuple with named fields
Quick Check: Which collection would you use to count occurrences? (Answer: Counter)
Try It Yourself
Experiment with Python's inbuilt modules in the editor below. Try using different modules and their functions.
INBUILT MODULES PRACTICE
========================================
1. MATH MODULE
sqrt(64): 8.0
factorial(6): 720
π: 3.1416
2. DATETIME MODULE
Current: 2026-08-02 12:00:00
3. OS MODULE
Current dir: /home/user
4. SYS MODULE
Python version: 3.10.0
5. JSON MODULE
JSON: {"name": "Alice", "age": 25}
6. RANDOM MODULE
Random 1-10: 7
7. COLLECTIONS MODULE
Counter: Counter({'a': 3, 'b': 2, 'c': 1})
Inbuilt modules practice complete!
You've Got It!
You now understand Python's most useful inbuilt modules — math, datetime, os, sys, json, random, and collections. These tools will make your everyday programming much easier!
Quick Quiz
Test what you've learned:
Frequently Asked Questions
What is the difference between math and random modules?
What is the purpose of the os module?
What is the difference between json.dumps() and json.loads()?
What's a common interview question about inbuilt modules?
What is the collections module used for?
When should I use datetime vs time modules?
Where to Go From Here
Now that you've mastered Python's inbuilt modules, check out these related topics:
User-Defined Modules
Learn how to create and use your own modules.
Learn More →📝 Assignments
Practice what you've learned with assignments.
Learn More →File Handling
Learn how to work with files in Python.
Learn More →