Python - 凯撒密码

2 投票
3 回答
1183 浏览
提问于 2025-04-18 13:13

我刚开始学习Python,想尝试做一个凯撒密码的程序,但我的代码需要一些帮助。它看起来是这样的:

def cipher(input):
    input = input.lower()  #don't mind capital letters
    output = []
    alphabet = 'abcdefghijklmnopqrstuvwxyz'
    steps = int(raw_input('How many steps? >> '))

    for i in input:
        if i == ' ':  #for space
            output.append(' ')
        else:
            pos = alphabet.index(i) + steps
            if pos >= 25:  #for out-of-range
                pos -= 26

        output.append(alphabet[pos])

    print 'The ciphered message: ', ''.join(output)


input = raw_input('Write your message. >> ')
cipher(input)

这个程序在某些方面能工作,但在处理空格时似乎不太对劲。

这是我得到的结果:

Write your message. >> abc abc
How many steps? >> 1
The ciphered message:  bcd dbcd

我不太明白输出结果中多出来的字母(在这个例子中是d)是怎么来的。

非常感谢任何帮助。

3 个回答

0

凯撒密码用两行代码实现,纯属好玩

rot3 = dict(zip(map(ord, 'abcdefghijklmnopqrstuvwxyz'), 'defghijklmnopqrstuvwxyzabc'))

'tiberivs clavdivs caesar'.translate(rot3)
1

这段话的意思是:

output.append(alphabet[pos])
这行代码应该放在 else 这个部分里。如果 i == ' ' 这个条件成立的话,output.append 这个操作会被执行两次。

4

你的缩进不对:

for i in input:
    if i == ' ':  #for space
        output.append(' ')
    else:
        pos = alphabet.index(i) + steps
        if pos >= 25:  #for out-of-range
            pos -= 26

    output.append(alphabet[pos]) # note here

你在 output 中添加内容时,不管 i 是否是空格。如果第一个字符是空格的话,这样会完全出错(会出现 NameError,因为 pos 还没有被赋值),但在字符串的其他地方只会导致重复。

改成:

for i in input:
    if i == ' ':  #for space
        output.append(' ')
    else:
        pos = alphabet.index(i) + steps
        if pos >= 25:  #for out-of-range
            pos -= 26
        output.append(alphabet[pos]) # now inside 'else'

注意,你也可以简化你的 out-of-range 错误处理:

pos = (alphabet.index(i) + steps) % 26

撰写回答