1.) a.) Write a Temperature class to represent Celsius and Fahrenheit temperatures. Your goal is to make this client code work:
The following output must be met with no errors:
>>> #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, returns a new Temperature object, does not change original
>>> t1.convert()
Temperature(32.0,'F')
>>> t4 = t1.convert()
>>> t4
Temperature(32.0,'F')
>>> t1
Temperature(0.0,'C')
>>> #__str__
>>> print(t1)
0.0°C
>>> print(t2)
100.0°F
>>> #==
>>> t1 == t2
False
>>> t4 == t1
True
>>> #raised errors
>>> Temperature('apple','c') #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ValueError: could not convert string to float: 'apple'
>>> Temperature(21.4,'t') #doctest: +IGNORE_EXCEPTION_DETAIL
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’
convert – convert does not actually change the current temperature object. It just returns a new Temperature object with units switched from ‘F’ to ‘C’ (or vice-versa).
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)