我一直在试用这个Ceasar Cipher,我收到一个我似乎无法绕过的错误。我目前正在使用python36,并想知道是否有任何人可以让我知道为什么会出现未绑定的本地错误。谢谢!
#Ceasar Cipher
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
MAX_KEY_SIZE = len(SYMBOLS)
def getMode():
while True:
print('Do you wish to ENCRYPT or DECRYPT a message?')
mode = input().lower()
if mode in ['encrypt', 'e', 'decrypt', 'd']:
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
def getMessage():
print('Enter your message:')
return input()
def getKey():
key = 0
while True:
print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
key = int(input())
if (key >= 1 and key <= MAX_KEY_SIZE):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
symbolIndex == SYMBOLS.find(symbol)
if symbolIndex == -1: # Symbol not found in SYMBOLS.
# Just add the symbol without any change.
translated += symbol
else:
# Encrypt or decrypt.
symbolIndex += key
if symbolIndex >= len(SYMBOLS):
symbolIndex -= len(SYMBOLS)
elif symbolIndex < 0:
symbolIndex += len(SYMBOLS)
translated += SYMBOLS[symbolIndex]
return translated
mode = getMode()
message = getMessage()
key = getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
更新 我收到的错误如下:
追踪(最近一次通话): 文件&#34; C:\ Users \ Badger \ Desktop \ DEV \ Scripts \ Ceasar_Cipher.py&#34;,第52行,in print(getTranslatedMessage(mode,message,key)) getTranslatedMessage中的文件&#34; C:\ Users \ Badger \ Desktop \ DEV \ Scripts \ Ceasar_Cipher.py&#34;,第32行 symbolIndex == SYMBOLS.find(symbol) UnboundLocalError:局部变量&#39; symbolIndex&#39;在分配前引用
答案 0 :(得分:0)
Caesar Cipher的密钥将是1到26之间的数字。 你的len(SYMBOLS)大于26。 本代码使用python3
为我工作MAX_KEY_SIZE = 26
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = raw_input().lower()
if mode in 'encrypt e decrypt d'.split():
return mode
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
def getMessage():
print('Enter your message:')
return raw_input()
def getKey():
key = 0
while True:
print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
key = int(input())
if (key >= 1 and key <= MAX_KEY_SIZE):
return key
def getTranslatedMessage(mode, message, key):
if mode[0] == 'd':
key = -key
translated = ''
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26
elif num < ord('A'):
num += 26
elif symbol.islower():
if num > ord('z'):
num -= 26
elif num < ord('a'):
num += 26
translated += chr(num)
else:
translated += symbol
return translated
mode = getMode()
message = getMessage()
key = getKey()
print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))
答案 1 :(得分:0)
我发现了什么问题......
我在分配时将symbolIndex设置为“==”。
将其改为“=”之后,一切都很美妙!