1

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)
4
  • You have to read a little bit about scopes in python: w3schools.com/PYTHON/python_scope.asp Commented May 31, 2020 at 13:09
  • If 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. Commented May 31, 2020 at 13:10
  • @JohnColeman So, you want to say that fahr is not working because I have entered except statement i.e., 'Please enter a number'? Commented May 31, 2020 at 13:27
  • When 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 same fahr = float(inp) which triggered the error) to suddenly start working. You just printed something, but didn't actually do anything else. Commented May 31, 2020 at 13:34

4 Answers 4

5

Less in the try expression is preferable

It is preferable that the code you enter the try: block should only contains the bits that may directly produce the error in interest. This way, it would be easier to track its source and not to get distracted by any surrounding and presumably safe code.

In doing so, think about control flow

The first snippet of code runs correctly because when the error is raised in line 4, the control flow jumps directly to the except block, so any statements that depend on the fahr variable do not get affected. However, in the second snippet, if the error is raised and the control flow jumps to the except block, the fahr variable does not get defined, making the subsequent statements that depend on it raise the NameError error that you talk about. A safer method is to define an alternate, default fahr = 0 for example in the except block or to use an else: block, where the control flow jumps to if no errors are raised in the try: block.

Make your error handling specific

Always try and make the error you anticipate may be raised explicit in your code. this is by putting the base class of the group of errors after the except keyword and before the colon. For example,

except ValueError:
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you so much. I followed your advise and came up with the following code. Is that what are you trying to say? Please have a look at the following code: inp = input('Enter Fahrenheit Temperature:') try: fahr = float(inp) except ValueError: print('Please enter a number') else: fahr = float(inp) cel = (fahr - 32.0) * 5.0 / 9.0 print(cel)
And can you please tell me about the following which you mentioned in your post above: " A safer method is to define an alternate, default fahr = 0 for example in the except block" How would you actually do it practice like can you show me via code if you can?
You do not need to redefine fahr in the else: block, but yes, the rest is fine. You can see what I meant with a default case here
Thanks. I have a question. How can you do this in a function? Like def function?
Thanks. I have a question. How can you do this in a function? Like def function?
1

First, do not use a general catch clause. This would be considered bad practice.

In your case, it would make sense to catch ValueErrors in case a user enters letters instead of numbers in example:

while True:
    inp = input('Enter Fahrenheit Temperature:')
    try:
        fahr = float(inp)
        break # Break loop to get to main program
    except ValueError:
        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)

One alternative would be a recursive input if you really want to avoid the loop:

def force_input(prompt):
    inp = input(prompt)
    try:
        fahr = float(inp)
        return fahr
    except ValueError:
        print('Please enter a number')
        force_input(prompt)
        return False

fahr = force_input("Enter Fahrenheit Temperature:")
cel = (fahr - 32.0) * 5.0 / 9.0
print(cel)

13 Comments

Thank you so much so it can be performed with the help of while loop only? Can't I perform it without while loop? Would appreciate your help and why have you entered ValueError like I just checked there isn't any difference even if I enter this "ValueError" in except statement and don't enter. What's your take on?
If you want to force repeated input from the user you will need to use some form of loop The ValueError is thrown when there is a problem with the content of the object you tried to assign the value to. float() in example cannot parse alphabetic values but only numbers
@FionaDaniel I updated my answer to include a recursion instead of the loop - hope that helps
Thank you. I want to ask one thing in your second method (def function). Is it necessary to use return fahr under try block? Why have you written that? Because I tried the same solution provided by you without this line of code i.e., "return fahr" and it is working fine for me. So, can I just comment it? Your take-on?
Hm I would need to see the full code you use now (maybe use pastebin?) because the function definitely needs to return the value, otherwise, fahr will have no value.
|
0

Your first set of code is fine, but it doesn't recover from the error. If you'd like the program to gracefully recover and ask again for an input, you'll need to continually loop the input and try until it passes, like such.

while True:
    inp = input('Enter Fahrenheit Temperature:')
    try:
        fahr = float(inp)
        break
    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)

1 Comment

Thanks. I have a question. How can you do this in a function? Like def function?
0

Your problem is quite simple: try: except: is not a loop.

try:
    fahr = float(inp)
except:
    print('Please enter a number')

Here, you try to set fahr, and if you fail, you print 'Please enter a number' and your program continues.

But it failed to set fahr! So on the next line, when you try to use fahr to run calculation, it does not exist. Hence, NameError: name 'fahr' is not defined.

Why does this work:

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')

Here, you try to set fahr, you run your calculation, you print. But if any of these steps fail, you print your error and continue.

See the difference ? I hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.