为什么我的python代码不加密或解密我的消息

时间:2015-05-29 13:05:38

标签: python encryption caesar-cipher

由于某种原因,当我在最后运行代码时,它只显示消息而不加密或解密它我真的很困惑请不要讨厌我,如果这是非常明显的我对python很新,几乎不知道基础知识< / p>

#declare variables
NewWord =""
NewLetter = ""
SecretMessage = 0

mode = input("Please enter a mode: ").lower()  #makes it lowercase
message = input("Please enter a message: ").lower() # lowercase to tackle capitals
while True:
    try:
        offset = int(input("Please enter a number: ")) #If no exception occurs, the except clause is skipped and execution of the try statement is finished.
        break
    except ValueError: #If exception occurs, the except clause continues printing not a valid number and letting you re-enter the offset and not just throwing up an error.
        print ("Not a valid number")
#print(mode, message, offset) #Test to check user Input

for letter in message : 
    SecretMessage = ord(letter)
    if mode == "Encrypt" :
        SecretMessage += offset # add the offset to the letter
    if mode == "Decrypt" :
         SecretMessage -= offset # subtract the offset to the letter
    if SecretMessage < 97:
       SecretMessage  += 26
    if SecretMessage > 122:
        SecretMessage -= 26
    NewLetter = SecretMessage 
    NewLetter = chr(NewLetter) 

   # print(newLetter)# check conversion
    NewWord += NewLetter

print(NewWord)

2 个答案:

答案 0 :(得分:0)

mode = input("Please enter a mode: ").lower()

使模式全部小写,以防止它等于&#34;加密&#34;或&#34; Decrypt&#34;。因此,您的if条款不会被执行。

答案 1 :(得分:0)

您正在小写mode变量,因此它无法等于EncryptDecrypt。您必须测试这些单词的小写版本:

if mode == "encrypt" :
    SecretMessage += offset # add the offset to the letter
if mode == "decrypt" :
     SecretMessage -= offset # subtract the offset to the letter