You can use the modulo operator ('%') to get the rest after a division i.e. 10%3
would be 1. You can use this to make your values "wrap around" at a specific point.
I've moved your calculations out to two separate statements to make it clearer what's happening - first we find the value for the actual character (a => 0, b => 1, c => 2, etc) by subtracting 97 from the char value. We then add the key, and make sure that it wraps around at 26 (since there are only 26 lowercase letters in the english alphabet). We then add 97 again to get the proper ascii value of that letter again.
'z' will first be 122, subtracting 97 gives us 25, adding 1 gives us 26. Using the modulo operator, this tells us the rest would have been 0 - effectively wrapping around to a
again. We get the character back by adding 97 to 0 - getting 97 - which is the ascii value of a
.
To return the complete string, we add each character to the result by using +=
. That way we can append each letter the the previous sequence of letters before returning them.
def encrypt(message, key):
message = message.lower().replace(" ", "")
print("lower case message: " + message)
result = ""
for i in message:
offset_from_a = (ord(i) - 97) + key
chr_value = 97 + (offset_from_a % 26)
result += chr(chr_value)
return result
encrypt('abc', 1) => 'bcd'
encrypt('zbc', 1) => 'acd'