Python - 凯撒密码 [英] Python - Caesar Cipher
问题描述
我是 Python 新手,我想尝试制作一个凯撒密码,并且可以对我的代码使用一些帮助.它看起来像这样:
I'm new to Python and thought I'd try to make a Caesar cipher and could use some help with my code. It looks like this:
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)
当涉及到空间时,它似乎有点作用,但并不完全.
It seems to work a bit, but not fully, when it comes to spaces.
这是我得到的:
Write your message. >> abc abc
How many steps? >> 1
The ciphered message: bcd dbcd
我不太明白输出中额外的字母(在本例中为 d)从何而来.
I don't quite understand where the extra letter (d, in this case) in the output comes from.
感谢您的帮助.
推荐答案
您的缩进不正确:
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
您append
到output
无论i
是否为空格.如果第一个字符是空格(NameError
,因为 pos
尚未分配),这将完全中断,但只会导致字符串中其他地方的重复.
You append
to the output
whether or not i
is a space. This would break completely if the first character was a space (NameError
, as pos
is not yet assigned), but just causes repeats elsewhere in the string.
更改为:
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
:
Note you can also simplify your out-of-range
:
pos = (alphabet.index(i) + steps) % 26
这篇关于Python - 凯撒密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!