How to convert cm to inch?

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 the CM_IN_INCH constant which I will definitely use later.

See also  What are the max and min values of integer in Python?

Next, I defined a simple function that performs the conversion from cm to inches.

Then, I take input from the user.

And finally printing the result rounded to the two decimal places.

The result is as follows:
cm to inch conversion