Created
September 20, 2025 17:41
-
-
Save derekbelrose/9fa13e6d97ccaf2747c464d84e6f39a0 to your computer and use it in GitHub Desktop.
A simple Python script that encrypts a string using the Caesar cipher.
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. | |
Usage: | |
# 1. Pass both text and shift on the command line | |
$ python caesar_encrypt.py "Hello, World!" 5 | |
# 2. Only pass the text – uses default shift of 3 | |
$ python caesar_encrypt.py "Attack at dawn!" | |
# 3. No arguments – script will prompt interactively | |
$ python caesar_encrypt.py | |
""" | |
import sys | |
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: | |
args = sys.argv[1:] | |
if not args: | |
plaintext = input("Enter the text to encrypt: ") | |
try: | |
shift = int(input("Enter the shift amount [default 3]: ") or "3") | |
except ValueError: | |
print("Invalid shift value. Using default shift of 3.") | |
shift = 3 | |
else: | |
plaintext = args[0] | |
if len(args) > 1: | |
try: | |
shift = int(args[1]) | |
except ValueError: | |
print(f"Invalid shift '{args[1]}'. Using default shift of 3.") | |
shift = 3 | |
else: | |
shift = 3 | |
ciphertext = caesar_encrypt(plaintext, 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