CS 100

Logo

Scientific Computing

Activity 13 - The Caesar cipher & practice with strings

Encryption often involves the Caesar cipher - named after Julius Caesar, who used the system to encrypt military messages. Many early internet users also adopted this cipher. Called rot13, the cipher encrypts a message by rotating the plaintext character by 13 positions in the alphabet. For example, “a” becomes “n” and likewise “n” becomes “a”. The nice thing about rot13 is that the same function can be used to encrypt and decrypt a message!

  1. Create a file called caesar.py. Write a function called rot13 that takes a message as a parameter and rotates all alphabet characters by 13 places and preserves whitespace characters.
    def rot13(msg):
       # your code here
       result = ""
       
       return result
    
  2. Use your function to decrypt the following message: "lbh ner n fhcre pbby pbqr oernxvat clguba cebtenzzre". Print the decrypted message.

  3. Create an encrypted message of your own with the Caesar cipher. Decrypt your encrypted message.

More practice with strings

  1. Write code that will take input from the user (typed into the Shell), and displays that input back in upper and lower cases.

  2. Write a python function isPalindrome(myString) to return True or False based on whether myString is a palindrome. A palindrome is a string such as "racecar" which is the same forwards as it is backwards. For example:
    print(isPalindrome("racecar")) # prints True
    print(isPalindrome("madam")) # prints True
    print(isPalindrome("yourname")) # prints False
    
  3. Test your isPalindrome function also handles spaces. You may need to update your implementation to do so. For example
    print(isPalindrome("a man a plan a canal panama")) # prints True
    print(isPalindrome("never odd or even")) # prints True
    print(isPalindrome("your name")) # prints False
    

If you finish early

  1. Write a function alternatingText(myString) which will return the given string with alternating upper and lowercase letters. For example, alternatingText("Here is a cute dog") would return “HeRe iS A CuTe dOg”.

  2. Can you come up with another cipher which, like the Ceaser cipher, uses the same function to encrypt and decrypt a message?

How to submit

Submit your working caesar.py to Moodle.