因此,正如标题所示,我正在尝试做一个待办事项列表CLI应用程序,并且遇到了该错误。 (NameError: name 'loaded_uinput' is not defined
)
当我将load_uinput设置为全局变量时,它会给我该错误,但是如果我不这样做,则会给我一个错误:UnboundLocalError: local variable 'loaded_uinput' referenced before assignment
我一直在努力研究整天,以寻找我做错了什么,但是除了写得不好的代码(目前,我打算很快将其重构)之外,我找不到它:/
userlist = []
filename = "userdata.p"
def maininput():
while True:
#Selecting if user wants to read or write the list, and or exit
init_conf = input("Would you like to read or write your list? (read | write | exit)")
#Printing the list
if init_conf == "read":
pickle_in = open(filename, "rb")
loaded_uinput = pickle.load(pickle_in, encoding='bytes')
pickle_in.close()
print(*loaded_uinput, sep="\n")
#Customizing the list
elif init_conf == "write":
uinput = input("What would you like to add to your list?")
userlist.append("-" + uinput)
pickle_out = open(filename, "ab")
pickle.dump(userlist, pickle_out)
pickle_out.close()
print(*loaded_uinput, sep="\n")
elif init_conf == "exit":
break
maininput()
我只想让它运行时没有错误哈哈,甚至不理解它是如何定义的:
我想写一些东西并将其存储在userdata.p
谢谢!
答案 0 :(得分:1)
您只需要在循环之前定义变量。它仅在“ if”块范围内创建,而不是在尝试访问它的“ elif”块时创建。您可以根据需要将其设置为空列表。
userlist = []
filename = "userdata.p"
def maininput():
loaded_uinput = []
while True:
#Selecting if user wants to read or write the list, and or exit
init_conf = input("Would you like to read or write your list? (read | write | exit)")
#Printing the list
if init_conf == "read":
pickle_in = open(filename, "rb")
loaded_uinput = pickle.load(pickle_in, encoding='bytes')
pickle_in.close()
print(*loaded_uinput, sep="\n")
#Customizing the list
elif init_conf == "write":
uinput = input("What would you like to add to your list?")
userlist.append("-" + uinput)
pickle_out = open(filename, "ab")
pickle.dump(userlist, pickle_out)
pickle_out.close()
print(*loaded_uinput, sep="\n")
elif init_conf == "exit":
break
maininput()
答案 1 :(得分:1)
请勿将loaded_uinput
定义为函数外部的全局变量。如果在定义之前尝试使用UnboundLocalError
,则会出现loaded_uinput
,如果在while循环的第一个迭代中init_conf == "write"
是True
时可能会发生。也就是说,如果您第一次键入"write"
,则在尝试将其用于打印输出时将不会定义loaded_uinput
。
答案 2 :(得分:1)
发生错误是因为您在尝试向loaded_uinput
变量分配任何值之前对其进行了访问。
当循环首次运行并输入'write'命令时,循环获取将输入的数据获取到uinput
并将其保存到文件,但尝试打印print(*loaded_uinput, sep="\n")
而不是尚未分配。它应该更改为:
print(*uinput)
open(filename, "ab")
已更改为替换文件的内容,而不是附加到文件。
open(filename, "wb")
检查此工作代码:
import pickle
userlist = []
filename = "userdata.p"
def maininput():
while True:
#Selecting if user wants to read or write the list, and or exit
init_conf = input("Would you like to read or write your list? (read | write | exit)")
#Printing the list
if init_conf == "read":
pickle_in = open(filename, "rb")
loaded_uinput = pickle.load(pickle_in)
pickle_in.close()
print(*loaded_uinput, sep="\n")
#Customizing the list
elif init_conf == "write":
uinput = input("What would you like to add to your list?")
userlist.append("-" + uinput)
pickle_out = open(filename, "wb")
pickle.dump(userlist, pickle_out)
pickle_out.close()
print(*uinput)
elif init_conf == "exit":
break
maininput()