Ojasa Mirai

Ojasa Mirai

Python

Loading...

Learning Level

🟢 Beginner🔵 Advanced
Modules Import BasicsCreating ModulesImport StatementsRelative ImportsImport PathsPackages StructureNamespace PackagesPip & DependenciesModule Performance
Python/Modules Packages/Modules Import Basics

📚 Modules Import Basics — Organizing Your Code

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.


🎯 What is a Module?

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.56

💡 The import Keyword

The `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 json

🎨 Built-in Modules

Python 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})

🔄 Different Import Styles

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)

🏗️ Checking Module Contents

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.so

📊 Practical Examples

Example 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, 2024

Example 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}")

🔑 Key Takeaways

  • ✅ Modules are `.py` files containing reusable code
  • ✅ Use `import module_name` to load a module
  • ✅ Access module items with `module_name.item`
  • ✅ Python includes many built-in modules (math, random, datetime, os, etc.)
  • ✅ `from module import item` imports specific items directly
  • ✅ Use `dir()` and `help()` to explore module contents

Ready to practice? Challenges | Quiz


Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn