LearnFrenzy
Sign in Take a free test

Python Programming · Topic 15 of 25

Modules and Packages Questions and Concepts

  • 4 exercises
  • 50 questions
  • ~60 min
  • Answers explained

Introduction & Syntax

Modules and Packages · Study material

A module is simply a .py file; a package is a folder of modules. Modules let you split a program into files, reuse code across projects and use the huge standard library – math, datetime, json, collections and hundreds more – plus third-party packages installed with pip. Interviews ask how import finds and caches modules, what __name__ == "__main__" does, the difference between import x and from x import y, relative imports and __init__.py. This topic answers them with examples that really run, then gives you 50 practice questions run on Python 3.

On this page

  • Import forms: import, from … import, as, import *
  • Writing your own module and the __main__ guard
  • How imports are found (sys.path) and cached (sys.modules)
  • Packages, __init__.py, absolute and relative imports
  • __all__, dir() and help()
  • Standard library essentials, pip and virtual environments

Ways to import

FormWhat you getUsage
import maththe module objectmath.sqrt(9)
from math import sqrtone name, copied into your namespacesqrt(9)
import numpy as npthe module under a short aliasnp.array(...)
from math import sqrt as roota renamed nameroot(9)
from math import *all public names – avoid: unclear origin, may shadow your namessqrt(9)
import math                              # the whole module: use math.name
from math import sqrt, pi                # specific names into this namespace
from statistics import mean as avg       # rename with as
import datetime as dt                    # module alias

print(math.floor(7.8), sqrt(81), round(pi, 3))
print(avg([70, 80, 90]))
print(dt.date(2026, 11, 30).strftime("%A"))
print(type(math).__name__, math.__name__)

Output

7 9.0 3.142
80
Monday
module math

Writing your own module

Save functions in lf_geometry.py and any file in the same folder (or on sys.path) can import lf_geometry. The module's top-level code runs once, at the first import. When a file is run directly its __name__ is "__main__"; when imported it is the module name – so put test or demo code under if __name__ == "__main__":. Names starting with an underscore are internal by convention. (The example writes the module to a temporary folder so that it can run here as one file.)

import sys, tempfile, textwrap, pathlib

folder = pathlib.Path(tempfile.mkdtemp())
# Any .py file is a module. Write one: lf_geometry.py
(folder / "lf_geometry.py").write_text(textwrap.dedent('''
    """Simple geometry helpers."""
    PI = 3.14159

    def circle_area(r):
        return round(PI * r * r, 2)

    def _helper():                 # leading underscore: "internal" by convention
        return "hidden"

    if __name__ == "__main__":     # runs only when the file itself is executed
        print("testing geometry")
'''))

sys.path.insert(0, str(folder))     # let Python find modules in that folder
import lf_geometry

print(lf_geometry.circle_area(2))
print(lf_geometry.__name__, lf_geometry.__doc__)
print([n for n in dir(lf_geometry) if not n.startswith("__")])

Output

12.57
lf_geometry Simple geometry helpers.
['PI', '_helper', 'circle_area']

How imports are found and cached

import x first checks sys.modules, the cache of already-loaded modules; only if x is not there does Python search the folders in sys.path – the script's folder, PYTHONPATH, the standard library and site-packages – load the file and run it. Importing again returns the cached module without running its code. importlib.reload(module) re-executes the file. Never name your own file like a standard module (random.py, math.py, json.py): it would be found first and hide the real one.

import sys, tempfile, pathlib, importlib

folder = pathlib.Path(tempfile.mkdtemp())
(folder / "lf_config.py").write_text('print("loading lf_config")\nMODE = "dev"\n')
sys.path.insert(0, str(folder))

import lf_config            # runs the module's code: prints once
import lf_config            # already in sys.modules: nothing runs again
print("lf_config" in sys.modules, lf_config.MODE)

lf_config.MODE = "prod"     # module attributes can be changed at run time
importlib.reload(lf_config) # reload re-executes the file
print(lf_config.MODE)

Output

loading lf_config
True dev
loading lf_config
dev

Packages

A package is a folder of modules, optionally with an __init__.py that runs when the package is imported (and can expose convenient names). Inside a package, modules can import each other with relative imports (from .pricing import with_gst, from .. import x); from outside, use absolute imports such as from lf_shop.payments.upi import pay. Relative imports work only in modules that belong to a package – not in a script run directly.

import sys, tempfile, pathlib

root = pathlib.Path(tempfile.mkdtemp())
pkg = root / "lf_shop"
(pkg / "payments").mkdir(parents=True)

(pkg / "__init__.py").write_text('VERSION = "1.0"\nfrom .cart import total\n')
(pkg / "cart.py").write_text(
    "from .pricing import with_gst\n"                 # relative import inside the package
    "def total(prices):\n    return with_gst(sum(prices))\n")
(pkg / "pricing.py").write_text("def with_gst(amount):\n    return round(amount * 1.18, 2)\n")
(pkg / "payments" / "__init__.py").write_text("")
(pkg / "payments" / "upi.py").write_text('def pay(amount):\n    return f"Paid Rs {amount} by UPI"\n')

sys.path.insert(0, str(root))
import lf_shop
from lf_shop.payments.upi import pay      # absolute import of a sub-package module

print(lf_shop.VERSION, lf_shop.total([100, 250]))
print(pay(413.0))

Output

1.0 413.0
Paid Rs 413.0 by UPI

The standard library

Python ships "batteries included". A few modules worth knowing well: math and statistics for numbers, random and secrets for random values, datetime for dates, collections (Counter, defaultdict, deque, namedtuple), itertools (combinations, permutations, accumulate, groupby), functools (lru_cache, partial, reduce), json and csv for data files, os, pathlib and shutil for files, re for regular expressions, and sys for the interpreter.

import math, statistics, json
from collections import Counter, defaultdict, deque
from itertools import combinations, accumulate
from datetime import date, timedelta
from pathlib import PurePosixPath

print(math.gcd(84, 36), math.isqrt(50), math.comb(5, 2))
print(statistics.median([7, 1, 5, 3]), Counter("banana").most_common(1))
print(list(combinations("ABC", 2)), list(accumulate([1, 2, 3, 4])))
print(date(2026, 12, 25) - date(2026, 11, 30), date(2026, 11, 30) + timedelta(days=45))
print(json.dumps({"name": "Asha", "skills": ["python", "sql"]}))
p = PurePosixPath("reports") / "2026" / "marks.csv"
print(p, p.suffix, p.stem)

Output

12 7 10
4.0 [('a', 3)]
[('A', 'B'), ('A', 'C'), ('B', 'C')] [1, 3, 6, 10]
25 days, 0:00:00 2027-01-14
{"name": "Asha", "skills": ["python", "sql"]}
reports/2026/marks.csv .csv marks

pip and virtual environments

Third-party packages come from PyPI. Create an isolated virtual environment per project so that each has its own package versions, then install with pip:

python -m venv .venv                 # create the environment in the folder .venv
source .venv/bin/activate            # activate (Windows: .venv\Scripts\activate)
pip install requests pandas          # install packages into this environment only
pip freeze > requirements.txt        # record exact versions
pip install -r requirements.txt      # recreate the same environment elsewhere
deactivate                           # leave the environment

Common mistakes

  • Naming a file random.py or math.py – it hides the standard module.
  • import math, then sqrt(9) – NameError; write math.sqrt or from math import sqrt.
  • from module import * – unclear names; can shadow built-ins (os exports open).
  • Assigning to a module name – math = 3.14 replaces the module.
  • Test code without a __main__ guard – it runs on every import.
  • Relative imports in a script – ImportError: no known parent package.
  • Editing a module and importing again – the cached version is used; reload or restart.

Key points to remember

  • A module is a .py file; a package is a folder of modules.
  • A module's code runs once, on first import; later imports use sys.modules.
  • Python searches sys.path in order – the script's folder first.
  • __name__ is "__main__" only for the file being run.
  • __init__.py runs when its package is imported.
  • Relative imports (from . import x) work only inside packages.
  • __all__ lists what from module import * brings in.

Frequently asked questions

Is __init__.py required?

Not since Python 3.3 – a folder without it is a "namespace package". Adding it is still the norm: it marks a regular package and lets you run setup code or re-export names.

What is the difference between a module, a package and a library?

A module is one file, a package is a folder of modules, and "library" is an informal word for a collection of packages you install and use (such as requests or pandas).

Where are installed packages stored?

In the site-packages folder of the active environment; python -m site or pip show package-name shows the location.

Where can I learn more?

Read Python Modules, pip and Virtual Environments and The Python Standard Library in the Python tutorial, then practise with the exercises below.

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About Python Programming

Why it matters

  • Python is the most popular first language and the default for data science, AI, automation and scripting
  • Campus coding rounds and technical interviews increasingly allow – or prefer – Python
  • "Predict the output" questions on lists, strings, dictionaries and mutable defaults are a favourite in written tests
  • Clean Python with comprehensions, generators and OOP is what product companies expect from freshers

Who it is for

  • School students (Class 11–12 computer science with Python) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA, B.Sc CS) preparing for semester exams, lab work and viva
  • Freshers preparing for campus placements, coding tests and Python interviews
  • Anyone moving into data science, AI or automation who needs strong Python fundamentals

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • Topic-wise MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs: syntax errors, runtime exceptions and logical bugs
  • Coding problems with solutions and real output, every one run on Python 3 – open any example in the online Python compiler

Asked in

  • Campus placements
  • TCS, Infosys, Wipro, Accenture tests
  • Python interviews for freshers
  • Data science interviews
  • CBSE / university practicals
  • GATE CS

How to use this section

  1. Read the study material of a topic and run the examples in the browser.
  2. Practise the four exercises – MCQs, output, errors, coding problems – each marked Easy, Medium or Hard, and read every explanation.
  3. Revise with the interview questions and cheat sheet, then move to the next topic.

Search LearnFrenzy

Esc

Quick links