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

(vip2019) #1
Conditions (What If?) 99

The Python function to turn a character into its ASCII num-
ber value is ord():

>>> ord('A')
65
>>> ord('Z')
90

The reverse function is chr():

>>> chr(65)
'A'
>>> chr(90)
'Z'

This function turns a numeric value into the corresponding
character.

Our Encoder/Decoder Program


With all these pieces, we can put together a program that takes in
a message and makes it all uppercase. It then loops through each
character in the message and, if the character is a letter, shifts it
by 13 to encode or decode it, adds the letter to an output message,
and prints the output message.
EncoderDecoder.py

message = input("Enter a message to encode or decode: ") # Get a message
u message = message.upper() # Make it all UPPERCASE :)
v output = "" # Create an empty string to hold output
w for letter in message: # Loop through each letter of the message
x if letter.isupper(): # If the letter is in the alphabet (A-Z),
y value = ord(letter) + 13 # shift the letter value up by 13,
z letter = chr(value) # turn the value back into a letter,
{ if not letter.isupper(): # and check to see if we shifted too far
| value -= 26 # If we did, wrap it back around Z->A
} letter = chr(value) # by subtracting 26 from the letter value
~ output += letter # Add the letter to our output string
print("Output message: ", output) # Output our coded/decoded message


The first line prompts the user for an input message to
encode or decode. At u, the upper() function makes the message
all uppercase to make the letters easier for the program to read
and to make the encoding simpler to write. At v, we create an
empty string (nothing between the double quotes, "") named output,
Free download pdf