Caesar Cipher Validation
Solution 1:
If you just want to allow alpha characters:
defgetMessage():
whileTrue:
message = input('Enter your message: ')
if message.isalpha():
return message
print("Invalid input, text must contain alphabetic characters only.")
To allow spaces and letters:
if all(ch.isalpha() or ch.isspace() for ch in message):
return message
A dict and using modulo is going to be a much more concise approach:
defget_mode():
whileTrue:
mode = input('Do you wish to encrypt(e) or decrypt(d) a message: ').lower()
if mode.lower() in {"e","d"}:
return mode
print('Enter either "encrypt" or "e" or "decrypt" or "d".')
defget_message():
whileTrue:
message = input('Enter your message: ')
ifall(ch.isalpha() or ch.isspace() for ch in message):
return message
print("Invalid input, text must contain alphabetic characters only.")
defget_key():
return5from string import ascii_letters
d = {k: i for i, k inenumerate(ascii_letters)}
enc = ascii_letters
defget_translated_message(mode, message, key):
if mode == "e":
return"".join([enc[(d[ch] + key) % 52] ifnot ch.isspace() else ch for ch in message])
return"".join([enc[(d[ch] - key) % 52] ifnot ch.isspace() else ch for ch in message])
Just run it the same way:
mode = get_mode()
message = get_message()
key = get_key()
print('Your translated text is: ', get_translated_message(mode, message, key))
Solution 2:
You mentioned you want to return an error if the user enters something like '123'. Based off of that requirement, the problem in your code is right here:
You are doing this check:
if symbol.isalpha():
Which will check if something is of alpha: A-Z
Therefore, in your else, you want to return your error when the alpha check fails:
So when you do this:
else:
translated += symbol
You want this:
else:
return"input invalid"
However, again, focusing on your code, this brings up another problem. You need to change how you are handling the return of your method, so the output makes more sense. You might want to consider something like this:
mode = getMode()
message = getMessage()
key = getKey()
result = getTranslatedMessage(mode, message, key)
if not result:
print("invalid")
else:
print('Your translated text is: ', result)
Based on recent updates, you are looking to preserve whitespace. Therefore, you should consider changing your code to also handle whitespace by simply adding an elif
condition for checking for whitespace and adding ' '
to your translated
variable. So, the code in your for loop would then look like this:
for symbol in message:
if symbol.isalpha():
num = ord(symbol)
num += key
if symbol.isupper():
if num > ord('Z'):
num -= 26elif num < ord('A'):
num += 26elif symbol.islower():
if num > ord('z'):
num -= 26elif num < ord('a'):
num += 26
translated += chr(num)
elif symbol.isspace():
translated += ' 'else:
returnFalse
But Padraic's approach is really good and is definitely worth a look to consider refactoring.
Post a Comment for "Caesar Cipher Validation"