0

I been trying to create a Caesar cypher program with the message 'my secret' and key 6 - all letters are shifted 6 positions to the right in the cypher alphabet, with letters “wrapping around” when falling off the end. Using the cypher, the message “my secret” would be encoded as “gsumzxlzn”. However, I keep the wrong encoded and decoded results. It's comes out as: Encoded: sdfykixkz Decoded: abcdefghi

please help!

import sys
ALPHABET= ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',' ']


def main(plaintext, key):
     cypher = generate_cypher(key)
     plaintext = sys.argv[1]
     e_code = encode_message(plaintext, cypher)
     mes s= decode_message(e_code, cypher)

def generate_cypher(key):
    cipher = []
    for i in range(len(ALPHABET)):
        cipher.append(ALPHABET[i+key%27])
    print(cipher)
    return(cipher)


def encode_message(plaintext,cipher):     
    key = int(sys.argv[2])
    en_code=''
    for c in plaintext:
        if c in cipher:
            en_code+=cipher[(cipher.index(c)+key)%(len(cipher))]
    print("Encoded: ", en_code)
    return en_code

def decode_message(e_code,cipher):
    key = int(sys.argv[2])
    message = []
    for i in range(len(e_code)):
        message.append(cipher[i-key%27])

    mess=''.join(message)
    print("Decoded: ", mess)
    return mess
  • Possible duplicate of [Caesar Cipher Function in Python](http://stackoverflow.com/questions/8886947/caesar-cipher-function-in-python) – Trent Apr 18 '17 at 04:18
  • 2
    `i+key%27` and `i-key%27` look suspicious, note that the modulo operator `%` is stronger (executed first) than `+`. You can use brackets to specify the order of execution. Also make it a habit to space operators i.e. it should read e.g. `i + key % 27` for readability. – miraculixx Apr 18 '17 at 04:19
  • Thank you for the advice but I dont think user1063450's problem applies to mine since the key rely on the index of of the string for encoding. – Alfred Jones Apr 18 '17 at 04:46
  • It might be easier to convert your string to numbers using the ord() function, shift the numbers, and then convert your numbers back into a string with chr(). – iUknwn Apr 18 '17 at 05:01

0 Answers0