I am a beginner trying to learn python and came to a question where I have doubts in its answer. In scientific computing with python course, the python for everybody video course series, I came across a question in its 8th video, that is, More conditional structures. In the main question for going to the next series, I have a doubt.
Which line/lines should be surrounded by try block?
The answer is 3rd line and 4th line together but wouldnt that affect the program
if try block is in both 3rd line and 4th line wouldnt it stop executing the rest of the line if some error happens in the third line?
Please someone check and tell me the answer
That depends what exactly would be done in the except block. If only line 3 is in try/except then on line 4 can be another error, if fahr is not set.
temp = "5 degrees"
cel = 0
try:
fahr = float(temp)
except ValueError:
print(f'"{temp}" cannot be converted to float')
cel = (fahr - 32.0) * 5.0 / 9.0 # NameError: name 'fahr' is not defined
print(cel)
While wrapping both 3 and 4 lines will at least execute script to the end
temp = "5 degrees"
cel = 0
try:
fahr = float(temp)
cel = (fahr - 32.0) * 5.0 / 9.0
except ValueError:
print(f'"{temp}" cannot be converted to float')
print(cel) # cel is printed as 0
This is assuming the minimum is done when the exception is caught. In case of error when converting to float, fahr or cal could have been set manually to some specific value, in the except block.