Skip to content

Latest commit

 

History

History
68 lines (48 loc) · 2.39 KB

Python_Convert_temperature.md

File metadata and controls

68 lines (48 loc) · 2.39 KB



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:

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 = 100
from_unit = 'C'
to_unit = 'F'

Model

Unit available

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)

Output

Display result

result = convert_temperature(value, from_unit, to_unit)
result