rocknrollpartytime
rocknrollpartytime

Reputation: 53

Python - Caesar Cipher

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.

Upvotes: 2

Views: 1228

Answers (3)

V1A0
V1A0

Reputation: 41

Caesar Cipher in 2 lines, just for fun

rot3 = dict(zip(map(ord, 'abcdefghijklmnopqrstuvwxyz'), 'defghijklmnopqrstuvwxyzabc'))

'tiberivs clavdivs caesar'.translate(rot3)

Upvotes: 0

jonrsharpe
jonrsharpe

Reputation: 121966

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

Upvotes: 4

Ashoka Lella
Ashoka Lella

Reputation: 6729

The statement

output.append(alphabet[pos])

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

Upvotes: 1

Related Questions