Required for the AP Exam for this course, my project was a simple Caesar cipher that functions through a CLI. It references a pair of lists representing the alphabet, indexing them to get a shift value for encryption.
After entering an input and shift value, the program “encrypts” the text by way of a Caesar cipher. It supports 26 alphabetic characters of the English alphabet. Unsupported characters are passed through and output unchanged.
The cipher calls back to two functions:
mainandc_ciph, controlling the interface and the functionality respectively. The two lists initialized are the basis of the cipher, the alphabet in both uppercase and lowercase. The program calls back tomain, where a forever loop is initialized. The program takes the needed inputs and calls back toc_ciphfor the output. Depending on the values given toc_ciph, it will either encrypt or decrypt, passing non alphabetical characters. It indexes the lists, using the shift values to determine new values for every non-encrypted character. Once the new string is “built”, it is printed for the user to view. The loops repeats for a new selection. Selecting “Q” from the interface breaks the loop and quits the program.
In the future, alphabetical lists can be consolidated among other small efficiency improvements, as there are some redundant elements in retrospect. Overall, I am still proud of this program, and only notice these issues after practicing.
Program Code
import string
a = list(string.ascii_lowercase)
aa = list(string.ascii_uppercase)
def c_ciph(text, shift, encrypt=True):
result = []
for char in text:
if char.isalpha():
shift_am = int(shift if encrypt else -shift)
tshift = ()
if char.isupper(): letter = aa
else: letter = a
if letter.index(char) + shift_am > 25:
tshift = ((letter.index(char) + shift_am) - 26)
else:
tshift = (letter.index(char) + shift_am)
result.append(letter[tshift])
else:
result.append(char)
return ''.join(result)
def main():
while True:
sel = input("\n(E) Encrypt a message\n(D) Decrypt a message\n(Q) Quit the program\n").strip().upper()
if sel == 'E' or sel == 'D':
t = input("\nEnter the text: ")
s = int(input("\nEnter the shift amount: "))
res = c_ciph(t, s, True if sel == 'E' else False)
print('\nEncrypted ' if sel == 'E' else '\nDecrypted ', f"text is: {res}")
elif sel == 'Q':
print('Quitting...')
break
main()