UnboundLocalError:赋值前引用的局部变量'key'

时间:2016-02-12 14:08:37

标签: python file encryption

我正在尝试导入文本文件并通过两个关键字加密/解密。我设置了一个关键变量,但无法找到正确的位置来定位它。

目前的情况如下:

def importFile():
     importText = []
     file = input('What is the text file name: ')
     fileName = open(file,'r')
     text = fileName.read()
     fileName.close()
     fileName = text
     message = text
     #print (text)
     delete = open(file,'w')
     delete.write('')
     key = input ('What key do you wnat to use: ')

以下是调用key的地方:

def translatedMessage(mode):
    translated = []
    keyIndex = 0
    key = key.upper()

    for symbol in message: 
        num =LETTERS .find(symbol.upper())
        if num != -1: 
            if mode == 'encrypt':
                num += LETTERS .find(key[keyIndex]) 
            elif mode == 'decrypt':
                num -= LETTERS .find(key[keyIndex])

            num %= len(LETTERS)

            if symbol.isupper():
                translated.append(LETTERS[num])
            elif symbol.islower():
                translated.append(LETTERS[num].lower())

            keyIndex += 1 
            if keyIndex == len(key):
                keyIndex = 0
        else:
            translated.append(symbol)
    return ''.join(translated)
if __name__ == '__main__':
    main()

如果您需要,请将它们放在一起:

LETTERS = 'ZABCDEFGHIJKLMNOPQRSTUVWXY'
def main():
    myMode = input("Encrypt 'e' or Decrypt 'd': ")
    if myMode == 'encrypt' or myMode == 'e':
        translated = encryptFile()
    elif myMode == 'decrypt' or myMode == 'd':
        translated = decryptFile()

def importFile():
     importText = []
     file = input('What is the text file name: ')
     fileName = open(file,'r')
     text = fileName.read()
     fileName.close()
     fileName = text
     message = text
     #print (text)
     delete = open(file,'w')
     delete.write('')
     key = input ('What key do you wnat to use: ')

def encryptFile():
    textFile = input("Would you like to import a text file 'Y' or 'N': ")
    if textFile.lower() == 'y' :
        importFile()

    return translatedMessage('encrypt')

def decryptFile():
    textFile = input("Would you like to import a text file 'Y' or 'N': ")
    if textFile.lower() == 'y' :
        importFile()

    return translatedMessage('decrypt')

def translatedMessage(mode):
    translated = []
    keyIndex = 0
    key = key.upper()

    for symbol in message: 
        num =LETTERS .find(symbol.upper())
        if num != -1: 
            if mode == 'encrypt':
                num += LETTERS .find(key[keyIndex]) 
            elif mode == 'decrypt':
                num -= LETTERS .find(key[keyIndex])

            num %= len(LETTERS)

            if symbol.isupper():
                translated.append(LETTERS[num])
            elif symbol.islower():
                translated.append(LETTERS[num].lower())

            keyIndex += 1 
            if keyIndex == len(key):
                keyIndex = 0
        else:
            translated.append(symbol)
    return ''.join(translated)
if __name__ == '__main__':
    main()

我对编码很新,并且知道这非常简单,所以非常感谢任何建议:)

1 个答案:

答案 0 :(得分:2)

您的代码中的问题是您将key视为全局变量,但它是本地变量,因此您需要在函数之间传递它:

LETTERS = 'ZABCDEFGHIJKLMNOPQRSTUVWXY'
def main():
    myMode = input("Encrypt 'e' or Decrypt 'd': ")
    if myMode == 'encrypt' or myMode == 'e':
        translated = encryptFile()
    elif myMode == 'decrypt' or myMode == 'd':
        translated = decryptFile()

def importFile():
     importText = []
     file = input('What is the text file name: ')
     fileName = open(file,'r')
     text = fileName.read()
     fileName.close()
     fileName = text
     message = text
     #print (text)
     delete = open(file,'w')
     delete.write('')
     return input ('What key do you wnat to use: ')  # Return the key

def encryptFile():
    textFile = input("Would you like to import a text file 'Y' or 'N': ")
    if textFile.lower() == 'y' :
        key = importFile()  # Get the key returned by the function

    return translatedMessage('encrypt', key)  # Pass the key to the function

def decryptFile():
    textFile = input("Would you like to import a text file 'Y' or 'N': ")
    if textFile.lower() == 'y' :
        key = importFile()  # Get the key returned by the function

    return translatedMessage('decrypt', key)  # Pass the key to the function

def translatedMessage(mode, key):  # `key` is an argument
    translated = []
    keyIndex = 0
    key = key.upper()

    for symbol in message: 
        num =LETTERS .find(symbol.upper())
        if num != -1: 
            if mode == 'encrypt':
                num += LETTERS .find(key[keyIndex]) 
            elif mode == 'decrypt':
                num -= LETTERS .find(key[keyIndex])

            num %= len(LETTERS)

            if symbol.isupper():
                translated.append(LETTERS[num])
            elif symbol.islower():
                translated.append(LETTERS[num].lower())

            keyIndex += 1 
            if keyIndex == len(key):
                keyIndex = 0
        else:
            translated.append(symbol)
    return ''.join(translated)
if __name__ == '__main__':
    main()

更简单的解决方案是通过将key行添加到global key函数,将importFile()定义为全局变量。但总的来说,我认为不鼓励在Python中使用global关键字。

Python中对全局变量和局部变量的这种解释可能会有所帮助:http://www.python-course.eu/global_vs_local_variables.php