Author SHA1 Message Date
Tirsvad 9d8beb3aef Refactor to unified caesar() function with encode/decode support
- Replace separate encrypt/decrypt with shared caesar() function
- Add direction constants (DIRECTION_ENCODE, DIRECTION_DECODE) and
  prompts
- Update main.py to support interactive encode/decode loop
- Keep encrypt/decrypt as wrappers for backward compatibility
- Add tests for caesar() with both directions and error handling
- Update tests for main.py with interactive scenario tests
2026-10-04 13:23:47 +08:00
Tirsvad d4b3e6ab19 Merge pull request 'Part 2: Decryption' (#2) from part-2-decryption into main
TirSystem/github-action: Sync GitHub mirror metadata / sync-metadata (push) Successful in 6s
Reviewed-on: #2
2026-10-04 07:20:21 +02:00
Tirsvad 621f5f7272 Add decrypt function to Caesar cipher
- Implement decrypt function that reverses encryption with negative
  shift
- Export decrypt in package's public API
- Update tests with basic roundtrip and edge case tests
- Update documentation to reflect encryption/decryption support
2026-10-04 13:18:33 +08:00
8 changed files with 160 additions and 33 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
# 🔐 Caesar Cipher # 🔐 Caesar Cipher
A beginner-friendly Python program that encodes messages with the Caesar cipher. A beginner-friendly Python program that encodes and decodes messages with the Caesar cipher.
## 📚 Table of Contents ## 📚 Table of Contents
@@ -14,7 +14,7 @@ A beginner-friendly Python program that encodes messages with the Caesar cipher.
## 🧭 Overview ## 🧭 Overview
The Caesar cipher shifts every letter by a fixed number of places (with a shift of 3, `E` becomes `H`). This project, from Udemy's *100 Days of Code: The Complete Python Pro Bootcamp* (Day 8), finds letter positions with `list.index` and wraps around the alphabet with the modulo operator. Part 1 covers encryption; decryption and a combined program follow in later parts. Code lives in `src/`, tests in `tests/`, docs in `docs/`. The Caesar cipher shifts every letter by a fixed number of places (with a shift of 3, `E` becomes `H`). This project, from Udemy's *100 Days of Code: The Complete Python Pro Bootcamp* (Day 8), finds letter positions with `list.index` and wraps around the alphabet with the modulo operator. The interactive program lets you encode or decode as many messages as you like. Code lives in `src/`, tests in `tests/`, docs in `docs/`.
## 📋 Requirements ## 📋 Requirements
+1 -1
View File
@@ -3,7 +3,7 @@
Each letter is moved `shift` places through the alphabet: Each letter is moved `shift` places through the alphabet:
`new_position = (ALPHABET.index(letter) + shift) % 26`. `new_position = (ALPHABET.index(letter) + shift) % 26`.
The modulo keeps positions in range for shifts past `z`. The modulo keeps positions in range for shifts past `z`.
Non-letters are left untouched and letter case is preserved. Decoding shifts by `-shift`; one shared `caesar(text, shift, direction)` function does both. Non-letters are left untouched and letter case is preserved.
API reference: run `doxygen Doxyfile` from the repository root and open API reference: run `doxygen Doxyfile` from the repository root and open
`docs/doxygen/html/index.html`. The step-by-step plan is in [plan.md](plan.md). `docs/doxygen/html/index.html`. The step-by-step plan is in [plan.md](plan.md).
+2 -2
View File
@@ -1,6 +1,6 @@
## @file __init__.py ## @file __init__.py
# @brief Public API of the caesar_cipher package. # @brief Public API of the caesar_cipher package.
from caesar_cipher.cipher import encrypt from caesar_cipher.cipher import caesar, decrypt, encrypt
__all__ = ["encrypt"] __all__ = ["caesar", "encrypt", "decrypt"]
+30 -7
View File
@@ -1,14 +1,21 @@
## @file cipher.py ## @file cipher.py
# @brief Caesar cipher encryption. # @brief Caesar cipher: one shared function for encoding and decoding.
from caesar_cipher.constants import ALPHABET from caesar_cipher.constants import ALPHABET, DIRECTION_DECODE, DIRECTION_ENCODE
def encrypt(text: str, shift: int) -> str: def caesar(text: str, shift: int, direction: str) -> str:
## @brief Encrypt a text with the Caesar cipher. ## @brief Encode or decode a text with the Caesar cipher.
# @param text Original text. # @param text Text to transform.
# @param shift Positions to move each letter (may be negative or > 26). # @param shift Positions to move each letter (may be negative or > 26).
# @return The encrypted text; non-letters are kept, case is preserved. # @param direction DIRECTION_ENCODE or DIRECTION_DECODE.
# @return The transformed text; non-letters are kept, case is preserved.
# @throws ValueError If direction is not a known direction.
if direction == DIRECTION_DECODE:
shift = -shift
elif direction != DIRECTION_ENCODE:
raise ValueError(f"Unknown direction: {direction!r}")
result = [] result = []
for char in text: for char in text:
lower = char.lower() lower = char.lower()
@@ -19,3 +26,19 @@ def encrypt(text: str, shift: int) -> str:
else: else:
result.append(char) result.append(char)
return "".join(result) return "".join(result)
def encrypt(text: str, shift: int) -> str:
## @brief Encrypt a text with the Caesar cipher.
# @param text Original text.
# @param shift Number of positions to shift forward.
# @return The encrypted text.
return caesar(text, shift, DIRECTION_ENCODE)
def decrypt(text: str, shift: int) -> str:
## @brief Decrypt a Caesar-cipher text.
# @param text Encrypted text.
# @param shift Shift that was used to encrypt.
# @return The original text.
return caesar(text, shift, DIRECTION_DECODE)
+28
View File
@@ -4,10 +4,38 @@
## Lowercase alphabet used to look up letter positions. ## Lowercase alphabet used to look up letter positions.
ALPHABET = list("abcdefghijklmnopqrstuvwxyz") ALPHABET = list("abcdefghijklmnopqrstuvwxyz")
## Direction keyword for encoding.
DIRECTION_ENCODE = "encode"
## Direction keyword for decoding.
DIRECTION_DECODE = "decode"
## Prompt for the direction.
PROMPT_DIRECTION = "Type 'encode' to encrypt, type 'decode' to decrypt:\n"
## Prompt for the message. ## Prompt for the message.
PROMPT_TEXT = "Type your message:\n" PROMPT_TEXT = "Type your message:\n"
## Prompt for the shift number. ## Prompt for the shift number.
PROMPT_SHIFT = "Type the shift number:\n" PROMPT_SHIFT = "Type the shift number:\n"
## Prompt to continue.
PROMPT_AGAIN = "Type 'yes' if you want to go again. Otherwise type 'no'.\n"
## Name of the environment file holding tokens. ## Name of the environment file holding tokens.
ENV_FILE = ".env" ENV_FILE = ".env"
## ASCII art title shown at start-up.
TITLE = r"""
____ _ _____ ____ _ ____
/ ___| / \ | ____/ ___| / \ | _ \
| | / _ \ | _| \___ \ / _ \ | |_) |
| |___ / ___ \| |___ ___) / ___ \| _ <
\____/_/ \_\_____|____/_/ \_\_| \_\
____ ___ ____ _ _ _____ ____
/ ___|_ _| _ \| | | | ____| _ \
| | | || |_) | |_| | _| | |_) |
| |___ | || __/| _ | |___| _ <
\____|___|_| |_| |_|_____|_| \_\
"""
## ANSI escape code for bright cyan text.
COLOR_TITLE = "\033[96m"
## ANSI escape code that resets text colour.
COLOR_RESET = "\033[0m"
+43 -20
View File
@@ -1,20 +1,43 @@
## @file main.py ## @file main.py
# @brief Interactive command line interface. # @brief Interactive command line interface.
from caesar_cipher import constants as c import os
from caesar_cipher.cipher import encrypt import sys
from caesar_cipher import constants as c
def main() -> None: from caesar_cipher.cipher import caesar
## @brief Ask for a message and a shift, then print the encrypted text.
text = input(c.PROMPT_TEXT)
try: def print_title() -> None:
shift = int(input(c.PROMPT_SHIFT)) ## @brief Print the ASCII title, in colour when the terminal supports it.
except ValueError: if sys.stdout.isatty() and "NO_COLOR" not in os.environ:
print("The shift must be a whole number.") os.system("") # enables ANSI escape sequences on older Windows consoles
return print(f"{c.COLOR_TITLE}{c.TITLE}{c.COLOR_RESET}")
print(f"Here's the encoded result: {encrypt(text, shift)}") else:
print(c.TITLE)
if __name__ == "__main__":
main() def main() -> None:
## @brief Run the interactive encode/decode loop until the user stops.
print_title()
while True:
direction = input(c.PROMPT_DIRECTION).strip().lower()
if direction not in (c.DIRECTION_ENCODE, c.DIRECTION_DECODE):
print("Please type 'encode' or 'decode'.")
continue
text = input(c.PROMPT_TEXT)
try:
shift = int(input(c.PROMPT_SHIFT))
except ValueError:
print("The shift must be a whole number.")
continue
print(f"Here's the {direction}d result: {caesar(text, shift, direction)}")
if input(c.PROMPT_AGAIN).strip().lower() != "yes":
print("Goodbye")
break
if __name__ == "__main__":
main()
+26 -1
View File
@@ -1,4 +1,6 @@
from caesar_cipher import encrypt import pytest
from caesar_cipher import caesar, decrypt, encrypt
from caesar_cipher.env import load_env from caesar_cipher.env import load_env
@@ -24,3 +26,26 @@ def test_load_env(tmp_path):
f.write_text("# c\nA=1\nB='two'\n", encoding="utf-8") f.write_text("# c\nA=1\nB='two'\n", encoding="utf-8")
assert load_env(f) == {"A": "1", "B": "two"} assert load_env(f) == {"A": "1", "B": "two"}
assert load_env(tmp_path / "missing") == {} assert load_env(tmp_path / "missing") == {}
def test_decrypt_basic():
assert decrypt("mjqqt", 5) == "hello"
def test_decrypt_roundtrip():
assert decrypt(encrypt("Hello, World!", 7), 7) == "Hello, World!"
def test_decrypt_wraps_around_alphabet():
assert decrypt("abc", 3) == "xyz"
assert decrypt("def", 29) == "abc"
def test_caesar_encode_and_decode():
assert caesar("hello", 5, "encode") == "mjqqt"
assert caesar("mjqqt", 5, "decode") == "hello"
def test_caesar_unknown_direction():
with pytest.raises(ValueError):
caesar("hello", 5, "sideways")
+28
View File
@@ -0,0 +1,28 @@
from caesar_cipher.main import main
def run(monkeypatch, capsys, answers):
it = iter(answers)
monkeypatch.setattr("builtins.input", lambda _="": next(it))
main()
return capsys.readouterr().out
def test_encode_then_stop(monkeypatch, capsys):
out = run(monkeypatch, capsys, ["encode", "hello", "5", "no"])
assert "mjqqt" in out and "Goodbye" in out
def test_decode_then_go_again(monkeypatch, capsys):
out = run(monkeypatch, capsys, ["decode", "mjqqt", "5", "yes", "encode", "a", "1", "no"])
assert "hello" in out and "b" in out
def test_invalid_input_reprompts(monkeypatch, capsys):
out = run(monkeypatch, capsys, ["nope", "decode", "x", "abc", "encode", "a", "1", "no"])
assert "encode' or 'decode" in out and "whole number" in out
def test_title_printed_plain_when_not_a_tty(monkeypatch, capsys):
out = run(monkeypatch, capsys, ["encode", "a", "1", "no"])
assert "____" in out and "\033[" not in out