Encrypt Letters with a Caesar Cipher Script

Alright, are you ready to write a script that does what you just did by hand? 

Before getting started, think about this set of steps as a conversion between by-hand to pseudo code for programming.

  1. Store the key in a variable
  2. Store the plaintext letter you are starting with in a variable
  3. Create an alphabet
  4. Find the index of that plaintext letter in the alphabet
  5. Add the key to the index
  6. Find and store the ciphertext letter at the new index

Now let's go!

Find a Character

A script that does the Caesar cipher has to start by finding a character in an alphabet.  In this example, you will write a script that creates an alphabet string and finds the index of a certain character.  In other words, it will tell you that A has an index of 0, B has an index of 1, and so on, up through Z, which has an index of 25.

Example script: find_letter_in_alphabet

# find_letter_in_alphabet

from microbit import *

sleep(1000)

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

letter = "M"
index = alpha.find(letter)

print("letter =", letter, "index =", index)
print()

When the script runs, the terminal should print index = 12 since that is the index of M in the string alpha.

  • If it's not already open, click Show serial to open the serial monitor.
    (See Use the Serial Monitor.)
  • Verify that it displays:

    letter = M , index = 12
  • Change letter = "M" to letter = "D".
  • Flash the modified script.
  • Verify that the terminal displays:

     letter = D , index = 3
  • Repeat this process for "A", "B", "Y", and "Z".

How find_letter_in_alphabet Works

Every cipher begins with an alphabet, so the script starts by creating a string named alpha, which contains all the uppercase letters in the alphabet.  

alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

The .find() method is something available to each string in Python. .find() searches the string for whatever text is passed to it from inside the parentheses, and it returns the index where the text is first located.  Remember that the index numbers in a string start at zero.  So, the first character A has an index of 0, B has an index of 1, and so on, through Z with an index of 25.  In this counting system, M has an index of 12 in the alpha string.  So, letter = "M" followed by alpha.find(letter) returns 12.


“…and now, for something completely different!” 

You might have already experimented with the .find method in Try This: Find the Substring.  It had examples of finding the starting index values of words like "Arthur" and "run", and even used the index to decide what to do next.  In this encryption example, the alpha string’s .find() method is instead used to locate a single letter within a string.