Why add "try/except" to 2 lines in this question?

In the python lesson titled: “# More Conditional Structures”, why do we need a try around lines 3 and 4? I ran the code and was able to get an answer quite easily with just a try and except around line 3 only. (below is the original code and my testing of it below that)

Given the following code:

``````01: temp = "5 degrees"
02: cel = 0
03: fahr = float(temp)
04: cel = (fahr - 32.0) * 5.0 / 9.0
04: print(cel)
``````

The question was: Which line/lines should be surrounded by `try` block?
The official answer is: lines 3/4

My test though shows we only need the try around 3

``````temp = "5 degrees"
cel = 0
try:
fahr=float(temp)
except:
fahr=5
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
``````

Thanks in advance for the clarification

Well that’s not the task though. The question was “what should go in the TRY block” not “write something in the EXCEPT block”.

You designed your EXCEPT block to avoid the error that was otherwise the reason to put both lines into the TRY block.
On top of that, you just made some random decisions. For a start you assign “5” without any prompt to do so, then you still calculate “cel” again, would waste computational power given you will get a constant result.

Both aren’t huge problems in this theoretical environment, but in real production, both decisions can cause huge problems. You created a new default value which might cause issues down the line. And you are running a pointless calculation which in more complex programs could end up quite expensive.

I’m not sure I understood your response.
Do you mean that the question’s intent is that only a try is added and nothing else? (I thought the whole point of using try was to catch and handle an exception? So in real life we don’t get weird results?)

Another way I could have written this is to try on the third line and then produce some sort of error return code. But I still don’t know why anyone would just want to use a try without an except (if that was the implied question).

Hoping for a clearer response.