Write a Python function to perform a shift (Caesar) cipher.
Write a Python function to perform a shift (Caesar) cipher.
One of the earliest ways that people encrypted information was the shift cipher, also known as the Caesar cipher (after Julius Caesar, who apparently did use the cipher to protect his correspondance across the Roman Empire). In this cipher, each character in a string is replaced by a shifted version of itself. For example, with a shift of 3 (the value Julius Caesar apparently used) the letter "H" can be replaced by "K", "E" can be replaced by "H", "L" by "O", etc.:
Given what we learned in lecture 7 about chr()
and ord()
and lectures 14, 15 and 16
about defining functions, design a Python function called shift
that will:
-
accept a string
plaintext
and an integerkey
as parameters (in that order), wherekey
has a default argument of 3, -
shift each A–Z and a–z character in the plaintext by the number of spaces specified by the key, leaving all other characters (e.g., space) alone and
-
return the resulting ciphertext string.
I would suggest that you:
-
start by assuming that you only need to worry about upper-case characters A–W with
shift=3
, -
then consider how to handle letters at the end of the alphabet,
-
only add more cases (lower-case a–z, "special" characters like space and punctuation) after the above works correctly,
-
come up with simple test cases using rot13.com and
-
only convert your algorithm into Python after convincing yourself that it works on paper.
Submit your work in a file called cipher.py
.
As always, please don’t hesitate to contact me if you have questions! Also as always, remember that assignments are individual work.