“UnboundLocalError: local variable 'input'

2019-01-26 23:15发布

When I run my code I get these errors:

linechoice = input("What password do you want to delete?:\n")

UnboundLocalError: local variable 'input' referenced before assignment

def delete():
    print("Welcome to the password delete system.")
    file = open("pypyth.txt", "w")
    output =  []
    linechoice = input("What password do you want to delete?:\n")
    if linechoice == "email":
        for line in file:
            if "Hotmail" != line.strip():
                output.append(line)
                print("Password " + linechoice + " deleted.")
                y_n = input = ("Do you want to save these changes?\ny/n\n")
                if y_n == "y":
                    file.close()
                    print("Change saved.")
                    input("Press enter to go back to menu")
                    main()
                else:
                    main()
    elif linechoice == "skype":
        for line in file:
            if "Skype" != line.strip():
                output.append(line)
                print("Password " + linechoice + " deleted.")
                y_n = input = ("Do you want to save these changes?\ny/n\n")
                if y_n == "y":
                    file.close()
                    print("Change saved.")
                    input("Press enter to go back to menu")
                    main()
                else:
                    main()
    else:

2条回答
贪生不怕死
2楼-- · 2019-01-26 23:53

You are assigning a string to the variable input in

y_n = input = ("Do you want to save these changes?\ny/n\n")

input now has the value of 'Do you want to save these changes?\ny/n\n'

However, you are also calling the built-in function input in

linechoice = input("What password do you want to delete?:\n")

Consider changing the name of your variable to avoid these conflicts.

Looking at the context of the program, you are probably expecting

y_n = input("Do you want to save these changes?\ny/n\n")

instead of

y_n = input = ("Do you want to save these changes?\ny/n\n")
查看更多
我欲成王,谁敢阻挡
3楼-- · 2019-01-26 23:53

If you got this error, due to calling input():

UnboundLocalError: local variable 'input' referenced before assignment

than you should check whether your runtime python interpreter is 3.x, if you were assuming it is 2.x.

This Error happened to me while executing on python 3.6:

if hasattr(__builtins__, 'raw_input'): 
    input = raw_input
input()

So I got rid of this, and instead used:

from builtins import input
查看更多
登录 后发表回答