# Area Unit Conversion (Python)

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.

1,054 Views

Scientist

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

#create an empty dictionary
# 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

def convertArea(x, unit1, unit2):
"""area conversion with error trapping"""
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)``````

Used in "wxPython ComboBox Demo" at:
http://www.daniweb.com/code/snippet410.html

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.