Python Modules: Create, Import, and Use Them Right
A practical guide to Python modules: what they are, three import styles, built-in modules for placement tests, and the __name__ guard with working code.
A Python module is just a .py file, and understanding how to create, import, and structure one separates clean placement code from tangled single-file submissions.
What a Python module is
Per the Python documentation, a module is a file containing Python definitions and statements. The file name is the module name with the .py suffix. Every Python file you write is already a module; you just haven’t imported it from another file yet.
Three reasons modules matter for placement-level code:
- Reusability. Write a helper function once in its own file. Import it wherever you need it rather than copying the code into every solution.
- Testability. A function isolated in a module is easier to test with edge cases than the same function buried inside a 200-line script.
- Namespace clarity. Each module has its own namespace, so a function named
sortin yourutils.pydoesn’t collide with asortdefined elsewhere.
The Python basic programs guide covers the individual functions you’ll write at this level. Modules are the next layer: organising those functions into importable files.
How to create a custom module
Creating a module takes two steps: write a .py file, then import it from another script.
Step 1: write the module file.
Save the following as calc.py:
# calc.py
def add(a, b):
return a + b
def sub(a, b):
return a - b
That’s it. calc.py is a module. No special keyword, no class wrapper required.
Step 2: import it in your main script.
Save this as main.py in the same directory:
# main.py
from calc import add, sub
result1 = add(20, 10)
print(result1) # 30
result2 = sub(20, 10)
print(result2) # 10
Run it from the terminal:
python main.py
The calculator program in Python extends this exact calc.py pattern into a full interactive program. Read it once you’re comfortable with imports.
Three import styles
Python gives you three ways to import from a module. Each has a legitimate use case:
import module
import calc
print(calc.add(5, 3)) # 8
Use this when you want to make it clear which module a function comes from. Calling calc.add() is unambiguous in code review.
from module import name
from calc import add
print(add(5, 3)) # 8
Use this when you call the function many times and the module name would clutter the code. Avoid it for modules where function names might clash with your own.
import module as alias
import calc as c
print(c.add(5, 3)) # 8
Common in data science (import numpy as np) but useful anywhere the module name is long. Placement tests rarely penalise alias choice, but use short, conventional abbreviations.
A note on star imports. from calc import * imports everything in the module into the current namespace. It works, but it makes code harder to read and can shadow names you’ve already defined. Avoid it in placement submissions unless the problem statement explicitly uses it.
Built-in modules for placement tests
Python ships with a large standard library. Four modules appear in placement test scenarios often enough to memorise their key functions:
math
The math module covers square roots, logarithms, trigonometry, and constants like pi.
import math
print(math.sqrt(144)) # 12.0
print(math.factorial(5)) # 120
print(math.ceil(4.2)) # 5
print(math.floor(4.9)) # 4
print(math.gcd(12, 8)) # 4
The array sum program in this cluster uses built-in sum(). Use math.fsum() instead when floating-point precision matters, as it handles rounding errors that sum() does not. This distinction appears in AMCAT numerical coding questions.
os
The os module interacts with the file system and the operating system. Placement tests that involve file reading or path manipulation lean on it.
import os
print(os.getcwd()) # current working directory
print(os.listdir('.')) # list files in current directory
os.mkdir('new_folder') # create a directory
sys
sys provides access to the Python runtime environment. The most-used function in placement contexts is sys.argv, which reads command-line arguments.
import sys
print(sys.argv) # list of command-line arguments
print(sys.version) # Python version string
sys.exit(0) # clean exit with status code
datetime
Date arithmetic shows up in reasoning-type coding questions. datetime handles it cleanly.
from datetime import date, datetime
today = date.today()
print(today) # e.g. 2026-05-09
now = datetime.now()
print(now.strftime("%d-%m-%Y %H:%M")) # formatted timestamp
The __name__ guard
Every Python module has a built-in attribute called __name__. When you run a file directly, Python sets __name__ to '__main__'. When you import it from another script, __name__ is set to the module’s file name.
This matters because:
# calc.py
def add(a, b):
return a + b
def sub(a, b):
return a - b
if __name__ == '__main__':
# This block runs only when calc.py is run directly
print(add(10, 5)) # 15
print(sub(10, 5)) # 5
Without the guard, every script that imports calc would also trigger the print statements, producing unexpected output. With the guard, those lines are invisible to importers.
Placement tests sometimes provide starter code that uses this pattern. Knowing why it’s there prevents you from deleting it and corrupting the output the grader expects.
Modules as the entry point to real Python projects
Writing code as a single flat script gets unwieldy past a few hundred lines. Every substantial Python project (web apps built on Django, data pipelines using pandas, API clients using requests) is structured as a collection of modules, each responsible for one concern.
If you’ve worked through the programs in this guide and the Python basic programs guide, you already have the building blocks. The next step is writing code that someone else (or a test runner) can import and verify.
TinkerLLM’s Python-based exercises are structured exactly this way: each task expects a function in one file, called from a separate test runner in another. That multi-file structure is what this article teaches. Working through a few of those exercises on TinkerLLM at ₹299 builds the import-and-test habit faster than debugging a monolithic script the night before your placement round.
Primary sources
Frequently asked questions
What is the difference between a Python module and a package?
A module is a single .py file. A package is a folder containing an __init__.py file plus one or more module files. When you write 'import numpy', numpy is a package; when you import a single .py file you wrote, that is a module.
Does importing a module twice slow down a Python program?
No. Python caches every imported module in sys.modules after the first import. Subsequent import statements for the same module just fetch the cached reference rather than re-executing the file.
How do I see all functions inside a module?
Call dir(module_name) after importing it. This returns a list of every attribute and function the module exposes. For built-ins, help(module_name) gives a formatted reference with docstrings.
Can two Python files have the same module name?
They can coexist on disk, but Python's import system resolves by path order in sys.path. If two files share a name, the one in the directory that appears first in sys.path wins. Rename one to avoid ambiguity.
Do placement tests ask questions about Python modules?
Yes. TCS NQT, AMCAT Automata, and Infosys Hackathon rounds include questions where the starter code imports a module you must use correctly. Knowing import styles and built-in module functions prevents avoidable errors in timed tests.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)