UnboundLocalError:分配前已引用局部变量“键”

奥因·威廉姆斯(Owain Williams)

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

这是当前的位置:

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

我对编码非常陌生,并且知道这很简单,因此任何建议都将不胜感激:)

约翰逊

代码中的问题是您将其视为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 keyimportFile()函数将其定义为全局变量但是,总的来说,我认为global不建议在Python中使用该关键字。

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

简单函数问题,分配前已引用局部变量

在if语句后出现“ UnboundLocalError:分配前引用的局部变量”

Python 3:UnboundLocalError:分配前引用的局部变量

Python范围:“ UnboundLocalError:分配前已引用局部变量'c'”

分配前已引用局部变量“列表”

UnboundLocalError:分配前已引用局部变量“ cursor”

无局部变量,但警告:分配前已引用

UnboundLocalError:分配前已引用局部变量“ ticketCost”

Django:UnboundLocalError:分配前已引用局部变量“ company”

UnboundLocalError:分配前已引用局部变量“ classes_taken”

UnboundLocalError:分配前已引用局部变量“ batch_index”

UnboundLocalError:分配前已引用局部变量“ settingsText”

UnboundLocalError:分配前已引用局部变量“ response”

UnboundLocalError:分配前已引用局部变量“事件”(PYGAME)

UnboundLocalError:分配前已引用局部变量“ req”

分配前已引用错误局部变量

Python:当变量和类具有相同的名称时:UnboundLocalError:分配前已引用局部变量“ foo”

UnboundLocalError:分配前已引用局部变量“ mp”

UnboundLocalError:分配前已引用局部变量“ slcount”

UnboundLocalError:分配前已引用局部变量“ word_list”

UnboundLocalError:分配前已引用局部变量“分数”

UnboundLocalError:分配前已引用局部变量“ opTuple”

While循环:UnboundLocalError:分配前引用的局部变量

IF条件Python“分配前已引用局部变量'monthlyPayment'”

分配前已引用局部变量“ ...”

UnboundLocalError(赋值前引用的局部变量)

UnboundLocalError:分配前引用了局部变量“pin”

UnboundLocalError: 局部变量.... 赋值前引用

UnboundLocalError:分配前引用的局部变量“pop”