 Ricky - 4 years ago 191
Python Question

# 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? Malik Brahimi
Answer Source

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]
``````
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download