I'm taking a free online Python tutorial, which wants me to:
Create a temperature converter which will convert Fahrenheit values to Celsius and vice-versa using the following two formulas which relate the temperature f in Fahrenheit to the temperature c in Celsius:
f = c * 9/5 + 32 c = (f -32)* 5/9
The input will be a string consisting of a floating-point number followed immediately by the letter
F
orC
, such as"13.2C"
. I need to convert to the other temperature scale and print the converted value in the same format. For example, if the input is "8F" then the output should be (approximately)"-13.333C"
, and if the input is"12.5C"
then the output should be"54.5F"
.
My answers are always slightly off. For example I get -16.444444444444446C
when the correct output is -16.394444444444442C
. Is there a problem with how I am using float? My code is as follows:
def celsiusCon(farenheit):
return (farenheit - 32)*(5/9)
def farenheitCon(celsius):
return ((celsius*(9/5)) + 32)
inputStr = input()
inputDig = float(inputStr[0:-2])
if inputStr[-1] == 'C':
celsius = inputDig
print(farenheitCon(celsius),'F',sep ='')
if inputStr[-1] == 'F':
farenheit = inputDig
print(celsiusCon(farenheit),'C', sep='')
You are cutting off the last two characters, not just the last one:
inputDig = float(inputStr[0:-2])
should be:
inputDig = float(inputStr[0:-1])
This accounts for your accuracy problem:
>>> celsiusCon(2.4)
-16.444444444444446
>>> celsiusCon(2.49)
-16.394444444444446
Since slicing counts from the end, slicing to :-2
cuts of both the unit and the last digit:
>>> '2.49F'[:-2]
'2.4'
>>> '2.49F'[:-1]
'2.49'