Search code examples
pythoncaesar-cipher

Encryption of an input with Caesar Cipher in Python


I have to write this code where The function must receive a path to a text file which must contain text composed of only English letters and punctuation symbols and a destination file for encrypted data. Punctuation symbols must be left as they are without any modification and the encrypted text must be written to a different file. Also, I have to validate the inputs.

I've done most of it but in the first part, where I have to ask for a text, the code isn't accepting spaces or punctuation marks, and as I gather it's because of .isalpha, however I couldn't find a way to fix it.

I'm not sure if I have completed the aforementioned requirements, so any type of feedback / constructive criticism is appreciated.

  while True:   #  Validating input text
    string = input("Enter the text to be encrypted: ")
    if not string.isalpha():
        print("Please enter a valid text")
        continue
    else:
        break
while True:  #  Validating input key
    key = input("Enter the key: ")
    try:
        key = int(key)
    except ValueError:
        print("Please enter a valid key: ")
        continue
    break


def caesarcipher(string, key):   #  Caesar Cipher
    encrypted_string = []
    new_key = key % 26
    for letter in string:
        encrypted_string.append(getnewletter(letter, new_key))
    return ''.join(encrypted_string)


def getnewletter(letter, key):
    new_letter = ord(letter) + key
    return chr(new_letter) if new_letter <= 122 else chr(96 + new_letter % 122)


with open('Caesar.txt', 'a') as the_file:  # Writing to a text file
    the_file.write(caesarcipher(string, key))

print(caesarcipher(string, key))
print('Your text has been encrypted via Caesar-Cipher, the result is in Caesar.txt')

Solution

  • Well, you could check it "manualy".

    # ____help_function____
    def check_alpha(m_string):
       list_wanted = ['!', '?', '.', ',']
    
       for letter in m_string:
          if not (letter in list_wanted or letter.isalpha()):
             return False
    
       return True
    
    # ____in your code____
    while True:
       string = input("Enter the text to be encrypted: ")
    
       if check_aplha(string):
          break
       else:
          print('....')