Created
September 20, 2025 17:42
-
-
Save derekbelrose/e92a89ba99ed8e8f3b181628b51783c6 to your computer and use it in GitHub Desktop.
Python script that encrypts a string using the Caesar cipher with argparse.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
caesar_encrypt.py | |
Encrypt a string with the Caesar cipher using argparse. | |
Usage: | |
$ python caesar_encrypt.py "Hello, World!" --shift 5 | |
$ python caesar_encrypt.py "Attack at dawn!" | |
""" | |
import argparse | |
def caesar_shift_char(ch: str, shift: int) -> str: | |
if ch.isupper(): | |
base = ord('A') | |
elif ch.islower(): | |
base = ord('a') | |
else: | |
return ch | |
offset = ord(ch) - base | |
new_offset = (offset + shift) % 26 | |
return chr(base + new_offset) | |
def caesar_encrypt(text: str, shift: int) -> str: | |
return ''.join(caesar_shift_char(ch, shift) for ch in text) | |
def main() -> None: | |
parser = argparse.ArgumentParser(description="Caesar cipher encryptor") | |
parser.add_argument("text", help="Text to encrypt") | |
parser.add_argument( | |
"--shift", | |
type=int, | |
default=3, | |
help="Number of positions to shift (default: 3)", | |
) | |
args = parser.parse_args() | |
ciphertext = caesar_encrypt(args.text, args.shift) | |
print("\nCiphertext:\n") | |
print(ciphertext) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment