Simple Python Temperature Converter

xponent picture xponent · Sep 25, 2015 · Viewed 8.4k times · Source

I'm fairly new to programming, and have decided to start with Python as my entry into it. Anyway, I can't seem to figure out why this temperature conversion script I wrote isn't running.

def convert_to_fahrenheit(celsius):

    c = celsius
    f = c * 9 / 5 + 32
    print '%r Celsius, converted to Fahrenheit, is: %r Fahrenheit.' % c, f


def convert_to_celsius(fahrenheit):

    f = fahrenheit
    c = (f - 32) * 5 / 9
    print '%r Fahrenheit, converted to Celsius, is: %r Celsius.' % f, c


def convert():

    print 'To convert a temperature from Celsius to Fahrenheit:'
    cels = raw_input('CELSIUS: ')
    print ''
    convert_to_fahrenheit(cels)

    print ''
    print 'To convert a temperature from Fahrenheit to Celsius:'
    fahr = raw_input('FAHRENHEIT: ')
    convert_to_celsius(fahr)


convert()

It returns a TypeError:

Traceback (most recent call last):
  File "C:/Users/Brandon/PycharmProjects/IntroTo/Ch1/Exercises.py", line 32,     in <module>
    convert()
  File "C:/Users/Brandon/PycharmProjects/IntroTo/Ch1/Exercises.py", line 24,     in convert
    convert_to_fahrenheit(cels)
  File "C:/Users/Brandon/PycharmProjects/IntroTo/Ch1/Exercises.py", line 8,      in convert_to_fahrenheit
    f = c * 9 / 5 + 32
TypeError: unsupported operand type(s) for /: 'str' and 'int'

Answer

Ilya Peterov picture Ilya Peterov · Sep 25, 2015

One problem is that you pass and string to the first two functions, but expect it to be a float. You can solve it by converting the value you get from string to float. You should do that

c = float(celcius)

in the first function, and

f = float(farenheit)

in the second one.


Another prblem is that you need to put parentheses around (c, f) and (f, c) for % to work properly.


And one more thing you probably want to do is to ask whether user wants to convert for cel to far or the other way around. You can do it using if:

def convert():

    user_input = raw_input('From what do you want to convert?: ')

    if user_input == 'celsius':
        print 'To convert a temperature from Celsius to Fahrenheit:'
        cels = raw_input('CELSIUS: ')
        convert_to_fahrenheit(cels)

    elif user_input == 'farenheit':
        print 'To convert a temperature from Fahrenheit to Celsius:'
        fahr = raw_input('FAHRENHEIT: ')
        convert_to_celsius(fahr)