Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

using python!! Write a Temperature class to represent Celsius and Fahrenheit tem

ID: 3664850 • Letter: U

Question

using python!!

Write a Temperature class to represent Celsius and Fahrenheit temperatures. Your goal is to make this client code work:

>>> #constructors

>>> t1 = Temperature()

>>> t1

Temperature(0.0,'C')

>>> t2 = Temperature(100,'f')

>>> t2

Temperature(100.0,'F')

>>> t3 = Temperature('12.5','c')

>>> t3

Temperature(12.5,'C')

>>> #convert

>>> t1.convert()

Temperature(32.0,'F')

>>> t4 = t1.convert()

>>> t4

Temperature(32.0,'F')

>>> #__str__

>>> print(t1)

0.0°C

>>> print(t2)

100.0°F

>>> #==

>>> t1 == t2

False

>>> t4 == t1

True

>>> #raised errors

>>> Temperature('apple','c')

Traceback (most recent call last):

ValueError: could not convert string to float: 'apple'

>>> Temperature(21.4,'t')

Traceback (most recent call last):

UnitError: Unrecognized temperature unit 't'

Notes:

In addition to the usual __repr__, you should write the method __str__.   __str__ is similar to __repr__ in that it returns a str, but is used when a ‘pretty’ version is needed, for example for printing.

Unit should be set to ‘C’ or ‘F’ but ‘c’ and ‘f’ should also be accepted as inputs.

you must create an error class UnitError that subclasses Exception (it doesn’t have to anything additional to that). This error should be raised if the user attempts to set the temperature unit to something other than ‘c’,’f’,’C” or ‘F’

if the user tries to set the degree to something that is not understandable as a float, an exception should be raised (you can get this almost for free)

Explanation / Answer

class TemperatureErrorhere(Exception): pass class calculateTemperature(object): def __init__(self, temperature=None, scale='C'): self._celcius = None self._fahrenheit = None if temperature: if scale in ('c', 'C'): self.celcius = temperature elif scale in ('f', 'F'): self.fahrenheit = temperature else: raise TemperatureErrorhere @property def celcius(self): return self._celcius @celcius.setter def celcius(self, temperature): self._celcius = float('{0:.2f}'.format(temperature)) self._fahrenheit = float('{0:.2f}'.format((temperature - 32) * 5 / 9)) @property def fahrenheit(self): return self._fahrenheit @fahrenheit.setter def fahrenheit(self, temperature): self._celcius = float('{0:.2f}'.format(temperature * 9 / 5 + 32)) self._fahrenheit = float('{0:.2f}'.format(temperature)) OUTPUT: >>> t = calculateTemperature(20, 'F') >>> t.fahrenheit 20.0 >>> t.celcius 68.0