Goals
- Practice writing functions.
- Practice manipulating strings.
Background
The Caesar cipher
is a very simple way of creating encrypted messages. The original cipher, traditionally attributed
to Julius Caesar, involves shifting every letter in a plaintext message
3 positions further down in the alphabet to get the
corresponding ciphertext message. For example, a Q in the plaintext message would be
shifted by three postions to become a T in the ciphertext.
A plaintext message of "YAK AND ZEBRA"
would be transformed to the ciphertext message "BDN DQG CHEUD". Note that letters near
the end of the alphabet wrap around to the beginning (e.g. Y + 3 = B).
You can, of course, perform a Caesar cipher transformation using other values than
3 for the shift. "YAK AND ZEBRA" with a shift of 4, for example, becomes
"CEO ERH DIFVE".
In this assignment, you will write two functions that implement
encryption and decryption using the Caesar cipher. This will give you some
practice encapsulating a collection of operations into Python functions.
Your task
Write a program that:
- asks the user for an integer (the Caesar shift value)
and a string (the plaintext)
- calls a function named caesar_encrypt (see below for details) to obtain
the ciphertext
- prints the ciphertext
- calls a function named caesar_decrypt to obtain the plaintext
from the ciphertext
- prints the plaintext
Your functions should look like this:
def caesar_encrypt(shift, plaintext):
''' Returns the ciphertext obtained by transforming every letter
in the plaintext by a Caesar cipher by the specified shift.
Non-letter characters should remain unchanged in the ciphertext. '''
[Your code goes here]
return [something]
def caesar_decrypt(shift, ciphertext):
''' Returns the plaintext from which the ciphertext was obtained,
assuming the ciphertext came from a Caesar Cipher encryption
using the specified shift. In short, caesar_decrypt should undo
the work done by caesar_encrypt. As with caesar_encrypt, non-letter
characters should remain unchanged.
[Hint: you can write this function in two main ways. One way is that you
could essentially mimic caesar_encrypt, but with a small change
in the code. But alternatively, you could make this function very
short by cleverly calling caesar_encrypt. Either approach is fine.] '''
[Your code goes here]
return [something]
A typical session with your completed program might look like this:
$ python3 caesar.py
What is your plaintext? follow the elk
What shift do you want to use? 3
Your ciphertext is: iroorz wkh hon
Your plaintext was: follow the elk
$
Some ideas
- To step one character at a time through a string, see the
sample from the loops and functions lab.
- To shift a letter to another letter by some integer amount, you
will need to use the Python functions "ord" and "chr", which are described
in Chapter 5 of your textbook (assuming you have the
3rd edition), starting on page 140.
Start early, ask questions, and have fun!