Question

If the variable 'key' is returned into the decrypt function, why is it not recognized? The error reads "NameError: global name 'key' is not defined" Here is the code:

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)
Was it helpful?

Solution

You never assign key:

createKey(alphaList)

Change this to:

key = createKey(alphaList)

This happens because key in createKey(alphaList) is part of the createKey namescope. Although you return it, you don't create that as part of the decrypt namescope.

Alternatively, you could use global variables, but I don't recommend this, especially because there is an easy get around by assigning key in 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

References:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top