I am doing a mini project on Caesar cipher, I found one program but can't understand the 29th line "key = -key". Please help me.

# Caesar Cipher


def getMode():
        print('Do you wish to encrypt or decrypt a message?')
        print("'e' for encrypt and 'd' for decrypt")
        while True:
            mode = input().lower()
            if mode in 'encrypt e decrypt d'.split():
                return mode
            print('Enter either "encrypt" or "e" or "decrypt" or "d".')

def getMessage():
    print('Enter your message:')
    return input()

def getKey():
    key = 0
    while True:
        print('Enter the key number (1-%s)' % (MAX_KEY_SIZE))
        key = int(input())
        if (key >= 1 and key <= MAX_KEY_SIZE):
            return key

def getTranslatedMessage(mode, message, key):
    if mode[0] == 'd':
        key = -key
    translated = ''

    for symbol in message:
        if symbol.isalpha():
            num = ord(symbol)
            num += key

            if symbol.isupper():
                if num > ord('Z'):
                    num -= 26
                elif num < ord('A'):
                    num += 26
            elif symbol.islower():
                if num > ord('z'):
                    num -= 26
                elif num < ord('a'):
                    num += 26

            translated += chr(num)
            translated += symbol
    return translated

mode = getMode()
message = getMessage()
key = getKey()

print('Your translated text is:')
print(getTranslatedMessage(mode, message, key))

Edited by Reverend Jim: corrected spelling of Caesar

1 Year
Discussion Span
Last Post by Rajan_8

hey! rproffitt could u please tell me the use of tht line in the program


Sadly no. But my bet is there is some formula from a paper that this this code implements. Since I don't know the paper this was coded from I can't point to the formula from the paper.

Try this. Go get the paper or papers on this cipher and look at the formula for a negation step.

Edited by rproffitt: Spelling


A Ceasar cyper encodes by shifting letters in one direction, and decodes by shifting in the opposite direction. key is the number of places to shift. If the user wants to decode then key is negated to shift in the opposite direction.


Thank you Reverend jim and rproffitt for helping me here

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.