I'm a beginner in Python. I wrote this code which encrypts and decrypts text using Caesar chipher. I wrote it in many days and optimized it many times. But how it can be improved more?
I've used lists because they are flexible and they serve my algorithm.
print('''# This is version 1.0 Caesar Encryption-Decryption Tool.
# This tool is written by Mahmoud Naguib and it will be improved.
# You can contact me at : https://www.facebook.com/naguibarea
-----------------------------------------------------------------''')
letters_table = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q',
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
def caesar():
# This line iterates through every letter in the string.
for letter in range(len(text)):
# If there is a letter which isn't an English alphabet.
if not text[letter].isalpha():
letters_table.append(text[letter])
# This line locates the letter's numeric value in other words its position.
position = letters_table.index(text[letter])
# This line adds the key entered by the user to the letter's
# numeric value to reach the new letter.
step = position + key
# if the encrypted letter's numeric value is greater than 25
# then its new numeric value is the old numeric valuu %
# the number of English alphabet letters.
if step > 25:
step %= 26
# If step is lower than 0 then we need to add 26 to it to complete the decryption process.
if step < 0:
step += 26
# If position is greater than 25 that means it's not an alphabet
# value and it will be printed without adding the key(the letter will be printed as it is).
if position > 25:
step = position
# This line locates the letter's numeric value(its position) and prints the new letter.
# end is a keyword argument to combine all letters together.
print(letters_table[step], end='')
print('\n' + '-----------------------------------------------------------------')
while True:
while True:
# This line ask the user if he wants to encrypt or decrypt a text.
mode = input('Type E for enryption mode or D for decryption mode : ').upper()
if mode == 'D' or mode == 'E':
break
else:
print('You must enter E or D ! ')
# This line takes the user's text and converts it to uppercase to search for it in the letter's table.
while True:
text = input('Enter your text : ').upper()
if len(text) != 0:
break
else:
print('You can not leave it blank ! ')
while True:
try:
# This line takes the user's key.
key = int(input('Enter a key : '))
if type(key) == int:
break
except ValueError:
print('You must enter an integer number ! ')
# If the user wants to encrypt a text it will call the caesar() function.
if mode == 'E':
caesar()
# If the user wants to decrypt a text it will make the key value negative so that there's a reverse process
# and it will call the caesar() function.
elif mode == 'D':
key = 0 - key
caesar()