5
\$\begingroup\$

I wrote an encryption/decryption algorithm for the Caesar Cipher. It works fine, but I'm curious if there are any constructive critiques, tips, tricks, comments, or advice anyone may have on how the code operates, performs, looks, etc.

# Caesar Cipher
def chooseMode():
    while True:
        mode = raw_input("\nChoose a mode (encryption or decryption):\n 1) Encrypt \n 2) Decrypt\n 3) Brute Force\n\n")
        if mode in ['1', '2', '3']:
            return mode


def collectMessage():
    message = raw_input("Enter the message you would like to translate:\n\n")
    return message


def collectKey():
    while True:
        key = raw_input("What is the key for your message? (Enter a number from 0 to 26): \n")
        try:
            if int(key) in range(27):
                return int(key)
            else:
                print("Please enter an integer between 0 and 26.\n")
                continue
        except ValueError:
            print("Please enter an integer between 0 and 26.\n")
            continue


def translateMessage(text, cipher_mode, caeser_key):
    translation = ''
    # If decrypting, convert key to negative.
    if cipher_mode == '2':
        caeser_key = -caeser_key

    for symbol in text:
        # Convert only Alphabetical Symbols
        if symbol.isalpha():
            num = ord(symbol)

            # Shift num down to 1 through 26 for more easier to visualize modulous.
            # Then Apply the Key; then Modulate; then Move Back Up; then Build into Chr and Translation
            if symbol.isupper():
                num -= ord('A')
                num += caeser_key
                num %= 26
                num += ord('A')
                translation += chr(num)

            else:
                num -= ord('a')
                num -= caeser_key
                num %= 26
                num += ord('a')
                translation += chr(num)
        else:
            translation += symbol
    return translation


def bruteForce(text, cipher_mode):
    if cipher_mode == '3':
        for index in range(26):
            print "A Caeser Key of ", str(index), "reveals:\t", translateMessage(text, cipher_mode, 26 - index)
        exit()
    else:
        return None


choice_of_mode = chooseMode()
entered_message = collectMessage()

bruteForce(entered_message, choice_of_mode)

entered_key = collectKey()
final_form = translateMessage(entered_message, choice_of_mode, entered_key)
print final_form
\$\endgroup\$
6
\$\begingroup\$

Some style notes (you can read more 'bout them on Python's official style-guide which is called PEP8):

  • you misspelled Caeser. It should be Caesar.
  • function names should be snake_cased not camelCased
  • instead of commenting lines at the middle of the method, just add a docstring:

    def choose_mode():
        """
        Docstring here 
        """
        # the rest of your code
    
  • you should add the if __name__ == '__main__' guard

About the code

  1. It's pretty weird to use exit which is a helper for the interactive shell instead of sys.exit which is intended for use in programs. I'd stick to the latter.
  2. In collectMessage() you can directly return raw_input("Enter the message you would like to translate:\n\n")
  3. In collectKey(): you can remove both continue statements
  4. You should use format() when printing. Here, you can read more about formatting.

About the algorithm

  • In Python, we have the translate method which applies a substitution cipher to a string. More, when building the translation table, in Python 2, we have string.maketrans.

    import string
    from string import ascii_lowercase
    
    
    shift = 6
    cipher = string.maketrans(ascii_lowercase, ascii_lowercase[shift:] + ascii_lowercase[:shift])
    
    print "I love to review code at midnight because I have no life".translate(cipher)
    

    Which outputs:

    I rubk zu xkbokc iujk gz sojtomnz hkigayk I ngbk tu rolk

  • Another built-in that you may take advantage of is:

    "I love to review code at midnight because I have no life".encode("rot13")
    

PS: You can also have a quick look at this answer for other recommendations that might apply quite well to your code.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.