凯撒密码与大写字母

问题描述 投票:0回答:1

因此,每当我使用小写字母时,我的Caesar密码程序运行良好。但是当我用大写输入单词或短语时,我希望它能够工作。这是我现在的代码。希望你们都能帮我完成这个。

user defined functions

def encrypt(消息,距离):“”“将获取消息并将其旋转距离,以便创建加密消息”“”

encryption = ""
for ch in message:
    ordvalue = ord(ch)
    cipherValue = ordvalue + distance
    if cipherValue > ord("z"):
        cipherValue = ord("a") + distance - (ord("z") - ordvalue + 1)
    encryption += chr(cipherValue)
return encryption

def decrypt(消息,距离):“”“将解密上述消息”“”

decryption = ""
for cc in message:
    ordvalue = ord(cc)
    decryptValue = ordvalue - distance
    if decryptValue < ord("a"):
        decryptValue = ord("z") - distance - (ord("a") - ordvalue - 1)
    decryption += chr(decryptValue)
return decryption

def binaryConversion(message):“”“将单词转换为二进制代码”“”

binary = ""
for cb in message:
    binaryString = " " #Binary number
    binaryNumber = ord(cb)
    while binaryNumber > 0:
        binaryRemainder = binaryNumber % 2
        binaryNumber = binaryNumber // 2
        binaryString = str(binaryRemainder) + binaryString
    binary += binaryString
return binary

while loop

run = True

跑步时:

#input 

message = input("Enter word to be encrypted: ") #original message
distance = int(input("Enter the distance value: ")) #distance letters will be moved

#variables

fancy = encrypt(message, distance)
boring = decrypt(fancy, distance)
numbers = binaryConversion(message)

#output
print("\n")
print("Your word was: ", format(message, ">20s"))
print("The distance you rotated was: ", format(distance), "\n")
print("The encryption is: ", format(fancy, ">16s"))
print("The decryption is: ", format(boring, ">16s"))
print("The binary code is: ", format(numbers)) #I know an error comes here but it will work in the end

repeat = input("Would you like to encrypt again? Y/N ")
print("\n")
if repeat == "N" or repeat == "n":
    run = False
else:
    run = True

Finale

打印(“谢谢你和Julius Caesar曾经说过'Veni,vidi,vici'”)

谢谢

python caesar-cipher
1个回答
1
投票

我建议你在映射的思维模式而不是偏移量中解决这个问题。您可以基于偏移量构建映射,但如果使用字典或其他形式的一对一映射,则字符处理将更容易。

例如:

  offset = 5
  source = "abcdefghijklmnopqrstuvwxyz"
  target = source[offset:]+source[:offset]
  source = source + source.upper()
  target = target + target.upper()
  encrypt = str.maketrans(source,target)
  decrypt = str.maketrans(target,source)

  e = "The quick brown Fox jumped over the lazy Dogs".translate(encrypt)
  print(e)
  d = e.translate(decrypt)
  print(d)
© www.soinside.com 2019 - 2024. All rights reserved.