如何在Python中输入Caesar密码的偏移量

2024-06-18 11:48:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个代码,这是一个基本的凯撒密码,偏移量设置为1,但我想要它,以便用户可以输入偏移量。用户应该能够说出字母表的移动量,但是如果offset=input,它就不起作用了

#Caesar cipher
sentance = input('Enter sentance: ')
alphabet = ('abcdefghijklmnopqrstuvwxyz')
offset = 1
cipher = ''

for c in sentance:
    if c in alphabet:
            cipher += alphabet[(alphabet.index(c)+offset)%(len(alphabet))]

print('Your encrypted message is: ' + cipher)

Tags: 代码用户in密码forinput字母表offset
1条回答
网友
1楼 · 发布于 2024-06-18 11:48:06

这可能是因为您没有将输入转换为整数,实际上是用字符串填充offset。在

使用int(input())将输入的字符串转换为整数(可选-还记得添加原始字符,以防它们不在字母表中):

sentance = input('Enter sentance: ')
offset = int(input('Enter offset: '))
alphabet = ('abcdefghijklmnopqrstuvwxyz')
cipher = ''

for c in sentance:
    if c in alphabet:
        cipher += alphabet[(alphabet.index(c) + offset) % (len(alphabet))]
    else:
        cipher += c

print('Your encrypted message is: ' + cipher)

将产生:

^{pr2}$

相关问题 更多 >