Python Program to Convert Inches to Centimeters
You can convert inches to centimeters in Python by multiplying the inches value by
2.54. For example, centimeters = inches * 2.54.Examples
Input0
Output0.0
Input10
Output25.4
Input15.5
Output39.37
How to Think About It
To convert inches to centimeters, understand that 1 inch equals 2.54 centimeters. So, multiply the number of inches by 2.54 to get the length in centimeters.
Algorithm
1
Get the input value in inches from the user.2
Multiply the inches value by 2.54 to convert it to centimeters.3
Display the result.Code
python
inches = float(input("Enter length in inches: ")) centimeters = inches * 2.54 print(f"{inches} inches is equal to {centimeters} centimeters.")
Output
Enter length in inches: 10
10.0 inches is equal to 25.4 centimeters.
Dry Run
Let's trace converting 10 inches to centimeters through the code
1
Input
User enters 10, so inches = 10.0
2
Calculation
centimeters = 10.0 * 2.54 = 25.4
3
Output
Prints '10.0 inches is equal to 25.4 centimeters.'
| inches | centimeters |
|---|---|
| 10.0 | 25.4 |
Why This Works
Step 1: Input Conversion
The input is converted to a float to allow decimal values for inches.
Step 2: Multiplication by 2.54
Multiplying by 2.54 converts inches to centimeters because 1 inch equals 2.54 cm.
Step 3: Output Formatting
The result is printed using an f-string for clear and readable output.
Alternative Approaches
Using a function
python
def inches_to_cm(inches): return inches * 2.54 value = float(input("Enter inches: ")) print(f"{value} inches = {inches_to_cm(value)} cm")
This approach makes the conversion reusable and organizes code better.
Using a constant variable
python
INCH_TO_CM = 2.54 inches = float(input("Inches: ")) cm = inches * INCH_TO_CM print(f"{inches} inches = {cm} cm")
Using a constant improves readability and makes it easy to update the conversion factor.
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a single multiplication and input/output operations, so it runs in constant time.
Space Complexity
Only a few variables are used, so the space used is constant.
Which Approach is Fastest?
All approaches run in constant time; using a function or constant variable mainly improves code clarity, not speed.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct calculation | O(1) | O(1) | Simple quick conversion |
| Function | O(1) | O(1) | Reusable code in larger programs |
| Constant variable | O(1) | O(1) | Readability and easy updates |
Always multiply inches by 2.54 to convert to centimeters accurately.
Forgetting to convert the input to a number before multiplying causes errors.