3

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 or C, 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='')
AndyG
  • 39,700
  • 8
  • 109
  • 143
iaianmcd
  • 117
  • 1
  • 4
  • 13

3 Answers3

9

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'
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
0

notice your code is too long,instead of that:

tempInit = input()
temp = float(tempInit[:-1])
if tempInit[-1]== 'F':
    c=(temp-32)*5/9
    print(str(c)+'C')
if tempInit[-1]== 'C':
    f =(temp*9/5)+32
    print(str(f)+'F')
nima
  • 7,796
  • 12
  • 36
  • 53
-1

Here's a quick and dirty method.

temp = float(input("What's the temperature? C > F")))

conversion = (temp*9/5)+32

print(conversion)

This will convert from C > F, you can easily flip this around.

Neos Nokia
  • 125
  • 1
  • 2
  • 11