Skip to content

Latest commit

 

History

History
66 lines (46 loc) · 2.22 KB

Python_Convert_length.md

File metadata and controls

66 lines (46 loc) · 2.22 KB



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:

Input

Setup Variables

Unit Available symbols

  • value: starting unit value
  • from_unit : is the unit of the starting value, the one you want to convert
  • to_unit: this is the unit we want to achieve with this script
value = 10
from_unit = 'km'
to_unit = 'm'

Model

Unit available

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]

Output

Display result

result = convert_length(value, from_unit, to_unit)
result