2016-09-18 142 views
0

我有这个代码,它是一个基本的凯撒密码,偏移量设置为1,但我希望它可以让用户输入偏移量。用户应该能够通过字母多少在由感动地说,但它不会工作,如果偏移=输入如何在Python中输入凯撒密码的偏移量

#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) 

回答

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!