Template request | Bug report | Generate Data Product
Tags: #python #convert #units #snippet #operations #temperature
Author: Benjamin Filly
Description: This notebook shows you how to convert units temperature 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 = 100
from_unit = 'C'
to_unit = 'F'
def convert_temperature(value, from_unit, to_unit):
units = {
'C': {
'C': lambda x: x,
'F': lambda x: x * 9 / 5 + 32,
'K': lambda x: x + 273.15
},
'F': {
'C': lambda x: (x - 32) * 5 / 9,
'F': lambda x: x,
'K': lambda x: (x + 459.67) * 5 / 9
},
'K': {
'C': lambda x: x - 273.15,
'F': lambda x: x * 9 / 5 - 459.67,
'K': lambda x: x
}
}
if from_unit not in units or to_unit not in units[from_unit]:
raise ValueError("Invalid unit.")
return units[from_unit][to_unit](value)
result = convert_temperature(value, from_unit, to_unit)
result