python-3.xcommand-prompttry-excepthydrogen

Code runs on command prompt but not on hydrogen


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

Solution

  • 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.