Python Programming: An Introduction to Computer Science

(Nora) #1
4.3.STRINGSANDSECRETCODES 43

month number position
Jan 1 0
Feb 2 3
Mar 3 6
Apr 4 9

Ofcourse,thepositionsallturnouttobemultiplesof3. To getthecorrectmultiple,wejustsubtract 1
fromthemonthnumberandthenmultiplyby3.Sofor1 weget


^1 ^1  ^3 ^0 ^3 0 andfor^12 wehave
12  1  3 11 3 33
Now we’re readytocodetheprogram.Again,thefinalresultis shortandsweet;thecommentsdocument
thealgorithmwe’ve developed.


month.py


A program to printthe abbreviation of a month, given its number


def main():


months is usedas a lookup table


months = "JanFebMarAprMayJunJulAugSepOctNovDec"


n = input("Entera month number (1-12): ")

# compute startingposition of month n in months
pos = (n-1) * 3

# Grab the appropriateslice from months
monthAbbrev = months[pos:pos+3]

# print the result
print "The monthabbreviation is", monthAbbrev + "."

main()


Noticethelastlineofthisprogramusesstringconcatenationtoputa periodat theendofthemonthabbrevi-
ation.
Hereis a sampleofprogramoutput.


Enter a month number(1-12): 4
The month abbreviationis Apr.


4.3 StringsandSecretCodes


4.3.1 StringRepresentation.


Hopefully, youarestartingtogetthehangofcomputingwithtextual(string)data.However, youmightstill
bewonderinghow computersactuallymanipulatestrings.Inthepreviouschapter, yousawhow computers
storenumbersinbinarynotation(sequencesofzerosandones);thecomputerCPUcontainscircuitrytodo
arithmeticwiththeserepresentations.Textualinformationis representedinexactlythesameway. Under-
neath,whenthecomputeris manipulatingtext,it is reallynodifferentfromnumbercrunching.
To understandthis,youmightthinkintermsofmessagesandsecretcodes.Considertheage-oldgrade
schooldilemma.Youaresittinginclassandwanttopassa notetoa friendacrosstheroom.Unfortunately,
thenotemustpassthroughthehands,andinfrontofthecuriouseyes,ofmany classmatesbeforeit reaches
itsfinaldestination.And,ofcourse,thereis alwaystheriskthatthenotecouldfallintoenemyhands(the
teacher’s).Soyouandyourfriendneedtodesigna schemeforencodingthecontentsofyourmessage.
Oneapproachis tosimplyturnthemessageintoa sequenceofnumbers. Youcouldchoosea number
tocorrespondtoeachletterofthealphabetandusethenumbersinplaceofletters. Withouttoomuch

Free download pdf