Skip to content

Secret codes

Make a machine that turns messages into secret code, and back again.

Start here: open pygwide. On the home page, choose Tutorials, then Python Toolkit, then Lesson 3: Secret codes.

This lesson takes about an hour. The extensions take about 30 minutes more.

What you will learn

  • How to loop over the letters of a string.
  • How to find a letter's position, and the letter at a position.
  • How to wrap round to the start with %.
  • How to build a new string a letter at a time.

What you need from before

Step 1: Loop over letters

A string is like a list of letters, so a for loop can go through it one letter at a time:

for letter in "hello":
    print(letter)

in also checks whether a letter is in a string:

print("e" in "hello")
print("z" in "hello")

In Scratch

Looping over a string is like using letter 1 of, letter 2 of, and so on, with length of to know when to stop.

Step 2: Letters and positions

Make the alphabet into a string. A name in capitals, such as ALPHABET, tells people it never changes:

ALPHABET = "abcdefghijklmnopqrstuvwxyz"
print(ALPHABET.index("c"))
print(ALPHABET[2])

.index("c") finds where c is: 2, because Python counts from 0. ALPHABET[2] does the opposite, and gives the letter at position 2.

Step 3: Shift a letter

A Caesar cipher moves every letter along the alphabet. With a shift of 3, a becomes d, and b becomes e. But what happens to z? It needs to go back round to the start.

% gives the remainder after dividing. 27 % 26 is 1, so it wraps round, like a clock going past 12:

ALPHABET = "abcdefghijklmnopqrstuvwxyz"
shift = 3
position = ALPHABET.index("z")
new_position = (position + shift) % 26
print(ALPHABET[new_position])

This prints c.

Step 4: The encode function

Now replace your code with a function that codes a whole message. It builds the result one letter at a time, starting from an empty string "". Anything that isn't a letter, such as a space, stays as it is:

ALPHABET = "abcdefghijklmnopqrstuvwxyz"


def encode(message, shift):
    result = ""
    for letter in message.lower():
        if letter in ALPHABET:
            position = ALPHABET.index(letter)
            new_position = (position + shift) % 26
            result = result + ALPHABET[new_position]
        else:
            result = result + letter
    return result

In Scratch

result = result + ALPHABET[new_position] is like using join to stick a letter on the end.

Step 5: Code and decode

After the function, ask for a message and a shift. To decode, shift the other way, with a minus sign:

message = input("Type a secret message: ")
shift = int(input("Choose a shift from 1 to 25: "))
secret = encode(message, shift)
print(f"Your coded message: {secret}")
print(f"Decoded again: {encode(secret, -shift)}")

Send a coded message to a friend, and tell them the shift!

Check your code

# Secret-code machine

ALPHABET = "abcdefghijklmnopqrstuvwxyz"


def encode(message, shift):
    result = ""
    for letter in message.lower():
        if letter in ALPHABET:
            position = ALPHABET.index(letter)
            new_position = (position + shift) % 26
            result = result + ALPHABET[new_position]
        else:
            result = result + letter
    return result


message = input("Type a secret message: ")
shift = int(input("Choose a shift from 1 to 25: "))
secret = encode(message, shift)
print(f"Your coded message: {secret}")
print(f"Decoded again: {encode(secret, -shift)}")

Extensions

Crack the code

What if you don't know the shift? Write a code cracker that tries every shift from 1 to 25, and prints what each one gives. One of them will make sense.

One way to do it
# Code cracker: tries every shift

ALPHABET = "abcdefghijklmnopqrstuvwxyz"


def encode(message, shift):
    result = ""
    for letter in message.lower():
        if letter in ALPHABET:
            position = ALPHABET.index(letter)
            new_position = (position + shift) % 26
            result = result + ALPHABET[new_position]
        else:
            result = result + letter
    return result


secret = input("Type a coded message to crack: ")
for shift in range(1, 26):
    print(f"Shift {shift}: {encode(secret, -shift)}")
print("Can you spot the one that makes sense?")

Code or decode?

Ask the player whether they want to code or decode a message, and use the right shift for each.

Extra bits

Did you know?

Julius Caesar, a Roman general, really did use this code to send secret messages over 2,000 years ago. He used a shift of 3.

Export your project

pygwide keeps your work in this web browser, but club computers can forget it. Press ⇩ Export to save your project as a zip file. Keep it somewhere safe, such as a USB stick or your school drive.

Next time, choose ⇪ Import a project on the home page to carry on with it.