PYTHON: Write a Temperature class to represent Celsius and Fahrenheit temperatur
ID: 3694743 • Letter: P
Question
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
Answer for Question:
This below python code is written based on given problem statement.
1. Created Temperature Class with convert and Constructor and __repr__ methods.
2. From Console Input read the different combinations of inputs and present the output.
3. This will do the both temperatures conversions vice versa and handled exception handled.
See the python code
class Temperature:
def __init__(self,temp=None,cf='C'):
if temp == None:
self.temp = float('0.0')
else:
try:
self.temp = float("{0:.2f}".format(temp))
except:
print('Your temperature must be a number!')
if cf not in ['c','C','f','F']:
print('You must identify the temperature as either F for Fahrenheit or C for Celsius!')
else:
self.cf = cf.upper()
def convert(self):
if self.cf == 'F':
return Temperature(float("{0:.2f}".format((self.temp - 32) * 5 / 9)), 'C')
elif self.cf == 'C':
return Temperature(float("{0:.2f}".format((9/5)*self.temp + 32)))
def __repr__(self):
return('Temperature({},{})'.format(self.temp,self.cf))
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.