Template request | Bug report | Generate Data Product
Tags: #python #convert #units #snippet #operations #weight
Author: Benjamin Filly
Description: This notebook shows you how to convert weight 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 = 500
from_unit = 'kg'
to_unit = 'lb'
def convert_weight(value, from_unit, to_unit):
units = {
'mg': 0.001,
'g': 1.0,
'kg': 1000.0,
'lb': 453.592,
'oz': 28.3495,
't': 1000000.0,
'st': 6350.29318,
'carat': 0.2,
'grain': 0.06479891
# Add other weight 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_weight(value, from_unit, to_unit)
result