1
\$\begingroup\$

I've been studying computer science for around two school terms now. Currently, I'm making a Caesar Cipher program as a base for my examination, this is so that I can use the 15 hours to either add, or improve my code. Please, give me some feedback on how to improve my code or, at least, make it clearer.

class Functions:
    def encrypt(message, shift):
        nEncryptedMessage = "" #Defines it as an empty string
        encryptedMessage = "" #Defines it as an empty string
        cap = 0 #Defines cap as 0
        for ch in message.lower(): #This takes each letter of the message
            if ch.isalpha(): #If the message has a character, it's passed through. This stops the ascii code of a space getting mixed up in the code.
                ch = ord(ch) #Changes the letter into its corrasponding Ascii code
                ch += int(shift) #Adds the shift
                if ch > ord("z"): #Sees if the Ascii is now bigger than the last letter in the alphabet
                    while ch > ord("z"): #This ensures that the code, if given a really big shift, isn't too big
                        ch -= 26 #Takes away 26 as there are only 26 letters, therefore it'll go back to 'a'
                    encryptedMessage += chr(ch) #This adds to the newly altered message
                else:
                    encryptedMessage += chr(ch) #This adds the characters that weren't greater than 'z'
            else:
                encryptedMessage += ch #This adds a character that isn't a letter, eg. A space, period, etc.
        for letter in encryptedMessage: #This for loop capitalizes the first letter of the sentence
            cap += 1 #Adds one to 'cap' every time the loop finishes once
            if cap == 1: #If cap is equal to 1 - the following happens
                nEncryptedMessage += letter.upper() #As cap is equal to one, this is the first letter, so it's placed into the string as a capital letter
            else: #If cap is not equal to 1 - this happens
                nEncryptedMessage += letter.lower() #As I've already placed a capital letter, the rest should be lower case
        return nEncryptedMessage #The functions returns the punctuated and decrypted message

    def decrypt(message, shift):
        nDecryptedMessage = ""
        decryptedMessage = ""
        cap = 0
        for ch in message.lower(): #This takes each letter of the message
            if ch.isalpha(): #If the message has a character, it's passed through. This stops the ascii code of a space getting mixed up in the code.
                ch = ord(ch) #Changes the letter into its corrasponding Ascii code
                ch -= int(shift) #Takes away the shift
                if ch < ord("a"): #Sees if the Ascii is now less than the first letter in the alphabet
                    while ch < ord("a"): #This ensures that the code, if given a really big shift, isn't too small
                        ch += 26 #Adds 26 as there are only 26 letters, therefore it'll go back to 'z'
                    decryptedMessage += chr(ch) #This adds to the newly altered message
                else:
                    decryptedMessage += chr(ch) #This adds characters that weren't less than 'a'
            else:
                decryptedMessage += ch #This adds a character that isn't a letter, eg. A space, period, etc.
        for letter in decryptedMessage: #This for loop capitalizes the first letter of the sentence
            cap += 1 #Adds one to 'cap' every time the loop finishes once
            if cap == 1: #If cap is equal to 1 - the following happens
                nDecryptedMessage += letter.upper() #As cap is equal to one, this is the first letter, so it's placed into the string as a capital letter
            else: #If cap is not equal to 1 - this happens
                nDecryptedMessage += letter.lower() #As I've already placed a capital letter, the rest should be lower case
        return nDecryptedMessage #The functions returns the punctuated and decrypted message

class Menu: #This is a class designed just to run the menu. This helps to make the code look tidy
    displayMenu = True #If this variable
    while displayMenu == True: #While true, this runs the menu before it's broken
        menu = input("""
1) Encrypt
2) Decrypt
3) Exit
""") #Menu input which is made by the user to choose from one of the selections in the menu by addressing it by the number to the left of the action
        if menu == '1': #This is where the encrypt function gets its variables
            storeEncryptedMessages = open("encryptedMessages.txt", "a") #Opens the file 'encryptedMessages.txt' and assigns it to the corrasponding variable
            message = input("What is the message that you'd like to encrypt? ") #Message to encrypt
            shift = input("What is the shift? ") #The shift for the message
            enctpMessage = Functions.encrypt(message, shift) #Calls the encrypt function from 'Functions'
            print(enctpMessage)
            storeEncryptedMessages.write("The original message was '" + message + "' with a shift if '" + shift + ".' The encrypted message was '" + enctpMessage + ".' \n") #Writes into the file
            storeEncryptedMessages.close() #Closes the file
        elif menu == '2': #This is where the decrypt function gets its variables
            storeDecryptedMessages = open("decryptedMessages.txt", "a") #Opens the file 'decryptedMessages.txt' to the corresponding variable
            message = input("What message do you want to decrypt? ") #Message to decrypt
            shift = input("What was the shift? ") #The shift
            DecryptedMessage = Functions.decrypt(message, shift) #Calls the decrypt function from 'Functions'
            print(DecryptedMessage)
            storeDecryptedMessages.write("The encrypted message was '" + message + ".' The decrypted message was '" + DecryptedMessage + "' with a shift of '" + shift + ".' \n") #Writes into this file
            storeDecryptedMessages.close() #Closes this file
        elif menu == '3': #This exits the loop that runs the menu, therefore, closing the application
he program
            break #This breaks the while 
\$\endgroup\$
4
  • \$\begingroup\$ Welcome to Code Review! Good job on your first question. \$\endgroup\$
    – Phrancis
    Commented Mar 18, 2016 at 5:45
  • 1
    \$\begingroup\$ A comment per line is never necessary. Also, these functions don't need to be in a class, you can use them first-class instead (global). Also, between encryption and decryption not much stuff is different, so why don't you do it in one function with a boolean parameter to indicate encryption or decryption. \$\endgroup\$ Commented Mar 18, 2016 at 5:56
  • \$\begingroup\$ Ah, thank you! I shall add that to my final version of the code. \$\endgroup\$ Commented Mar 18, 2016 at 6:00
  • \$\begingroup\$ You have some stray text after elif menu == '3'. Please verify that you have faithfully posted your actual working program. \$\endgroup\$ Commented Mar 18, 2016 at 8:53

1 Answer 1

2
\$\begingroup\$

Coding

Building up on the comment of @Tamoghna Chowdhury, one can express either encrypt or decrypt using the other function.

For example you could write

def encrypt(message, shift):
    # your code without the class

def decrypt(message, shift):
    return encrypt(message, -shift)

Your menu class is not a real class either. It may and probably should be replaced by a function.

Also consider to use with open(...) as ... when reading and writing from and to files, as this will take care the file gets closed even if an exception is raised while working on it (see Python doc 7.2.1, last paragraph).

Style

I don't know, if your teacher told you to use a certain style (e.g. camelCase variable names). Python itself has some very comprehensive recommendations for coding style with a lot of examples. If you can spare some time, have a look at the so called PEP8.

General

Rethink your use of classes. In general, classes are used you to represent "prototypes" or common methods/properties of objects. You better do not use them just to group functions together (well there are exceptions, but let's ignore them) or create a local scope for variables.

If you are really interested in learning Python programming, you should check the many online resources. For example, Codecademy, taught me lot of things when I started. It is interactive and absolutely free.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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