Caesar Cipher in Python
A Caesar cipher practices character codes, modulo arithmetic, and string construction.
What is Caesar Cipher?
A Caesar cipher practices character codes, modulo arithmetic, and string construction.
Shift lowercase letters by a fixed amount.
When should you use it?
- Learn Python syntax through a practical example.
- Build a foundation for larger programming problems.
- Test an idea quickly without a local setup.
Example code
main.py
message = "code"
shift = 3
# Shift each lowercase letter and wrap after z.
encrypted = "".join(
chr((ord(character) - ord("a") + shift) % 26 + ord("a"))
for character in message
)
print(encrypted)
Expected output
frgh
How it works
Subtracting the code for a creates a zero-based letter index before wrapping with modulo 26.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the input and predict the output before running.
- Handle empty or invalid input.
- Wrap the logic in a function and add more test cases.