In this post, we will learn how to convert a millimeter value to inches in Python. We will write one function that will take the millimeter value as input from the user and it will print the converted inch value.
To convert millimeter to inch, you need to divide it by 25.4. So,
1 millimeter = 1/25.4 inch
x millimeter = (x/25.4) inch
where x is any value in millimeter.
Let’s write down the python program to convert millimeter to inch:
milli = float(input("Enter the millimeter value: ")) inch = milli/25.4 print("Inches: ", inch)
In this program,
- We are reading the user input value using input. input returns the value in string. We are converting it to float. This is the millimeter value.
- The inch is calculated by dividing the millimeter by 25.4.
- The last line is printing the inch value.
If you run this program, it will print output as like below:
Enter the millimeter value: 122 Inches: 4.803149606299213
We can round the result to a given number of digits after the decimal. Python provides one method called round, we can use that.
Let’s change the above program:
milli = float(input("Enter the millimeter value: ")) inch = round(milli/25.4, 2) print("Inches: ", inch)
It will give output as like below:
Enter the millimeter value: 122 Inches: 4.8 Enter the millimeter value: 133 Inches: 5.24
We can use a separate function to do the conversion. If you are using millimeter to inch conversion in many places, creating a separate function makes it easier. You can call it from any other place of any other files. If you make any mistake, you need to change at one place.
Below program uses a separate function to do the millimeter to inch conversion:
def milliToInch(num): return round(num/25.4, 2) milli = float(input("Enter the millimeter value: ")) print("Inches: ", milliToInch(milli))
If you run this program, it will print similar output.
- How to decrement a for loop in Python
- Split the root, extension of a path in Python using os.path.splitext
- Python program to replace all negative numbers with zero in a list
- Python program to check if a file exists
- Python program to check if a number is prime or not
- Python program to convert inches to millimeters