2
\$\begingroup\$

I am new to python. I wrote the following Caesar Cipher. Could someone help me to improve the code or make it shorter? Thanks in advance. PS. #COM is to make comments.

import os #COM
import pyperclip
import sys #COMMMMMMMMMMMMMM

#GETTING MODE
def get_mode():
    try:
        while True:
            print('Press "E" to encrypt\nPress "D" to decrypt') ##COM
            mode = input().lower()
            if mode == 'e':
                print('You have chosen to encrypt') ##COMMMMMM
                return mode
            elif mode == 'd':
                print('You have chosen to decrypt') ##COMMMMM
                return mode#COM
            elif mode == 'god mode': ## GOD MODE TO INITIATE BRUTE FORCE
                print('Initiating God Mode') #COMMMM
                return mode
            print('Invalid option selected') #COMMMMM
    except ValueError: #COM
        print('Invalid input')
        get_mode()

#GETTING SECRET KEY
def get_key():
    try:
        while True:
            print('Please select a secret key: ')
            key = int(input())
            if (key >= 1) and (key <= 26):
                return key
            print('Key has to be between 1-26')
    except ValueError:
        print('Key has to be an integer') #COM
        get_key()

#ALL CHARACTERS
def all_cha(): #COM
    all_characters = ''
    for i in range(1, 1000):
        all_characters += chr(i) #COMMMM
    return all_characters #COOOMMMMMMMMMMMMM

#INPUT MESSAGE
def get_message():
    print('Please enter the message here:') #COOOOOOOOOOO
    mess = input()
    return mess #COOOMMMMMMMMMMMMMM

#MAIN CIPHER
def caesar_cipher(mode, message, key): ##COM 
    result = ''
    for characters in message:
        if characters in all_cha():
            num = all_cha().find(characters)
            if mode == 'e': #COM
                num += key
            elif mode == 'd':
                num -= key
            result += all_cha()[num]
        else: #COM
            result += characters
    print('Your translated message is: ' + result.encode(sys.stdout.encoding, errors='replace').decode())  #COM
    pyperclip.copy(result)
    write_message(result)
    return str(result.encode(sys.stdout.encoding, errors='replace').decode())

#READ DATA FROM TEXT FILE
def read_message():
    with open(file_path, 'r', encoding='utf-8') as r:
        x = r.read()
        return x

#WRITE TO A TEXT FILE
def write_message(data): #COMMM ffff fffff
    with open(file_path, 'w+', encoding='utf-8') as f: #COOMMD ffff ffff
        f.write(str(data))

#BRUTE FORCE
def brute_force(message): #COOMMMMM
    empty = []
    print('All possible combinations are: \n')
    for i in range(1, 27):
        g = caesar_cipher('d', message, i)
        print(g)
        empty.append(g)
    write_message(empty)
    return str(empty)


def main():
    global file_name
    global file_path
    file_name = os.path.basename(sys.argv[0]) + '_encrypt.txt'
    file_path = os.path.join(os.path.expanduser('~'), 'Desktop', file_name)
    print('Welcome to PyCi_02 V1 by Aj')
    a, b, c = get_mode(), None, get_key()
    try:
        if a == 'e':
            b = get_message()
            caesar_cipher(a, b, c)
            os.system('pause')
        elif a == 'd' or a == 'god mode':
            if os.path.exists(file_path):
                b = read_message()
                if read_message() == '':
                    print('Need to write data to encrypt')
                    os.system('pause')
                else:
                    if a == 'god mode':
                        brute_force(b)
                        os.system('pause')
                    elif a == 'd':
                        caesar_cipher(a, b, c)
                        os.system('pause')
            else:
                print('No data file.. New file has been created.. Enter your message')
                x = input()
                write_message(x)
                b = read_message()
                if a == 'god mode':
                    brute_force(b)
                    os.system('pause')
                elif a == 'd':
                    caesar_cipher(a, b, c)
                    os.system('pause')
    except Exception:
        print('Something went wrong')
        main()

if __name__ == '__main__':
    main()

It is a basic Caesar cipher. I wanna make it shorter so, I was wondering if someone can give me feedback.

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Comments

Remove the comments, they are not useful, they distract from the real code and make it more difficult to read.

  • It's clear that you would comments on your code, so there is no need for the '#COM' comments.

  • Comments like '#GETTING MODE' for a function named get_mode() does not add anything.

input

The input statement has a optional prompt argument so you can use:

mess = input('Please enter the message here:')

instead of:

print('Please enter the message here:') 
mess = input()

try except

Large try except blocks might be confusing for debugging, when the exception is raised you do not know exactly where the exception is raised. Furthermore I do not think the ValueError in get_mode is ever raised.

Recursion

In get_mode and get_key you call them self, although it works, this can be trickey. The while True: can do the same get_key can be rewritten to:

def get_key():
    while True: # until a good key is returned

        key_str = input('Please select a secret key(1-26): ')
        try:
            key = int(key_str)
        except ValueError:
            print('Please enter an integer')
            continue
        if (key >= 1) and (key <= 26):
            return key
\$\endgroup\$
2
  • \$\begingroup\$ I did them so that I could post my question. It wasn't letting me post unless i had more comments \$\endgroup\$
    – A J
    Commented Jun 4, 2017 at 10:24
  • \$\begingroup\$ @AJ Did you consider why CR's posting guidelines require comments? It's to get you to include useful comments in your code, not just add random comments. \$\endgroup\$
    – Barmar
    Commented Jun 8, 2017 at 22:39

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.