未绑定的本地错误 - Python - 文件I / O - 字典

时间:2013-11-20 22:11:22

标签: python file-io dictionary

我已经成功创建了5种不同的功能。这些函数添加到字典中,查找字典的值及其键,从字典中删除值或键,将字典保存到文件中,最后将文件读回给我。现在我的目标是创建一个主要功能,允许用户使用我创建的这些功能添加,删除,查找或清除字典,直到用户决定要结束程序。我的所有功能都有效,但我对程序的所有功能都持续出现同样的错误。错误如下:UnboundLocalError: local variable 'diction' referenced before assignment。我将粘贴下面的代码。任何想法,建议或提示?

def primary():
    diction = {}
    readit()
    decision = raw_input('Which would you like to choose: add? find? remove? clear? or end?     ')
    if decision == 'add':
        key = raw_input('Which would you like to add?     ')
        value = raw_input('What would you like to link to your new addition?     ')
        addit(diction, key, value)
    elif decision == 'find':
        key = raw_input('What would you like to find?     ')
        findit(diction, key)
    elif decision == 'remove':
        key = raw_input('What would you like to have removed or edited?     ')
        value = raw_input('Which value would you like to remove?     ')
        removeit(diction, key, value)
    elif decision == 'clear':
        diction = []
    elif decision == 'end':
        saveDB()
    if decision == 'add' or 'find' or 'remove' or 'clear':
        primary()
    elif decision == 'end':
        exit

1 个答案:

答案 0 :(得分:0)

根据您的代码,在if语句之前没有定义diction。这意味着,虽然是的,你确实在你的一个elifs中定义了它,但在你的其他ifs中却不存在。

你需要在你的主要部分初始化diction,所以它在全局可用,或者在你的ifs和elif之前在primary()的顶部。