[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

# Problem:
# Write a function that encodes a message using a Caesar cipher.
# Shift each letter by a given number. Wrap around the alphabet if needed.
# Preserve spaces and punctuation. Keep the case of each letter.

# Constraints:
# - Only shift alphabetic characters (a-z, A-Z)
# - Spaces and punctuation remain unchanged


def caesar_cipher(message: str, shift: int) -> str:
    result = []
    for char in message:
        if char.isalpha():
            if char.islower():
                unicode = ord(char)
                shifted_unicocde = (unicode - ord('a') + shift) % 26 + ord('a')
                shifted_char = chr(shifted_unicocde)
            if char.isupper():
                unicode = ord(char)
                shifted_unicocde = (unicode - ord('A') + shift) % 26 + ord('A')
                shifted_char = chr(shifted_unicocde)
            result.append(shifted_char)
        else:
            result.append(char)
   
    return ''.join(result)


if __name__ == '__main__':
    assert caesar_cipher("Hello, World!", 3) == "Khoor, Zruog!", 'test 1 failed'
    assert caesar_cipher("abc xyz", 2) == "cde zab", 'test 2 failed'
    assert caesar_cipher("Data-123", 1) == "Ebub-123", 'test 3 failed'

Comments