Python program to convert inch to centimeter

Python program to convert inch to centimeter:

In this post, we will learn how to convert a value in inch to centimeter in Python. This program will take the inch value as input from the user, convert it to centimeter and print it out.

If you know the conversion formula, you can do any conversion programmatically. I will show you how to convert an inch value to centimeter and how to format the output result with Python.

How to convert Inch to centimeter:

This program will take the inch value as input from the user. 1 inch is equal to 2.54 centimeters. So, if we multiply the user input value by 2.54, it will convert this value to centimeter.

Method 1: Python program to convert inch to centimeter:

Let’s write down the Python program to do the conversion:

inch_value = int(input('Enter the value in inch: '))
cm_value = 2.54 * inch_value

print(f'{inch_value}″ = {cm_value}cm')

Download it on Github

Explanation:

In this program,

  • It asks the user to enter the inch value. The input() method reads the user input value and returns it as a string. We are using the int() method to convert it to an integer and it is assigned to the inch_value variable.
  • The value of inch_value is multiplied by 2.54 to calculate the centimeter value and it is assigned to the cm_value variable.
  • The last line is printing these values to the user.

Output:

If you run this program, it will print outputs as below:

Enter the value in inch: 30
10= 25.4cm

Enter the value in inch: 30
20= 50.8cm

Enter the value in inch: 30
30= 76.2cm

Method 2: By using a different function:

We can also write a different function to simplify the above program. If we write a separate function to do the conversion, we can call it from different places in the program and code duplication can be avoided.

Let me show you how to do that:

def inch_to_cm(inch):
    return inch * 2.54

if __name__ == "__main__":
    inch_value = int(input('Enter the value in inch: '))

    print(f'{inch_value}″ = {inch_to_cm(inch_value)}cm')

Download it on Github

It is similar to the previous example. The only difference is that we created a new method inch_to_cm to calculate the centimeter value for a given inch value. This method takes the inch value as its argument, calculates the centimeter value and returns that.

In the last print statement, we are calling the inch_to_cm function to calculate the cm value for the given inch value.

Python inch to cm

This program will give similar output as the above one.

You might also like: