Hi
I’m working with an old python exercise is to implement the caesar cipher, a simple encryption technique. Description of the methods can be found on the web (wikipedia) http://en.wikipedia.org/wiki/Caeser_cipher and the additional document.
In short, each letter is replaced by another letter (like a is replaced by b, b is replaced by c,. . . in case we are using a shift of one). You should write a python code who is able to crypt and decrypt an English sentence (the 26 letters) using this cipher. You program should take as input the size of the shift too (a number between 0 and 26).

How can I decrypt my message:) ?

message= raw_input("Please enter plaintext to Cipher: ")
shift = int(raw_input("Please enter shift: "))

result = ''
for letter in message:
    x = ord(letter)

    if letter.isalpha():
        x = x + shift

        offset = 65
        if letter.islower():
            offset = 97

        while x < offset:
            x += 26

        while x > offset+25:
            x -= 26

        result += chr(x)

print result

I got just gggg?maybe Im writting wrong?

result = ''
for letter in message:
    x = ord(letter)

    if letter.isalpha():
        x = 26 - shift

Output

Please enter your Cipher code: bcde
Please enter shift: 1
gggg

This seems to work ...

message = 'your mother wears army socks'
shift = 1

def cipher(message, shift):
    result = ''
    for letter in message:
        x = ord(letter)
        if letter.isalpha():
            x = x + shift
            offset = 65
            if letter.islower():
                offset = 97
            while x < offset:
                x += 26
            while x > offset+25:
                x -= 26
        result += chr(x)
    return result

encoded = cipher(message, shift)
decoded = cipher(encoded, -shift)

print encoded
print decoded

''' result..
zpvs npuifs xfbst bsnz tpdlt
your mother wears army socks
'''

Thanks Vegaseat Thanks ....
Vegaseat you are one of the my favorite person in daniweb:)

Edited 3 Years Ago by tony75

I guess this works as well:

def cipher(message, shift):
    return ''.join([chr(ord(i)+shift) if i.isalpha() else i for i in message])

Edited 3 Years Ago by Lucaci Andrew

Thanks Lucaci Andrew for different way.
What about if Im reading from a file(plaintext.txt) and wirte cipher to another file(cipher.txt)?

Well, you could open both files, read each line from the 'plaintext.txt', cipher it, than write it to the second file...

def fl(flin, flout, shift):
    try:
        [open(flout, 'a').write(cipher(i, shift)) for i in open(flin, 'r')]
    except Exception as e:
        print e

Edited 3 Years Ago by Lucaci Andrew

This question has already been answered. Start a new discussion instead.