“UnboundLocalError: local variable 'input' referenced before assignment”
当我运行代码时,会收到以下错误:
1 2 | linechoice = input("What password do you want to delete?: ") |
UnboundLocalError: local variable 'input' referenced before assignment
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | def delete(): print("Welcome to the password delete system.") file = open("pypyth.txt","w") output = [] linechoice = input("What password do you want to delete?: ") 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? y/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? y/n ") if y_n =="y": file.close() print("Change saved.") input("Press enter to go back to menu") main() else: main() else: |
您正在为中的变量
1 2 3 | y_n = input = ("Do you want to save these changes? y/n ") |
y/n
'
但是,您也在调用内置函数
1 2 | linechoice = input("What password do you want to delete?: ") |
考虑更改变量的名称以避免这些冲突。
查看程序的上下文,您可能期望
1 2 3 | y_n = input("Do you want to save these changes? y/n ") |
而不是
1 2 3 | y_n = input = ("Do you want to save these changes? y/n ") |
如果由于调用input()而出现此错误:
UnboundLocalError: local variable 'input' referenced before assignment
如果假设运行时python解释器是2.x,那么应该检查它是否是3.x。
在python 3.6上执行时发生此错误:
1 2 3 | if hasattr(__builtins__, 'raw_input'): input = raw_input input() |
所以我去掉了这个,用了:
1 | from builtins import input |