2016-09-18 139 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!