The scrambled alphabet cipher has two arguments, text and encrypt. In this case, the cipher accepts upper-case characters or words. The encrypt argument accepts True or False. True encrypts, and False decrypts. Inside the function, there is an alphabet, and a cryptabet. The cryptabet is a scrambled version of the alphabet. It also has an empty result string that will be used to build the encryption result.
# Scrambled alphabet cipher. def scramble(text, encrypt): alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" crypta = "PTQGMKCRSVEXADZBJFOWYNIHLU" result = ""
This step is only performed if the function is called with the encrypt argument set to False. When the function encrypts, it uses alpha and crypta as declared above. When it decrypts, alpha has to store "PTQGMKCRSVEXADZBJFOWYNIHLU" and crypta has to store "ABCDEFGHIJKLMNOPQRSTUVWXYZ". So if encrypt is False, the statements below and indented shuffle the two strings. It does so by copying the alpha string into temp, then copying the crypta into alpha. Lastly, temp — which contains the original alpha — gets copied to crypta.
if encrypt is False: temp = alpha alpha = crypta crypta = temp
The encryption loop starts by making sure the letter is upper case with letter = letter.upper(). Then, it finds the index of the letter in alpha with index = alpha.find(letter). Finally, it looks up the letter with that index in the cryptabet and appends the string result with result = result + crypta[index].
for letter in text: letter = letter.upper() index = alpha.find(letter) result = result + crypta[index] return result # The script starts executing statements from here.
The script starts executing statements here, with the usual sleep(1000) and a message to set your keyboard to CAPS LOCK.
sleep(1000) print("Set your keyboard to CAPS LOCK.") print()
Inside the main loop, an input statement prompts you to type a CAPS LOCK word and stores the result in a variable named text. Then, result = scramble(text, True) encrypts the text you typed and stores it in a variable named result, which gets printed.
while True: text = input("Enter a CAPS LOCK string: ") result = scramble(text, True) print("scrambled result =", result)
Next, result = scramble(result, False) decrypts the string, and the last print statement displays the original text you entered.
result = scramble(result, False) print("unscrambled result =", result)