Start New Discussion within our Software Development Community

Did you ever want to know how how many square inches are in a square meter? This short Python code allows you to get the answer. It uses a dictionary to simplify the conversions. Could be the start of a nice GUI program using radio buttons.

# convert area units, also has error trapping
# tested with Python24     vegaseat      01aug2005

#create an empty dictionary
areaD = {}
# populate dictionary using indexing and assignment with units and conversion factors relative to sqmeter = 1.0
# to convert x sqmeters to any of the other area units multiply by the factor
# to convert x of any of the other area units to sqmeter divide by the factor
# to convert x of any area unit to any of the other area units go over interim sqmeter
# this minimizes the total number of conversion factors
areaD['sqmeter']      = 1.0
areaD['sqmillimeter'] = 1000000.0
areaD['sqcentimeter'] = 10000.0
areaD['sqkilometer']  = 0.000001
areaD['hectare']      = 0.0001
areaD['sqinch']       = 1550.003
areaD['sqfoot']       = 10.76391
areaD['sqyard']       = 1.19599
areaD['acre']         = 0.0002471054
areaD['sqmile']       = 0.0000003861022


def convertArea(x, unit1, unit2):
    """area conversion with error trapping"""
    if (unit1 in areaD) and (unit2 in areaD):
        factor1 = areaD[unit1]
        factor2 = areaD[unit2]
        return factor2*x/factor1
    else:
        return False


# test1: x square-miles have how many acres?
x = 1.0
unit1 = 'sqmile'
unit2 = 'acre'
outcome = convertArea(x, unit1, unit2)
if outcome is not False:
    print "1)  %f %s = %f %s" % (x, unit1, outcome, unit2)
else:
    print "1)  There was an error converting %s to %"  % (unit1, unit2)

# test2: force an error, misspelled unit is not in the dictionary
unit2 = 'acres'  
outcome = convertArea(x, unit1, unit2)
if outcome is not False:
    print "2)  %f %s = %f %s" % (x, unit1, outcome, unit2)
else:
    print "2)  There was an error converting %s to %s" % (unit1, unit2)
The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.