Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1
Conditions (What If?) 95

s cret Messages e


Now that we understand how to use conditions, we’re going to
learn to encode and decode secret messages using a Caesar cipher.
A cipher is a secret code, or a way of changing messages to make
them harder to read. The Caesar cipher is named after Julius
Caesar, who is said to have liked sending private messages by
shifting letters in the alphabet:

SECRET MESSAGES ARE SO COOL! -> FRPERG ZRFFNTRF NER FB PBBY!

We can create a simple Caesar cipher by using an encoder ring
like the one shown in Figure 5-7. To create the encoded message,
decide on the key, or the number of letters you want to shift each let-
ter by. In the coded message and in Figure 5-7, each letter is being
shifted by a key value of 13 , meaning we take the letter we want
to encode and count 13 letters past it in
the alphabet to get our encoded letter.
An A becomes an N, a B becomes an O,
and so on.
We sometimes call this shift a
rotation because by the time we get to
M (which becomes Z), we’re at the end
of the alphabet. To be able to encode an
N, we wrap around to A again. O wraps
around to B, all the way to Z, which
becomes an M. Here’s an example of a
Caesar cipher lookup table for the key
value of 13 , where each letter is shifted
by 13 letters for encoding or decoding:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
N O P Q R S T U V W X Y Z->A B C D E F G H I J K L M

Notice a pattern? The letter A is encoded as an N, and N is
encoded as an A. We call this a symmetric cipher or symmetric code
because it has symmetry—it’s the same in both directions. We can
encode and decode messages using the same key of 13 because the
English alphabet has 26 letters, and the key value of 13 means that
we shift every letter exactly halfway around. You can try it with a
message of your own: HELLO -> URYYB -> HELLO.

ABC
D E F G H I J K

QPONML

R

S

T

U

V

W

X
YZ

CBA

ED

F

G

H

I
J
KL

MNOPQ
R
S
T
U
V
XW
ZY

Figure 5-7: A Caesar cipher
Free download pdf