0

I'm just beginning with programming(python3), using the information available on Internet. Right now I'm learning how to use try/except. My problem is that the code I wrote runs fine in the command prompt of windows 10, but not in the shell(Atom/Hydrogen) where it throws an error(line 6, NameError) because I didn't defined the variable "fish", I know that usually happened the other way around but I just want to understand if I'm making a mistake. The code is as follows:

>try:
>>    fish = int (input("please enter your age "))
>except:
>>    print("That's not a number ")
>>    exit(0)
>if fish <= 15:
>>    parentLicense = input ("have one of your parents have a license? (yes/no) ")
>>    if parentLicense == "yes":
>>>        print ("You can fish")
>>    else:
>>>        print("So sad, you or one of your parents need a license")
Chiron
  • 3
  • 2

1 Answers1

0

Hi Chiron and welcome to the community. The reason you are getting an undefined error is because fish can be undifined under certain circumstances in the try statement. You should use

try:
    # try stuff
except ValueError:
    # do stuff when theres an error
else:
    # stuff if try stuff works

else is only called if no exception is raised. I would avoid using bare except too as it can cause issues and its not good practice.

David sherriff
  • 466
  • 1
  • 3
  • 9
  • Thanks for the answer and welcoming.Very useful the advice about the "except" without specifications, I didn't know it is not a good practice, I found it useful for an input statement, specially in order to avoid python's default error message. – Chiron Aug 04 '20 at 01:23
  • @Chiron you're welcome, if the answer helped solve the issue please accept it as the answer :) – David sherriff Aug 04 '20 at 06:10