2

如果将变量“key”返回到解密函数中,为什么无法识别?错误显示“NameError:未定义全局名称'key'”这是代码:

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)
4

1 回答 1

3

你永远不会分配key

createKey(alphaList)

将其更改为:

key = createKey(alphaList)

发生这种情况是因为keyincreateKey(alphaList)是名称范围的一部分createKey。尽管您将其返回,但您不会将其创建为名称范围的一部分decrypt

或者,您可以使用全局变量,但我不建议这样做,特别是因为通过分配keyin可以轻松解决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

参考:

于 2013-05-30T19:05:51.353 回答