[Python] caeser cipher pattern
Caesar cipher
Purpose
This function encodes a message using the Caesar cipher, where each alphabetic character is shifted forward by a specified amount.
- It preserves the case of each letter.
- It wraps around the alphabet when needed.
- It leaves spaces, numbers, and punctuation unchanged.
Constraints
- Only shift letters — lowercase (a–z) and uppercase (A–Z)
- Leave non-letter characters as-is
- The alphabet has 26 characters
- The shift must wrap around if it exceeds z or Z
Step-by-step Logic
1. Create a list to hold the final shifted characters.
This list will collect transformed letters (or untouched non-letters).
2. Iterate over each character in the input string.
Use a for loop to examine each character one by one.
3. Check if the character is alphabetic using .isalpha().
If it’s not a letter (like punctuation or a number), skip shifting.
4. Branch by case using .islower() and .isupper():
Handle lowercase and uppercase letters separately to preserve their casing.
5. Convert the character to its Unicode code using ord(char).
This gives the numeric position of the letter in the Unicode table.
6. Apply the Caesar shift:
- Subtract ord('a') or ord('A') to compute the character's offset from the start of the alphabet*
- Add the shift value
- Use % 26 to wrap around if needed
- Add back ord('a') or ord('A') to shift the result back into Unicode space
- Convert it back to a character using chr()
7. Append the shifted character to the result list
This builds the final output string step by step.
8. If the character is not alphabetic, simply append it unchanged.
For example: spaces, hyphens, numbers, punctuation.
9. Join the list into a final string using ''.join() and return it.
The function outputs the fully encoded Caesar cipher result.
Key Python Functions and Concepts
- ord(char) — converts a character to its Unicode number
- chr(number) — converts a Unicode number back to a character
- str.isalpha() — checks if a character is a letter
- str.islower() / str.isupper() — checks letter case
- % 26 — ensures the Caesar shift wraps around the alphabet
- ''.join() — combines a list of characters into a string
Comments
Post a Comment