我尝试了几个小时来制作一个简单的凯撒密码加密程序。它终于起作用了。但它只能加密没有空格和符号的文本。我不知道如何在代码中实现这些内容的检查部分。感谢那些让代码更干净、更干燥的批评者。谢谢。
我尝试实现该功能的代码:
#Taking Input String + converting to list
message = input("Enter the message for encrypting: ")
message_list = list(message)
#Taking Input Cipher
cipher = int(input("Enter shifting value (1-26): "))
#Alphabet
alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
#Defining variable
encrypted_message = []
#Shifting
for letter in message_list:
if letter not in alphabet:
encrypted_message.append(letter)
else:
#Getting Index of the letter in alphabet
letter_position = alphabet.index(letter)
#Getting the shifting value for the letter
shifting_value = letter_position + cipher
#Getting the shifted letter
shifted_letter = alphabet[shifting_value]
#Adding the corresponding letter to the encrypted message
encrypted_message.append(shifted_letter)
#Output
print("Original Message: " + message)
print("Encrypted Message: " + str(encrypted_message))
print("Cipher: " + str(cipher))
它应该做什么: 使用空格和符号加密消息(ceasar 密码),
它在做什么: 发生异常:IndexError 列表索引超出范围
最佳答案
IndexError list index out of range
由于您忘记了模数而发生错误。没有模数,
shifting_value = letter_position + cipher
该行的值将高于您正在索引的数组。请记住,凯撒密码是
c = p + 3 mod 26
所以该行必须是
移位值 = (字母位置 + 密码) % 26
注 1:cipher 在这里不是一个好的变量名。应该是shiftAmount。
注2:如果要将列表组合成字符串,请使用
str1 = ''.join(encrypted_message)
关于python - 检查符号和大写/小写以使用凯撒密码进行加密?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57581474/