
Python
A module is a Python file containing code (functions, classes, variables) that you can reuse in other programs. Importing modules allows you to access and use that code without rewriting it.
A module is simply a `.py` file. When you import it, Python loads the code and makes it available to use.
# math_helpers.py (this is a module)
def add(a, b):
return a + b
def subtract(a, b):
return a - b
PI = 3.14159# main.py (importing the module)
import math_helpers
result = math_helpers.add(5, 3) # 8
area = math_helpers.PI * 2 ** 2 # ~12.56The `import` keyword loads a module and makes it available in your code.
# Import the entire module
import math
# Access items using dot notation
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
print(math.ceil(4.3)) # 5
# Import multiple modules
import os
import sys
import jsonPython comes with many built-in modules you can use immediately.
# The 'datetime' module for working with dates
import datetime
today = datetime.datetime.now()
print(today) # 2024-02-23 15:30:45.123456
# The 'random' module for random numbers
import random
dice_roll = random.randint(1, 6)
print(dice_roll) # Random number 1-6
# The 'string' module for text utilities
import string
print(string.ascii_letters) # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
print(string.digits) # 0123456789
# The 'collections' module for specialized data structures
import collections
counter = collections.Counter(['a', 'b', 'a', 'c', 'a'])
print(counter) # Counter({'a': 3, 'b': 1, 'c': 1})Python offers several ways to import, each with different benefits.
# Style 1: Import entire module
import math
result = math.sqrt(9) # Need to use 'math.' prefix
# Style 2: Import specific items
from math import sqrt, pi
result = sqrt(9) # No prefix needed
print(pi)
# Style 3: Import everything (use with caution!)
from math import *
result = sqrt(9) # Works, but unclear where functions come from
# Style 4: Import with alias
import math as m
result = m.sqrt(9) # Shorter namespace
# Style 5: Import specific item with alias
from math import sqrt as square_root
result = square_root(16)Use `dir()` to see what's in a module, and `help()` to learn about it.
import math
# List all items in the module
print(dir(math))
# ['__doc__', '__loader__', '__name__', '__package__', '__spec__',
# 'acos', 'acosh', 'asin', 'asinh', 'atan', ...]
# Get help about a specific function
help(math.sqrt)
# Help on built-in function sqrt in module math:
# sqrt(x, /)
# Return the square root of x.
# Get the module's docstring
print(math.__doc__)
# Get the module's file location
print(math.__file__)
# /usr/lib/python3.9/lib-dynload/math.cpython-39-darwin.soExample 1: Using the `random` module for a game
import random
def guess_number_game():
secret = random.randint(1, 100)
guess = None
attempts = 0
while guess != secret:
guess = int(input("Guess a number (1-100): "))
attempts += 1
if guess < secret:
print("Too low!")
elif guess > secret:
print("Too high!")
else:
print(f"Correct! You won in {attempts} attempts!")Example 2: Using the `datetime` module
import datetime
# Get current date and time
now = datetime.datetime.now()
print(f"Current time: {now}")
# Create specific dates
birthday = datetime.datetime(1990, 5, 15)
print(f"Birthday: {birthday}")
# Calculate time differences
age_delta = now - birthday
print(f"Days since birthday: {age_delta.days}")
# Format dates for display
formatted = now.strftime("%B %d, %Y")
print(formatted) # February 23, 2024Example 3: Using the `os` module for file operations
import os
# Get current working directory
current_dir = os.getcwd()
print(f"Current directory: {current_dir}")
# List files in a directory
files = os.listdir(".")
print(f"Files: {files}")
# Check if a file exists
if os.path.exists("data.txt"):
print("File exists!")
# Get file information
file_size = os.path.getsize("data.txt") # Size in bytes
print(f"File size: {file_size}")Ready to practice? Challenges | Quiz
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward