2

I'm new to Python and thought I'd try to make a Caesar cipher and could use some help with my code. It looks like this:

def cipher(input): input = input.lower() #don't mind capital letters output = [] alphabet = 'abcdefghijklmnopqrstuvwxyz' steps = int(raw_input('How many steps? >> ')) for i in input: if i == ' ': #for space output.append(' ') else: pos = alphabet.index(i) + steps if pos >= 25: #for out-of-range pos -= 26 output.append(alphabet[pos]) print 'The ciphered message: ', ''.join(output) input = raw_input('Write your message. >> ') cipher(input) 

It seems to work a bit, but not fully, when it comes to spaces.

This is what I get:

Write your message. >> abc abc How many steps? >> 1 The ciphered message: bcd dbcd 

I don't quite understand where the extra letter (d, in this case) in the output comes from.

Thankful for any help.

1
  • 1
    You don't need to write 'abc[...]xyz'. Just use string.ascii_lowercase. Commented Jul 14, 2014 at 10:16

3 Answers 3

4

Your indentation is incorrect:

for i in input: if i == ' ': #for space output.append(' ') else: pos = alphabet.index(i) + steps if pos >= 25: #for out-of-range pos -= 26 output.append(alphabet[pos]) # note here 

You append to the output whether or not i is a space. This would break completely if the first character was a space (NameError, as pos is not yet assigned), but just causes repeats elsewhere in the string.

Change to:

for i in input: if i == ' ': #for space output.append(' ') else: pos = alphabet.index(i) + steps if pos >= 25: #for out-of-range pos -= 26 output.append(alphabet[pos]) # now inside 'else' 

Note you can also simplify your out-of-range:

pos = (alphabet.index(i) + steps) % 26 
Sign up to request clarification or add additional context in comments.

2 Comments

@user3781209 if it solves your problem, please accept and +1 this answer.
@m.wasowki I tried, but I don't seem to be allowed to give upvotes.. My reputation is too low.
1

The statement

output.append(alphabet[pos]) 

should be inside the else block. In case of i == ' ', the output.append is run twice

Comments

0

Caesar Cipher in 2 lines, just for fun

rot3 = dict(zip(map(ord, 'abcdefghijklmnopqrstuvwxyz'), 'defghijklmnopqrstuvwxyzabc')) 'tiberivs clavdivs caesar'.translate(rot3) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.