Untitled

mail@pastecode.io avatar
unknown
python
a year ago
2.3 kB
2
Indexable
Never
class Scale:
  CELSIUS = "CELSIUS"
  FAHRENHEIT = "FAHRENHEIT"
  KELVIN = "KELVIN"
  NONE = "NONE"
  Q = "Q"
  
class Temperature:

  def is_valid_scale_and_value(self, scale, value):
    if scale == Scale.CELSIUS:
        return value >= -273.15
    elif scale == Scale.FAHRENHEIT:
        return value >= -459.67
    elif scale == Scale.KELVIN:
        return value >= 0
    else:
        return False


  def __init__(self, value, scale=Scale.CELSIUS):
    if not self.is_valid_scale_and_value(scale, value):
      self.scale = Scale.NONE
      self.value = 0  

    else:
      self.scale = scale
      self.value = value
      

      
  def get_scale(self):
    return self.scale
      
  def get_value(self):
    return self.value
      
  def set_scale(self, scale):
    if scale not in [Scale.CELSIUS, Scale.FAHRENHEIT, Scale.KELVIN]:
        self.scale = Scale.NONE
    else:
        self.scale = scale
        if self.scale == Scale.CELSIUS:
            self.value = (self.value - 32) * 5 / 9
        elif self.scale == Scale.FAHRENHEIT:
            self.value = (self.value * 9 / 5) + 32
        elif self.scale == Scale.KELVIN:
            self.value = self.value + 273.15
      
  def set_value(self, value):
    if self.is_valid_scale_and_value(self.scale, value):
      self.value = value
    else:
      if self.scale == Scale.CELSIUS:
        self.value = -273.15
      elif self.scale == Scale.FAHRENHEIT:
        self.value = -459.67
      elif self.scale == Scale.KELVIN:
        self.value = 0    
        
  def set_scale_and_value(self, value, scale):
    if not self.is_valid_scale_and_value(scale, value):
      self.scale = Scale.NONE
      self.value = 0.0
    else:
      self.scale = scale
      self.value = value

  def __str__(self):
    if self.scale == Scale.NONE:
        return f"{self.value}N"
    else:
        return f"{self.value}{self.scale[0]}"


if __name__ == '__main__':
    t = Temperature(10.1)
    print(t.get_scale()) # displays "CELSIUS"
    print(t) # displays "10.1C"
    t.set_scale(Scale.FAHRENHEIT) # change scale
    print(t) # displays "50.18F" (notice it converted the value!)
    print(t.get_scale()) # displays "FAHRENHEIT"
    t = Temperature(12.25, "KELVIN") # scale input is not from Scale!
    print(t.get_scale()) # displays "NONE"
    print(t) # displays "0.0N"