In this tutorial, we will understand how to do the conversion from cm to km in Python.
Basic understanding of the conversion
Before diving into the code, let’s understand the relationship between centimeters and kilometers. The metric system, which is widely used for scientific and everyday measurements, defines the following:
- 1 kilometer (km) is equal to 1,000 meters (m).
- 1 meter (m) is equal to 100 centimeters (cm).
From these definitions, we can derive that:
- 1 kilometer (km) = 1,000 meters (m) * 100 centimeters (cm) = 100,000 centimeters (cm).
Therefore, to convert centimeters to kilometers, you simply divide the number of centimeters by 100,000.
Converting Centimeters to Kilometers in Python
First, let’s write a Python function that converts centimeters to kilometers:
def cm_to_km(cm): km = cm / 100000 return km
Let’s break down the function:
- The function
cm_to_km
takes one argument,cm
, which represents the number of centimeters. - Inside the function, we perform the conversion by dividing the centimeter value by 100,000 and store the result in the variable
km
. - Finally, the function returns the calculated kilometers.
We’ll define a variable to hold the number of centimeters we want to convert.
For this example, let’s use 150,000 centimeters.
centimeters = 150000
Next, we’ll call the cm_to_km
function with the centimeters
variable as its argument. This function will perform the conversion and return the result in kilometers.
kilometers = cm_to_km(centimeters)
Here, the cm_to_km
function takes the value of centimeters
(which is 150,000) and divides it by 100,000. The result, which is 1.5, is then stored in the kilometers
variable.
Finally, we print out the result using a formatted string to clearly display the conversion.
print(f"{centimeters} cm is equal to {kilometers} km")
Below is the output you will get for our program.
150000 cm is equal to 1.5 km
Please find the complete code below,
def cm_to_km(cm): km = cm / 100000 return km # Example usage centimeters = 150000 kilometers = cm_to_km(centimeters) print(f"{centimeters} cm is equal to {kilometers} km")