UPPERCASE_INDEX = 65 LOWERCASE_INDEX = 97 ALPHABET_LENGTH = 26 class NonIntegerShiftError(ValueError): pass class NonStringInputError(ValueError): pass def encrypt(plaintext, shift): '''encrypt a string using the caesar cipher''' if not isinstance(plaintext, str): raise NonStringInputError('Can only encrypt a string.') if not isinstance(shift, int): raise NonIntegerShiftError('Can only shift by an integral value.') characters = list(plaintext) for i in range(len(characters)): if characters[i].isalpha(): oldChar = ord(characters[i]) if oldChar < LOWERCASE_INDEX: oldChar -= UPPERCASE_INDEX newChar = ( (oldChar + shift) % ALPHABET_LENGTH ) + UPPERCASE_INDEX else: oldChar -= LOWERCASE_INDEX newChar = ( (oldChar + shift) % ALPHABET_LENGTH ) + LOWERCASE_INDEX characters[i] = chr(newChar) return ''.join(characters) def decrypt(ciphertext, shift): '''decrypt a string using the caesar cipher''' if not isinstance(ciphertext, str): raise NonStringInputError('Can only encrypt a string.') if not isinstance(shift, int): raise NonIntegerShiftError('Can only shift by an integral value.') characters = list(ciphertext) for i in range(len(characters)): if characters[i].isalpha(): oldChar = ord(characters[i]) if oldChar < LOWERCASE_INDEX: oldChar -= UPPERCASE_INDEX newChar = ( (oldChar - shift) % ALPHABET_LENGTH ) + UPPERCASE_INDEX else: oldChar -= LOWERCASE_INDEX newChar = ( (oldChar - shift) % ALPHABET_LENGTH ) + LOWERCASE_INDEX characters[i] = chr(newChar) return ''.join(characters)