HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMinor

A Simple Caesar Cipher in Python

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
caesarsimplepythoncipher

Problem

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,

Solution

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

  • 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.



  • In collectMessage() you can directly return raw_input("Enter the message you would like to translate:\n\n")



  • In collectKey(): you can remove both continue statements



  • 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.

Code Snippets

def choose_mode():
    """
    Docstring here 
    """
    # the rest of your code
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)
"I love to review code at midnight because I have no life".encode("rot13")

Context

StackExchange Code Review Q#157855, answer score: 6

Revisions (0)

No revisions yet.