Hello I am new to Python and learning basics. I am curious to understand try/except statements in Python and I want to ask whether I should keep as little as possible in try block/portion as mentioned below (Please refer Following Code Working Properly) or try to keep as much in try block/portion (Please refer Following Code Not Working Properly When I Enter Any String but it works when I enter float/integer).
So, these are the two scenarios almost the same but the other code (in which I am keeping minimum code) is giving me an error when I enter a string.
Why is that doing it? What should I do in that case if I want to keep as little as possible in try/except blocks? Any leads would be highly appreciated. What's the alternate correct solution of my second code in which I am keeping minimum lines of code? - What adjustment I am supposed to make in it to work for me? Please help.
NameError: name 'fahr' is not defined
***# Following Code Working Properly:***
inp = input('Enter Fahrenheit Temperature:')
try:
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
except:
print('Please enter a number')
***# Following Code Not Working Properly:***
inp = input('Enter Fahrenheit Temperature:')
try:
fahr = float(inp)
except:
print('Please enter a number')
fahr = float(inp) # Even if I comment it, it doesn't make any difference when it comes to entering float in an input but it raises red flag if I enter string.
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)
fahr = float(inp)fails then it isn't going to suddenly work 3 lines later just because you printed'Please enter a number'in the meantime.fahr = float(inp)fails, the only thing your error handler does is print'Please enter a number'. Nowhere does your code give the user an opportunity to actually enter another number. I don't see why you would expect the very next line of code (which is the exact samefahr = float(inp)which triggered the error) to suddenly start working. You just printed something, but didn't actually do anything else.