我有这个代码是一个基本的凯撒密码,偏移量设置为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)
答案 0 :(得分:1)
这可能是因为您没有将输入转换为整数,实际上用字符串填充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)
将产生:
Enter sentance: hello world!
Enter offset: 13
Your encrypted message is: uryyb jbeyq!