I am trying to create a temperature conversion module. My class is set up as below:
class Temperature: """A class to help work with temperature in various units""" def __init__(self, number, unit): # Convert and store units as self.celcius measure self.number = number self.unit = unit def __str__(self): return f"Temperature: {self.number}{self.unit}" def celcius(self): #convert to celcius if unit == 'C': self.celcius = number elif unit == 'F': self.celcius = (number - 32) * 5/9 elif unit == 'K': self.celcius = number - 273.15 else: raise Exception("Unit not recognised")# Unit not recognised def to(self, unit, dp=None):#convert self.celcius to temperature measure if unit == 'C': number = self.celcius() elif unit == 'F': number = (9/5 * self.celcius()) + 32 elif unit == 'K': number = self.celcius() + 273.15 else: raise Exception("Unit not recognised") if dp: number= round(number, dp) return f"{number}{unit}"
I then try to convert using the following:
from temperature import Temperature #assign temps temp_1 = Temperature(32,'C') temp_2 = Temperature(100, 'F') temp_3 = Temperature(324, 'K') print(temp_1) print(temp_2) print(temp_3) print(temp_1.to('F')) print(temp_2.to('K', 3)) print(temp_3.to('C', 1))
The original prints work but the conversion has the error: NameError: name ‘unit’ is not defined. How can I avoid this?
Advertisement
Answer
class Temperature: """A class to help work with temperature in various units""" def __init__(self, number, unit): # Convert and store units as self.celcius measure self.number = number self.unit = unit def __str__(self): return f"Temperature: {self.number}{self.unit}" def celcius(self): # convert to celcius if self.unit == 'C': return self.number elif self.unit == 'F': return (self.number - 32) * 5 / 9 elif self.unit == 'K': return self.number - 273.15 else: raise Exception("Unit not recognised") # Unit not recognised def to(self, unit, dp=None): # convert self.celcius to temperature measure if unit == 'C': self.number = self.celcius() elif unit == 'F': self.number = (9 / 5 * self.celcius()) + 32 elif unit == 'K': self.number = self.celcius() + 273.15 else: raise Exception("Unit not recognised") if dp: number = round(self.number, dp) return f"{self.number}{unit}" if __name__ == '__main__': # assign temps temp_1 = Temperature(32, 'C') temp_2 = Temperature(100, 'F') temp_3 = Temperature(324, 'K') print(temp_1) print(temp_2) print(temp_3) print(temp_1.to('F')) print(temp_2.to('K', 3)) print(temp_3.to('C', 1))