2

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)
2
  • 2
    your createKey function returns the key, but decrypt() doesn't capture that return value, e.g. key = createKey(alphaList). Commented May 30, 2013 at 19:04
  • @MarcB Sounds like an answer to me. Commented May 30, 2013 at 19:19

1 Answer 1

3

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:

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks. But why do I need to assign key? Shouldn't the original function return key when called?
@uncleGe You might want to read up on name scopes (I'll edit and add a link to my answer). Although it IS returning key, key is local to that function. You could create a global, but that's frowned upon.
Ok, I got it now, and I check out the scopes link. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.