# Implementing a Caesar Cipher

Copied!
Happy Pythoning!

Erick Kendall

I’m not clear on why we need to do `% len(alphabet)`.

Bartosz Zaczyński RP Team

@Erick Kendall The percent sign (`%`) is the modulo operator in Python, which can be handy in modular arithmetic.

In this case, it ensures that the shifted numbers will wrap around so that letters at the end of the alphabet, such as x, y, and z, will become a, b, and c, respectively:

``````>>> from string import ascii_lowercase as alphabet
>>> alphabet[(alphabet.index("z") + 3) % len(alphabet)]
'c'
``````

When you don’t use the modulo operator, then letters at the end of the alphabet will cause an error because the corresponding ordinal values will exceed the bounds of your alphabet:

``````>>> alphabet[(alphabet.index("z") + 3)]
Traceback (most recent call last):
...
IndexError: string index out of range
``````

Here are the underlying indices that you obtain with and without the modulo operator:

``````>>> (alphabet.index("z") + 3) % len(alphabet)  # We're back at 2
2

>>> (alphabet.index("z") + 3)  # That's too large!
28

>>> len(alphabet)  # There are only 26 letters in the alphabet
26
``````

to join the conversation.