Let’s see how to handle unit conversion in Python. I’m taking cm to inch conversion as an example.
Cm to inch conversion
CM_IN_INCH = 2.54 def cm_in_inch(cm): return cm / CM_IN_INCH number_cm = float(input("How many cm do you want to convert to inch?")) print("Entered number of %s centimeters equals %s inches" % (number_cm, round(cm_in_inch(number_cm), 2)))
Conversion code explanation
First, I defined CM_IN_INCH constant which I will defienietly use later.
Next defined the simple method which is doing the calculations of cm to inch.
Then I am taking the input from the user.
And finally printing the result rounded to the two decimal places.
The result is as follows: