简体   繁体   中英

UnboundLocalError inside python function replaced with NameError?

Basically I was receiving UnboundLocalError: local variable 'pw_is_long' referenced before assignment and saw using the global keyword helps to get rid of this inside a function. After using it, I am getting NameError: name 'pw_is_long' is not defined

I'm working in selenium and the instagram website. This code worked before I put it inside the function.

My first function:

password = input("Password\n")  
def pw_minimum_length(pw):
        if len(pw) > 5:
            return(True)
        else:
            return(False)
        
pw_is_long = pw_minimum_length(password)

My second and main function:

def login(username, password):
    #some if-else code
    #selenium element selecting & clicking
    #the following is the heirarchy inside the function where I am having this issue
    while (condition):
        if (condition):
            password = input("Password\n")
            global pw_is_long #when this line was not here, I was getting UnboundLocalError
            pw_is_long = pw_minimum_length(password)
        while not(pw_is_long): #line throwing NameError
            print("Password length must be at least 6 characters")
            password = input("Password\n")
            pw_is_long = pw_minimum_length(password)
        

Any answers are helpful. Thanks in advance.

If condition is False then it doesn't run if condition and it doesn't create variable pw_is_long =... but you need it in while not pw_is_long

I see two possibilities:

First: create pw_is_long at start with some default value - ie. None or Flase or 0

def login(username, password):

    pw_is_long = False

    while condition:
        if condition:
            password = input("Password\n")
            pw_is_long = pw_minimum_length(password)
            
        while not pw_is_long:
            print("Password length must be at least 6 characters")
            password = input("Password\n")
            pw_is_long = pw_minimum_length(password)
        

Second: maybe you should rather nested it and run while inside if

def login(username, password):

    while condition:
        if condition:
            password = input("Password\n")
            pw_is_long = pw_minimum_length(password)
            
            while not pw_is_long:
                print("Password length must be at least 6 characters")
                password = input("Password\n")
                pw_is_long = pw_minimum_length(password)
            

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM