Nov-21-2020, 12:05 PM
(Nov-21-2020, 09:55 AM)Larz60+ Wrote: FYI: Whenever you need a string of uppercase letters you can usestring.ascii_uppercase
string.ascii_lowercase
for lower case
Example:
>>> import string >>> LETTERS = string.ascii_uppercase >>> LETTERS 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' >>> LETTERS = string.ascii_lowercase >>> LETTERS 'abcdefghijklmnopqrstuvwxyz'
(Nov-21-2020, 07:31 AM)bowlofred Wrote: That's a lot of work your program is doing....
1) LETTERS has only uppercase contents. Hello only has one uppercase letter, so that's the only one modified. If you instead feed in "HELLO", all the letters will be translated.
Thank you both for your clarification. Where I declared
LETTERS
originally, I used all upper case letters typed by hand. I changed that line so my LETTERS now reads: LETTERS = string.ascii_letters
which provides the full english alphabet (upper case and lower case).With those changes, here is my script in full:
# Second sample code from Tutorials Point: https://www.tutorialspoint.com/cryptography_with_python/cryptography_with_python_caesar_cipher.htm import string message = 'Hello World' #encrypted message LETTERS = string.ascii_letters def encrypt(message, LETTERS): for key in range(len(LETTERS)): translated = '' for character in message: if character in LETTERS: num = LETTERS.find(character) num = num - key if num < 0: num = num + len(LETTERS) translated = translated + LETTERS[num] else: translated = translated + character return translated print(f"Encrypted message : {encrypt(message, LETTERS)}")
Quote:2) You're actually translating the string 26 times (that's the outer loop) and only printing out the last one. Rather than looping with key set to a lot of different things, you could just set it to 25 and then run the inner loop once (since you throw away all the other translations).
I’m not sure I completely understand your suggestion but I also don’t fully understand how or why my script runs the way it does.
When I run my script, the output I am expecting and actual output matches:
$ python script.py Encrypted message : Ifmmp XpsmeUsing the VS Code debugger, I see that the two for loops generate a cipher many, many times over and over, what seems like almost perpetually. It seems to go on forever.
Why does the final translated output characters shifted to the right by one variance when I don’t specify a variance?
If I wanted to rotate 3 characters instead of 1, where in my script should I specify that? Usually the variance is specified by the person doing the encrypting, typically as a parameter / argument in the function.
Is there a better, more efficient approach to a Caesar cipher in Python that you people might recommend so that the script performs 1 translation instead of going all the way through 25?