Explanation for Python Ceasar Cipher project

Hi,

I’m working on this project, however I was super stuck so I looked at the solution to understand it better.

alphabet = "abcdefghijklmnopqrstuvwxyz" punctuation = ".,?'! " message = "xuo jxuhu! jxyi yi qd unqcfbu ev q squiqh syfxuh. muhu oek qrbu je tusetu yj? y xefu ie! iudt cu q cuiiqwu rqsa myjx jxu iqcu evviuj!" translated_message = "" for letter in message: if not letter in punctuation: letter_value = alphabet.find(letter) translated_message += alphabet[(letter_value + 10) % 26] else: translated_message += letter print(translated_message)

I understand almost all of it, except I dont understand this part:

translated_message += alphabet[(letter_value + 10) % 26]

Why do they use the letter value + 10 and then %26? If someone could explain me this that would be nice.

Thanks!

letter_value is the index (integer) where that letter/character was found within alphabet
so if the letter is 'a' then letter_value would be 0.

letter_value + 10 shifts the letter over by 10 to get the index of the new letter
index % 26 gives you a number from 0 to 25
(which is needed because the length of alphabet is 26.
For example, alphabet[28] would cause an error, but alphabet[28 % 26] would not … since that would be alphabet[2] ).

The idea is to “wrap around” the alphabet … meaning use %26 to make the index smaller if its too big.

1 Like

Oh I understand now! Thanks!