Programming Challenge 2/99 Temperature Converter

Today I would like to complicate my next task and make this temperature converter object-oriented.

import sys
#Template class for scale classes
class Unit:
    value = None
    def __init__(self,val):
        self.value = val

class Fahrenheit(Unit):
    def toFahrenheit(self):
        return self.value

    def toCelsius(self):
        return (self.value - 32) * 5/9

    def toKelvin(self):
        return (self.value - 32) * 5/9 + 273.15

class Celsius(Unit):
    def toFahrenheit(self):
        return (self.value * 9/5) + 32

    def toCelsius(self):
        return self.value

    def toKelvin(self):
        return self.value + 273.15

class Kelvin(Unit):
    def toFahrenheit(self):
        return (self.value - 273.15) * 9/5 + 32

    def toCelsius(self):
        return self.value - 273.15

    def toKelvin(self):
        return self.value

In this part of code temperature classes inherit the unit class. Temperature classes contain a method to convert to the same temperature to simplify user input check algorithm(in second part of code).

def main(args):
    temp = None
    usage = "USAGE:python tempconv.py [NUMBER][F|K|C] [>|to] [F|K|C] \nEXAMPLE:python tempconv.py 12F to C"
    if len(args) < 4:
        print(usage)
        return
    value = args[1][:0-1]
    scale = args[1][0-1]
    #Check scale letter and create class instance
    if scale == "F" or scale == "f":
        temp = Fahrenheit(float(value))
    elif scale == "C" or scale == "c":
        temp = Celsius(float(value))
    elif scale == "K" or scale == "k":
        temp = Kelvin(float(value))
    else:
        print(usage)
    #Check program function operator(May be more in future)
    if args[2] == "to" or args[2] == ">":
        pass
    else:
        print(usage)
        return
    #Check scale to convert
    if args[3] == "K" or args[3] == "k":
        print(temp.toKelvin())
    elif args[3] == "C" or args[3] == "c":
        print(temp.toCelsius())
    elif args[3] == "F" or args[3] == "f":
        print(temp.toFahrenheit())
    else:
        print(usage)

main(sys.argv)

This part of the code is explained by the code comments.

Leave a Comment