Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

On Ex-5 Study drills of the book Learn Python the Hard Way, 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.

Till now, I have done this

inches = 1

centimeters = 1

convert = centimeters * 2.54

print inches

print centimeters 

print "1 inch is %s centimeters." % convert

Now the above code will just display the conversion of 1 inch and I don't know how to change it so that when the user gives input in centimeters or inches, and it should display the correct conversion?

Can anyone help me with my doubt?

1 Answer

0 votes
by (26.4k points)

For the described unit, you can also use a dictionary:

amount, unit = input('Enter amount with units: ').split()[:2]

converted_data = int(amount) * {'in': 2.54, 'cm': 0.39}[unit] 

Want to learn more about python? Come and join: python course

Related questions

0 votes
1 answer
asked Feb 7, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
asked Sep 25, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
...