因此,我编写了一个程序,使用凯撒平移算法对消息进行加密。这是代码:
MAX_KEY_SIZE = 26
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = 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 input()
def getKey():
key = 0
while True:
print('Enter the value you want your message to be shifted by. You can choose anything from 1 to 26.')
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))
这是在Visual Studio Code中运行它会发生的事情:
“您是否希望加密或解密邮件?加密
输入您的消息:银
输入您要转移其消息的值。您可以选择1到26之间的任何值。3
您翻译的文本是:无“
问题在于,无论输入什么消息进行加密,我总是得到相同的答案:'none',而不是加密的消息。
有人对我该如何解决有任何想法吗?
我相信您的问题完全在您的缩进中,应该在您最初的if语句中包含某些部分,而不是。
使用python时,您必须非常小心缩进,因为没有括号可以控制条件。
MAX_KEY_SIZE = 26
def getMode():
while True:
print('Do you wish to encrypt or decrypt a message?')
mode = 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 input()
def getKey():
key = 0
while True:
print('Enter the value you want your message to be shifted by. You can choose anything from 1 to 26.')
key = int(input())
if (key >= 1 and key <= MAX_KEY_SIZE):
return key
def getTranslatedMessage(mode, message, key):
translated = ''
if mode[0] == 'd':
key = -key
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))