Ricky
Ricky

Reputation: 791

Unit conversion using 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?

Upvotes: 3

Views: 27148

Answers (4)

Martin Thoma
Martin Thoma

Reputation: 136665

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

Upvotes: 6

Ones
Ones

Reputation: 7

centimeters = int(input("Enter your height in CM "))
meters = centimeters / 100
print ("You are %r meters long" % (meters))

This asks user to enter height in cm, remember 1m is equal to 100cm. So, we divide 180 by 100 to get the meters for example, if user enters 180 cm 1.8 meters will be printed.

Upvotes: 0

ha9u63a7
ha9u63a7

Reputation: 6854

You can use input() method (wrapped in float() method to convert data to integer

m_inch = float(input("Enter the amount in inches: ")) # will collection user data in inches

m_cm = m_inch*2.54 # converts from inches to cm

# rest of your code

N.B. I have used float type for input, but you could use int() to wrap as well....Does this help?

Upvotes: 4

Malik Brahimi
Malik Brahimi

Reputation: 16711

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] 

Upvotes: 4

Related Questions