Python Forum

Full Version: Referenced before assignment
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi All,

Im having an error where it says that the variable is being referenced before assignment. As seen below.

Error:
Incorrect Username, please try again Exception in Tkinter callback Traceback (most recent call last): File "D:\Work\School\ComputerScience\Python Files\lib\tkinter\__init__.py", line 1892, in __call__ return self.func(*args) File "D:\Work\School\ComputerScience\Code\Other\Tkinter Testing.py", line 40, in clicked if password == password_check: UnboundLocalError: local variable 'password_check' referenced before assignment
The code that is being run to create this issue is below.

def clicked():
        username=username_1.get()
        password=password_1.get()
            

        try:
            password_check = open("D:/Work/School/ComputerScience/Code/Other/TkinterTestingUserDetails/" + username + ".txt","r").read() #looking at what is in the file (the password)
        except:
            print ("Incorrect Username, please try again")
            username_1.delete(0, tk.END)
            password_1.delete(0, tk.END)

        if password == password_check:
            print ("Login Succesful")
            window_2.destroy()
            print ("Complete")
            #game()
        else:
            print("Login Unsuccesful, incorrect password, please try again")
            username_1.delete(0, tk.END)
            password_1.delete(0, tk.END)
            

    label_blank_2=tk.Label(text=" ")
    label_blank_2.grid(row=4)

    button=tk.Button(text="Click", fg="white", bg="blue", width=25, height=5, command=clicked)
    button.grid(row=5)

    window_2.mainloop()
If you could tell me what to fix that would be great!
Your error is on line 40, this script hasno line 40, are you importing this code to another python file? Basically when it gets to line 40 to validate the password is correct, it is saying it has no value for passeord_check.
Think about the flow of execution in that function: what happens if an exception bis thrown on line 7, so that execution enters the except block?
(Mar-02-2021, 07:46 PM)damian0612 Wrote: [ -> ]Your error is on line 40, this script hasno line 40, are you importing this code to another python file? Basically when it gets to line 40 to validate the password is correct, it is saying it has no value for passeord_check.

I have only sent a section of the code. Line 40 is where it says:

  if password == password_check: