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.
CodePudding user response:
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
CodePudding user response:
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