为什么我的Python代码会出现“未定义”错误?

时间:2013-05-30 19:01:49

标签: python nameerror

如果变量'key'返回到decrypt函数,为什么不能识别?错误读取“NameError:全局名称'键'未定义”以下是代码:

alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphaList = list(alphabet)
text = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj"

def createKey(aList):
    key = []
    count = 0
    for letter in aList:
        if count < 24:
            key.append(aList[count + 2])
        else:
            key.append(aList[count - 24])
        count += 1
    return key

def decrypt(text):
    createKey(alphaList)
    decryptedList = []
    textList = list(text)
    for c in textList:
        if c in alphaList:
            index = alphaList.index(c)       
            decryptedList.append(key[index])    
        else:
            decryptedList.append(c)
    decryptedText = "".join(decryptedList)
    return decryptedText

print decrypt(text)

1 个答案:

答案 0 :(得分:2)

您永远不会分配key

createKey(alphaList)

将其更改为:

key = createKey(alphaList)

这是因为key中的createKey(alphaList)createKey名称范围的一部分。虽然您将其返回,但您不会将其创建为decrypt名称范围的一部分。

或者,你可以使用全局变量,但我不建议这样做,特别是因为在key中分配decrypt()可以轻松解决这个问题:

alphabet = 'abcdefghijklmnopqrstuvwxyz'
alphaList = list(alphabet)
text = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj"
key = []

def createKey(aList):
    global key
    # everything else
    # no need to return, the `global key` has been changed

def decrypt(text):
    global key
    createKey(alphaList)
    # everything else

参考文献: