Lalies
Lalies

Reputation: 31

Creating a function to convert Fahrenheit to Celsius

I'm new to python and have started learning about functions. I am having trouble with homework to create my function to convert Fahrenheit to Celsius. Please see my code below.

def convert_f_to_c(temp_in_fahrenheit):

    celsius = float(temp_in_fahrenheit - 32.00) * float(5.00 / 9.00)
    
    return round(celsius)
convert_f_to_c()

The arguments is that we have a float representing a temperature, that returns a float representing a temp in degrees Celsius, rounded to 1dp.

I receive one of these errors when I run the test

TypeError: unsupported operand type(s) for -: 'str' and 'float'

I have tried to create a function to convert Fahrenheit to Celsius and I keep getting errors. Unsure how to proceed with this question.

Upvotes: 2

Views: 2983

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 177564

Make sure to pass a float to your function, not a string, then you won't need to construct floats (incorrectly, as it happens) in your function. Your function should focus on the formula for conversion, not conversion of the parameters or rounding. Leave that to the input and printing.

def convert_f_to_c(temp_in_fahrenheit):
    return (temp_in_fahrenheit - 32) * 5 / 9

tempf = float(input('Fahrenheit? '))
tempc = convert_f_to_c(tempf)
print(f'{tempc:.1f} degC')

Output:

Fahrenheit? 70
21.1 degC

Upvotes: 1

StonedTensor
StonedTensor

Reputation: 616

It seems like temp_in_fahrenheit is a string when it should be a float. Just change how the float function is called.


#wrong
float(temp_in_fahrenheit - 32)

#better
float(temp_in_fahrenheit) - 32

Upvotes: 4

Related Questions