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

(vip2019) #1

96 Chapter 5


If we can write a program that looks at each letter in a secret
message, then encodes that letter by shifting it 13 letters to the
right, we can send encoded messages to anyone who has the same
program (or who can figure out the pattern in the cipher). To write
a program that manipulates individual letters in a string, we need
to pick up more skills for working with strings in Python.

Messin’ with Strings


Python comes with powerful functions for working with strings.
There are built-in functions that can change a string of characters
to all uppercase, functions that can change single characters into
their number equivalents, and functions that can tell us whether a
single character is a letter, number, or other symbol.
Let’s start with a function to change a string to uppercase let-
ters. To make our encoder/decoder program easier to understand,
we’re going to change the message to all uppercase so that we’re
encoding only one set of 26 letters (A to Z) instead of two (A to Z
and a to z). The function that converts a string to all uppercase let-
ters is upper(). Any string followed by the dot (.) and the function
name upper() will return the same string with letters in uppercase
and other characters unchanged. In the Python shell, try typing
your name or any other string in quotes, followed by .upper(), to
see this function in action:

>>> 'Bryson'.upper()
'BRYSON'
>>> 'Wow, this is cool!'.upper()
'WOW, THIS IS COOL!'

As we saw earlier, the lower() function does the opposite:

>>> 'Bryson'.lower()
'bryson'

You can check to see whether a single character is an upper-
case letter with the isupper() function:

>>> 'B'.isupper()
True
>>> 'b'.isupper()
False
>>> '3'.isupper()
False
Free download pdf