Why move the Caesar cipher routine to a function? One advantage would be that you can swap it out with other, better encryption functions, or even function/method calls to a module. As an example, in the next activity, you will replace the caesar function with another one called ascii_shift. After the function swap, your script will only need one line changed!
Example script: caesar_cipher_function
- Enter caesar_cipher_function into the micro:bit Python Editor.
- Set the project's name to caesar_cipher_function.
- Click Save.
- Click the Send to micro:bit button.
# caesar_cipher_function from microbit import * ''' Function converts plaintext to ciphertext using key ''' def caesar(key, word): alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" result = "" for letter in word: letter = letter.upper() index = ( alpha.find(letter) + key ) % 26 result = result + alpha[index] return result ''' Script starts from here... ''' sleep(1000) print("Set your keyboard to CAPS LOCK.") print() while True: text = input("Enter key: ") key = int(text) letters = input("Enter character(s) in A...Z range: ") result = caesar(key, letters) print("result:", result) print()
The functionality is identical to the previous example (caesar_terminal_words).
- Open the serial monitor, and follow the prompts.
- Verify that the functionality matches the previous script.
- Take a look at the actual script you have to work with, it’s the part below the ''' Script starts from here... ''' comment.
See how all that script has to do is use result = caesar(key, letters) to encrypt the word?
How It Works
Your script now gets the ciphertext from this one line:
result = caesar(key, word)
The caesar function has two parameters, key and word. Keep in mind that word could also be ciphertext that you are converting back with a negative key value. Inside the function, it does all the same steps as caesar_terminal_words, and then returns the result.
def caesar(key, word): alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" result = "" for letter in word: letter = letter.upper() index = ( alpha.find(letter) + key ) % 26 result = result + alpha[index] return result