Python Forum

Full Version: Global Variable issue
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Here i have a fairly simple code where i tried to create a function that checks if the password entered by the user is valid.
def val():
    global valid
    try:
        hasBadLength, hasBadSymbols, hasSpaces=False, False, False
#These are the three variables that are the factors that determine if the
#password valid. Length, certain symbols and spaces.
        password = input('Enter a password: ')
        if len(password) < 8 or len(password) > 24:
            hasBadLength = True
#Code underneath checks for symbols that could be in password that are not
#permitted.
        for i in password:
            badSymbols = ['.', ']', ';', '@', '~', '[', ':', '>', '<']
            for e in badSymbols:
                if i == e:
                    hasBadSymbols = True

            if i.isspace() == True:
                hasSpaces = True
#Here underneath i use the states of the three main variables to determine what
#error messages will be printed and if the password is valid or not.
        passScale = 0
        if hasBadLength == False:
            passScale += 1
            
        if len(password) < 8:
            print('Password too short.')
            
        if len(password) > 24:
            print('Password too long.')

        if hasSpaces == False:
            passScale+=1
        else:
            print('Password contains spaces.')

        if hasBadSymbols==False:
            passScale+=1
        else:
            print('Password contains not allowed symbols.')
#If there is nothing wrong with the password, the global variable 'valid' is set
#to 'True'.
        if passScale==3:
            valid=True
    except:
        print('Error')
#MAIN
end=False
while end==False:
    val()
    if valid==True:
        print('Password is valid')
My issue is, whenever i input my password, half of the time this error message pops up:
Error:
Traceback (most recent call last): File "C:\Python34\MyPasswordValidationCode.py", line 45, in <module> if valid==True: NameError: name 'valid' is not defined
Judging from this error message, i think something is placed in the wrong location, why the code does not define my global variable half of the time.
Although, I cannot see how i could have possibly done anything incorrectly with this global variable, i cannot see anything wrong with it, help Pray

note: I changed all my variable names to make more sense and help understand what's going on in my code. That's why they are a little long **smile**
If you switch from using a global variable to a return value, the problem should become more clear.