Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1

100 Chapter 5


in which we’ll store our encoded message, letter by letter. The for
loop at w makes use of the fact that Python treats strings like col-
lections of characters; the variable letter will iterate over, or loop
through, the string message one character at a time.
At x, the isupper() function checks each character in the mes-
sage to see if it’s an uppercase letter (A to Z). If it is, then at y we
get the numeric value of the letter in ASCII using ord() and add
13 to that value to encode it. At z, we turn the new, encoded value
back into a character with chr(), and at {, we check to see if it’s
still a letter from A to Z. If not, we wrap the letter back around to
the front of the alphabet at | by subtracting 26 from the encoded
value (that’s how Z becomes an M), and we turn the new value into
its letter equivalent in }.
At ~, we add the letter to the end of the output string (append-
ing the character onto the end of the string) using the += operator.
The += operator is one of a handful of shortcut operators that
combine math (+) and assignment (=), and output += letter means
output gets letter added to it. This is the last line in our for loop, so
the whole process is repeated for each character in the input mes-
sage until output has been built up one letter at a time to hold the
encoded version of the entire message. When the loop is finished,
the last line of the program prints the output message.
You can use this program to
send coded messages for fun, but
you should know that it’s not as
secure as modern ways of encoding
messages—anyone who can solve
a puzzle in the Sunday paper can
read the encoded messages you’ve
sent—so use it only for fun with
friends.
Do a web search for encryption
or cryptography to learn about the
science of making secret messages
secure.
Free download pdf