Python try answer

what is the right answer for this exercise below?(https://www.freecodecamp.org/learn/scientific-computing-with-python/python-for-everybody/more-conditional-structures)

shouldn’t be only line 3? how come the answer is line 3 & 4? line 4 should be ok if line 3 is correct, as fahr would be a float.

Given the following code:

temp = “5 degrees”
cel = 0
fahr = float(temp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)

Which line/lines should be surrounded by try block?

Hello! Welcome to the community :grin:!

Yes, but what would happen if it isn’t OK? I suggest you to try it out :slightly_smiling_face:.

Answer (I really suggest you to try it out by yourself before)

The next line would be executed and another error would be thrown (fahr would not be defined):

temp = "5 degrees"
cel = 0

try:
    fahr = float(temp)
except:
    print('Failed to parse temp')
cel = (fahr - 32.0) * 5.0 / 9.0 # Here fahr would be undefined
print(cel)

I guess, that would depend what you put in the except: , technically, you can either quit, set fahr to some default float, or ask for new input.

1 Like

@dk.mix
You can try this code also. This is also a conditional structure. In this case you can enter any temperature for conversion. (F/C).

Write a Python program to convert temperatures to and from celsius, fahrenheit.
c = (5/9) * (F-32);
f = (9/5)*C (+32);

temp = input('Enter the temperature you wants to convert : ')
degree = float(temp[:-1])
i_convention = temp[-1]

if i_convention.upper() == 'C':
    result = float((9*degree)/5 + 32)
    o_convention = "Fahrenheit"
elif i_convention.upper() == "F":
    result = float((degree-32)*5/9)
    o_convention = "Celsius"
else:
    print('Enter the temperature with proper convention; F / C')
    quit()
print("The temperature in ", o_convention, "is", result, "degrees")
1 Like

@dk.mix

You can try this also .very simple. just replace the string with a float number.!

temp = 5 
cel = 0
fahr = float(temp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
1 Like