Hacking Secret Ciphers with Python

(Ann) #1
Chapter 6 – The Caesar Cipher 75

Like all conventions, we don’t have to follow it. But doing it this way makes it easier for other
programmers to understand how these variables are used. (It even can help you if you are looking
at code you wrote yourself a long time ago.)


The upper() and lower() String Methods


caesarCipher.py



  1. stores the encrypted/decrypted form of the message



  2. translated = ''




  3. capitalize the string in message



  4. message = message.upper()


On line 19, the program stores a blank string in a variable named translated. Just like in the
reverse cipher from last chapter, by the end of the program the translated variable will
contain the completely encrypted (or decrypted) message. But for now it starts as a blank string.


Line 22 is an assignment statement that stores a value in a variable named message, but the
expression on the right side of the = operator is something we haven’t seen before:
message.upper().


This is a method call. Methods are just like functions, except they are attached to a non-module
value (or in the case of line 22, a variable containing a value) with a period. The name of this
method is upper(), and it is being called on the string value stored in the message variable.


A function is not a method just because it is in a module. You will see on line 52 that we call
pyperclip.copy(), but pyperclip is a module that was imported on line 4, so copy() is
not a method. It is just a function that is inside the pyperclip module. If this is confusing, then
you can always call methods and functions a “function” and people will know what you’re
talking about.


Most data types (such as strings) have methods. Strings have a method called upper() and
lower() which will evaluate to an uppercase or lowercase version of that string, respectively.
Try typing the following into the interactive shell:





'Hello world!'.upper()
'HELLO WORLD!'
'Hello world!'.lower()
'hello world!'




Free download pdf