Python Programming: An Introduction to Computer Science

(Nora) #1
4.3.STRINGSANDSECRETCODES 45

Finally, weneedto converteachcharacterto a number. Thesimplestapproachis to usetheASCIInumber
(providedbyord) foreachcharacterinthemessage.
Hereis thefinalprogramforencodingthemessage:


text2numbers.py


A program to converta textual message into a sequence of


numbers,utlilizing the underlying ASCII encoding.


def main():
print "This programconverts a textual message into a sequence"
print "of numbersrepresenting the ASCII encoding of the message."
print


# Get the messageto encode
message = raw_input("Please enter the message to encode: ")

print
print "Here are theASCII codes:"

# Loop throughthe message and print out the ASCII values
for ch in message:
print ord(ch), # use comma to print all on one line.

print

main()


We canusetheprogramtoencodeimportantmessages.


This program convertsa textual message into a sequence
of numbers representingthe ASCII encoding of the message.


Please enter the messageto encode: What a Sourpuss!


Here are the ASCIIcodes:
87 104 97 116 32 97 32 83 111 117 114 112 117 115 115 33


Onethingtonoticeaboutthisresultis thateventhespacecharacterhasa correspondingASCIIcode.It is
representedbythevalue32.


4.3.3 Programminga Decoder


Nowthatwehave a programtoturna messageintoa sequenceofnumbers,it wouldbeniceif ourfriend
ontheotherendhada similarprogramtoturnthenumbersbackintoa readablemessage.Let’s solve that
problemnext.Ourdecoderprogramwillprompttheuserfora sequenceofnumbersrepresentingASCII
codesandthenprintoutthetextmessagecorrespondingtothosecodes. Thisprogrampresentsuswitha
coupleofchallenges;we’ll addresstheseaswegoalong.
Theoveralloutlineofthedecoderprogramlooksverysimilartotheencoderprogram. Onechangein
structureis thatthedecodingversionwillcollectthecharactersofthemessageina stringandprintoutthe
entiremessageattheendoftheprogram.To dothis,weneedtouseanaccumulatorvariable,a patternwe
saw inthefactorialprogramfromthepreviouschapter. Hereis thedecodingalgorithm:


get the sequence of numbersto decode
message = ""
for each number in theinput:
convert the numberto the appropriate character

Free download pdf