Abstract
The Measurement Conversion Tool is a Python-based project
designed to perform accurate and efficient unit conversions
across multiple domains, including length, mass, volume,
temperature, and time. The system applies object-oriented
programming (OOP) concepts to create a modular and
extensible framework, built around a common Base
Converter class and specialized subclasses for each
measurement category.
Each converter handles its own unit definitions and
conversion logic, ensuring scalability and clarity. The program
also features an interactive command-line interface (CLI) that
allows users to select a category, input values and units, and
instantly receive converted results. It includes intelligent unit
normalization, validation, and error handling for a smooth
user experience.
Additionally, the project is structured to integrate with web
frameworks like Django, allowing future expansion into a
web-based conversion tool. Overall, this project
demonstrates the practical application of OOP design,
modular coding, and user interaction handling in Python,
making it a robust and educational system for real-world
measurement conversions.
Index
Abstract
Page no.
1
Code
conversion.py
(Backend)
main.py (User Interface
-CLI)
Django management
file (Web Integration)
3
Outputs
16
Conclusions
18
Advantages
19
Limitations
20
Future Scopes
21
References
22
Code
i)
Backend
class BaseConverter:
def convert(self, value, from_unit, to_unit):
from_unit = self._normalize_unit(from_unit)
to_unit = self._normalize_unit(to_unit)
if from_unit not in self.units or to_unit not in self.units:
raise ValueError(f"Invalid units. Available units: {list(self.units.keys())}")
if from_unit == to_unit:
return value
base_value = value * self.units[from_unit]
return base_value / self.units[to_unit]
def _normalize_unit(self, unit):
unit = unit.lower().strip()
unit_mapping = {
'm': 'meters', 'meter': 'meters', 'metre': 'meters',
'km': 'kilometers', 'kilometer': 'kilometers', 'kilometre': 'kilometers',
'cm': 'centimeters', 'centimeter': 'centimeters', 'centimetre':
'centimeters',
'mm': 'millimeters', 'millimeter': 'millimeters', 'millimetre': 'millimeters',
'ft': 'feet', 'foot': 'feet', 'feets': 'feet',
'in': 'inches', 'inch': 'inches',
'yd': 'yards', 'yard': 'yards',
'mi': 'miles', 'mile': 'miles',
'nmi': 'nautical_miles', 'nautical_mile': 'nautical_miles',
'kg': 'kilograms', 'kilogram': 'kilograms', 'kilo': 'kilograms',
'g': 'grams', 'gram': 'grams',
'lb': 'pounds', 'pound': 'pounds', 'lbs': 'pounds',
'oz': 'ounces', 'ounce': 'ounces',
'ton': 'tons', 'tons': 'tons',
't': 'metric_tons', 'metric_ton': 'metric_tons',
'l': 'liters', 'liter': 'liters', 'litre': 'liters',
'ml': 'milliliters', 'milliliter': 'milliliters', 'millilitre': 'milliliters',
'gal': 'gallons', 'gallon': 'gallons',
'qt': 'quarts', 'quart': 'quarts',
'pt': 'pints', 'pint': 'pints',
'cup': 'cups', 'c': 'cups',
'fl_oz': 'fluid_ounces', 'floz': 'fluid_ounces', 'fluid_ounce': 'fluid_ounces',
'c': 'celsius', 'celcius': 'celsius', 'centigrade': 'celsius',
'f': 'fahrenheit', 'fahr': 'fahrenheit',
'k': 'kelvin',
's': 'seconds', 'sec': 'seconds', 'second': 'seconds',
'min': 'minutes', 'mins': 'minutes', 'minute': 'minutes',
'h': 'hours', 'hr': 'hours', 'hrs': 'hours', 'hour': 'hours',
'd': 'days', 'day': 'days',
'w': 'weeks', 'wk': 'weeks', 'week': 'weeks',
'mo': 'months', 'month': 'months',
'y': 'years', 'yr': 'years', 'yrs': 'years', 'year': 'years'
}
return unit_mapping.get(unit, unit)
class LengthConverter(BaseConverter):
def __init__(self):
self.units = {
'meters': 1.0,
'kilometers': 1000.0,
'centimeters': 0.01,
'millimeters': 0.001,
'feet': 0.3048,
'inches': 0.0254,
'yards': 0.9144,
'miles': 1609.344,
'nautical_miles': 1852.0
}
class MassConverter(BaseConverter):
def __init__(self):
self.units = {
'kilograms': 1.0,
'grams': 0.001,
'pounds': 0.453592,
'ounces': 0.0283495,
'tons': 1000.0,
'metric_tons': 1000.0
}
class VolumeConverter(BaseConverter):
def __init__(self):
self.units = {
'liters': 1.0,
'milliliters': 0.001,
'gallons': 3.78541,
'quarts': 0.946353,
'pints': 0.473176,
'cups': 0.236588,
'fluid_ounces': 0.0295735
}
class TemperatureConverter(BaseConverter):
def __init__(self):
self.units = {}
def convert(self, value, from_unit, to_unit):
from_unit = self._normalize_unit(from_unit)
to_unit = self._normalize_unit(to_unit)
valid_units = ['celsius', 'fahrenheit', 'kelvin']
if from_unit not in valid_units or to_unit not in valid_units:
raise ValueError(f"Invalid temperature units. Available: {valid_units}")
if from_unit == 'celsius':
celsius = value
elif from_unit == 'fahrenheit':
celsius = (value - 32) * 5/9
elif from_unit == 'kelvin':
celsius = value - 273.15
if to_unit == 'celsius':
return celsius
elif to_unit == 'fahrenheit':
return celsius * 9/5 + 32
elif to_unit == 'kelvin':
return celsius + 273.15
class TimeConverter(BaseConverter):
def __init__(self):
self.units = {
'seconds': 1.0,
'minutes': 60.0,
'hours': 3600.0,
'days': 86400.0,
'weeks': 604800.0,
'months': 2629746.0,
'years': 31556952.0
}
def convert_length(value, from_unit, to_unit):
converter = LengthConverter()
return converter.convert(value, from_unit, to_unit)
def convert_mass(value, from_unit, to_unit):
converter = MassConverter()
return converter.convert(value, from_unit, to_unit)
def convert_volume(value, from_unit, to_unit):
converter = VolumeConverter()
return converter.convert(value, from_unit, to_unit)
def convert_temperature(value, from_unit, to_unit):
converter = TemperatureConverter()
return converter.convert(value, from_unit, to_unit)
def convert_time(value, from_unit, to_unit):
converter = TimeConverter()
return converter.convert(value, from_unit, to_unit)
if __name__ == "__main__":
print("Testing converters...")
lc = LengthConverter()
print(f"10 meters = {lc.convert(10, 'meters', 'feet'):.2f} feet")
mc = MassConverter()
print(f"1 kilogram = {mc.convert(1, 'kg', 'pounds'):.2f} pounds")
vc = VolumeConverter()
print(f"1 gallon = {vc.convert(1, 'gallons', 'liters'):.2f} liters")
tc = TemperatureConverter()
print(f"32°F = {tc.convert(32, 'fahrenheit', 'celsius'):.2f}°C")
timec = TimeConverter()
print(f"1 hour = {timec.convert(1, 'hours', 'minutes'):.2f} minutes")
ii) main.py (CLI)
from conversion import (
LengthConverter,
MassConverter,
VolumeConverter,
TemperatureConverter,
TimeConverter
)
def print_banner():
print("=" * 60)
print("
MEASUREMENT CONVERSION TOOL")
print("=" * 60)
print()
def get_available_units():
return {
'length': {
'meters': 'm', 'kilometers': 'km', 'centimeters': 'cm', 'millimeters': 'mm',
'feet': 'ft', 'inches': 'in', 'yards': 'yd', 'miles': 'mi',
'nautical_miles': 'nmi'
},
'mass': {
'kilograms': 'kg', 'grams': 'g', 'pounds': 'lb', 'ounces': 'oz',
'tons': 'ton', 'metric_tons': 't'
},
'volume': {
'liters': 'l', 'milliliters': 'ml', 'gallons': 'gal', 'quarts': 'qt',
'pints': 'pt', 'cups': 'cup', 'fluid_ounces': 'fl_oz'
},
'temp': {
'celsius': 'c', 'fahrenheit': 'f', 'kelvin': 'k'
},
'time': {
'seconds': 's', 'minutes': 'min', 'hours': 'h', 'days': 'd',
'weeks': 'w', 'months': 'mo', 'years': 'y'
}
}
def interactive_mode():
print("Welcome to Interactive Conversion Mode!")
print("Type 'quit' or 'exit' to leave the program.\n")
available_units = get_available_units()
while True:
print("Available categories:")
for i, category in enumerate(available_units.keys(), 1):
print(f" {i}. {category}")
try:
choice = input("\nSelect a category (1-5) or 'quit': ").strip().lower()
if choice in ['quit', 'exit', 'q']:
print("Goodbye!")
break
category_num = int(choice)
categories = list(available_units.keys())
if 1 <= category_num <= len(categories):
category = categories[category_num - 1]
units = available_units[category]
print(f"\nAvailable units for {category}:")
for unit, abbrev in units.items():
print(f" {unit} ({abbrev})")
value = float(input(f"\nEnter value to convert: "))
from_unit = input("From unit: ").strip().lower()
to_unit = input("To unit: ").strip().lower()
result = perform_conversion(category, value, from_unit, to_unit)
if result is not None:
print(f"\nResult: {value} {from_unit} = {result:.6f} {to_unit}")
else:
print("Invalid units or conversion error!")
else:
print("Invalid choice! Please select 1-5.")
except ValueError:
print("Invalid input! Please enter a number or 'quit'.")
except KeyboardInterrupt:
print("\n\nGoodbye!")
break
print("\n" + "-" * 40)
def perform_conversion(category, value, from_unit, to_unit):
try:
if category == 'length':
converter = LengthConverter()
elif category == 'mass':
converter = MassConverter()
elif category == 'volume':
converter = VolumeConverter()
elif category == 'temp':
converter = TemperatureConverter()
elif category == 'time':
converter = TimeConverter()
else:
return None
return converter.convert(value, from_unit, to_unit)
except Exception as e:
print(f"Conversion error: {e}")
return None
print_banner()
interactive_mode()
iii)- Django Management File
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE',
'conversion_web.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
if __name__ == '__main__':
main()
Output
Output
Conclusions
The Measurement Conversion Tool project successfully
demonstrates the use of object-oriented programming (OOP)
concepts in Python to build a reliable, extensible, and userfriendly conversion system. By integrating multiple converter
classes under a unified architecture, the project showcases
how inheritance, modularity, and code reusability can be
effectively applied to solve real-world computational
problems.
The tool provides a simple and efficient way to perform
conversions across five major measurement categories —
length, mass, volume, temperature, and time — using a
consistent logic pattern and well-defined conversion factors.
Through the use of normalization, error handling, and
interactive user prompts, the program ensures accuracy and
ease of use for users of all levels.
Furthermore, the modular design and inclusion of a Djangocompatible structure highlight its scalability, allowing future
expansion into a web-based platform without altering the
existing logic.
Overall, this project strengthens understanding of software
design principles and practical implementation of data
abstraction, making it a valuable learning experience and a
functional utility for everyday scientific and engineering
conversions.
Advantages
User-Friendly Interface:
The interactive command-line interface allows users to
perform conversions easily with clear prompts and
instructions.
Accurate Conversions:
Uses reliable mathematical formulas and predefined
conversion constants to ensure high precision across all
categories.
Modular Design:
The project is structured using object-oriented
principles, making each converter (Length, Mass,
Volume, etc.) independent and reusable.
Scalability:
New measurement categories or units can be added
easily without changing the existing code structure.
Error Handling:
Handles invalid units and incorrect inputs gracefully
using input validation and exception handling.
Cross-Platform Compatibility:
Runs smoothly on any operating system that supports
Python (Windows, Linux, macOS).
Expandable Architecture:
Integration with Django (manage.py) allows future
transition to a web-based application without modifying
the backend logic.
Limitations
No GUI Interface:
Currently limited to a text-based interface; lacks
graphical visualization or modern UI components.
No File Storage:
The program doesn’t save user preferences,
history, or conversion results permanently.
No Real-Time Unit Updates:
Conversion constants are fixed and not
automatically updated from online data sources.
Limited to Standard Units:
Does not include specialized or scientific units
(e.g., nanometers, light-years, or atomic mass
units).
Manual Input Required:
Requires user input for every conversion; no batch
or automated conversion functionality.
Django Part Not Fully Implemented:
The Django setup (manage.py) is provided only for
future expansion — the web interface is not yet
active.
Future Scope
Graphical User Interface (GUI):
The project can be enhanced by developing a userfriendly graphical interface using libraries such as
Tkinter, PyQt, or Kivy, allowing users to perform
conversions through interactive buttons and input
fields instead of the command line.
Web-Based Application:
With the inclusion of the Django framework, the
system can be expanded into a web application
where users can access the converter online
through a browser, making it more accessible and
platform-independent.
File Handling and Data Storage:
The tool can be upgraded to store conversion
history and user preferences in local files or
databases for better usability and reference.
Real-Time Data Integration:
Future versions can integrate API-based updates to
fetch and update conversion factors dynamically,
ensuring the system remains accurate and up to
date.
Additional Unit Categories:
The project can be extended to include scientific
and engineering units, such as pressure, energy,
force, or digital storage conversions.
Voice and Batch Input Support:
Adding voice commands or the ability to perform
multiple conversions at once would make the
system more efficient and interactive.
Mobile Application Development:
The project can be ported to Android or iOS
platforms using frameworks like Kivy or Flutter with
Python backend, increasing accessibility and
convenience for everyday use.
References
Python Software Foundation. Python 3.12 Documentation. Retrieved
from: https://docs.python.org/3/
W3Schools. Python Classes and Objects Tutorial.
https://www.w3schools.com/python/python_classes.asp
GeeksforGeeks. Object-Oriented Programming in Python.
https://www.geeksforgeeks.org/python-oops-concepts/
TutorialsPoint. Python Exception Handling. Available at:
https://www.tutorialspoint.com/python/python_exceptions.htm
Django Software Foundation. Django Official Documentation. Available
at: https://docs.djangoproject.com/
Stack Overflow Community Discussions. Handling unit conversions and
normalization in Python. Accessed October 2025.
Unit Conversion Reference. International System of Units (SI) Base Units.
Bureau International des Poids et Mesures (BIPM). Retrieved from:
https://www.bipm.org/en/measurement-units/
0
You can add this document to your study collection(s)
Sign in Available only to authorized usersYou can add this document to your saved list
Sign in Available only to authorized users(For complaints, use another form )