Reputation: 1
I have this code which is a basic Caesar cipher, the offset is set to one but I want it so that the user can enter the offset. The user should be able to say by how much the alphabet is moved across by, but it won't work if 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)
Upvotes: 0
Views: 2068
Reputation: 16204
That is probably because you did not convert the input into an integer, and practically filled offset
with a string.
Use int(input())
to convert the inputted string as an integer (optional- also remember to add the original character in case they are not in the alphabet):
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)
Will produce:
Enter sentance: hello world!
Enter offset: 13
Your encrypted message is: uryyb jbeyq!
Upvotes: 1