Template request | Bug report | Generate Data Product
Tags: #python #convert #units #snippet #operations #length
Author: Benjamin Filly
Description: This notebook shows you how to convert length using Python.
References:
value
: starting unit valuefrom_unit
: is the unit of the starting value, the one you want to convertto_unit
: this is the unit we want to achieve with this script
value = 10
from_unit = 'km'
to_unit = 'm'
def convert_length(value, from_unit, to_unit):
units = {
'mm': 0.001,
'cm': 0.01,
'm': 1.0,
'km': 1000.0,
'in': 0.0254,
'ft': 0.3048,
'yd': 0.9144,
'mi': 1609.34,
'nm': 1e-9,
'μm': 1e-6,
'mil': 0.0254 / 1000,
'fm': 1e-15
# Add other length units here
}
if from_unit not in units or to_unit not in units:
raise ValueError("Invalid unit.")
return value * units[from_unit] / units[to_unit]
result = convert_length(value, from_unit, to_unit)
result