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

MAX_KEY_SIZE = 26

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
else:
print('Enter either "encrypt" or "e" or "decrypt" or "d".')

def getMessage():
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)
else:
translated += symbol
return translated

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

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

key = -key; is the same as key = key * -1;

IOW, negation.

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.