凯撒密码 python 带字母输入

Caesar Cipher python with alphabet input

我是 python 的初学者,正在学习这方面的课程。我的任务是制作凯撒密码,我可以在其中输入使用的字母表。为此,我不能使用 ord()list() 或任何导入函数,只能使用基本的 python。我已经让它适用于一封信,但我似乎无法弄清楚如何让它适用于不止一封信。任何帮助将不胜感激!

def cypher(target, alphabet, shift):
    
    for index in range( len(alphabet)):
        if alphabet[index] == target:
           x = index + shift
           y =  x % len(alphabet)
                  
    return (alphabet[y])

我看到这是你的第一个问题。谢谢提问。

我认为您希望您的代码使用您在上面构建的函数来加密完整长度的脚本。所以,你的函数所做的是将一个字母作为 target 并移动它。

这可以通过遍历其元素轻松应用于 string

我已经为您的查询提供了正确的实现,并在此处进行了一些调整:

alphabet = "abcdefghijklmnopqrstuvwxyz"

def cypher(target, shift):
    for index in range(len(alphabet)):
        if alphabet[index] == target:
            x = index + shift
            y =  x % len(alphabet)
            return (alphabet[y])


string = "i am joe biden"
shift = 3 # Suppose we want to shift it for 3
encrypted_string = ''
for x in string:
    if x == ' ':
        encrypted_string += ' '
    else:
        encrypted_string += cypher(x, shift)

print(encrypted_string)

shift = -shift # Reverse the cypher
decrypted_string = ''
for x in encrypted_string:
    if x == ' ':
        decrypted_string += ' '
    else:
        decrypted_string += cypher(x, shift)

print(decrypted_string)

有很多方法可以完成这样的事情,但您可能需要一种形式

  • 获取输入值
  • 构建您的映射并将其存储(可能首先在字典中进行某种按值比较或直接作为 str.maketrans table
  • 看看它是否是您想要和期望的
  • 执行密码运算
  • 返回结果(在结果上方或下方的行中显示原始字符串有助于发现问题!)

这是一个非常无聊的凯撒密码的完整示例

source_string = input("source string: ").upper()
cut_position  = int(input("rotations: "))

# available as string.ascii_uppercase
source_values = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

# create a mapping
mapping = source_values[cut_position:] + source_values[:cut_position]

# display mapping
print("using mapping: {}".format(mapping))

# build a translation table
table = str.maketrans(source_values, mapping)

# use your translation table to rebuild the string
resulting_string = source_string.translate(table)

# display output
print(resulting_string)

提供映射和小写文本留作练习