Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit conversion using Python

Tags:

python

I am going through Learn Python the Hard Way, On Ex-5 Study Drills, it states

Try to write some variables that convert inches and pounds to centimeters and kilos. Do not just type in the measurements. Work out the math in Python.

So far I have done this:

inches = 1
centimeters = 1
convert = centimeters * 2.54
print inches
print centimeters 
print "1 inch is %s centimeters." % convert

Now that will display the conversion of 1 inch, How would I be able to change it so that the user would input an amount in inches or centimeters, and it would correctly display the conversion?

And am I right in thinking that for it to successfully convert values, I would have to enter the values in manually or is there a way to do this already made in Python?

like image 778
Ricky Avatar asked Dec 09 '22 04:12

Ricky


2 Answers

There are libraries for handling units. pint is one for Python:

import pint

ureg = pint.UnitRegistry()
my_size = 1.74 * ureg.meter
print(my_size)  # 1.74 meter
print(my_size.to(ureg.inch))  # 68.503937007874 inch

The advantage is that the variables themselves have the information about which unit was used. This continues even if you divide:

import pint

ureg = pint.UnitRegistry()
distance = 40123 * ureg.meter
time = 1.2 * ureg.hour
speed = distance / time
print(speed)  # 33435.833333333336 meter / hour
print(speed.to(ureg.inch / ureg.hour))  # 1316371.3910761154 inch / hour
like image 115
Martin Thoma Avatar answered Dec 11 '22 11:12

Martin Thoma


You can use a dictionary to lookup for a specified unit:

amount, unit = input('Enter amount with units: ').split()[:2]
converted_data = int(amount) * {'in': 2.54, 'cm': 0.39}[unit] 
like image 31
Malik Brahimi Avatar answered Dec 11 '22 11:12

Malik Brahimi