52 CHAPTER4. COMPUTINGWITHSTRINGS
Supposeyouarewritinga computersystemfora bank.Yourcustomerswouldnotbetoohappy tolearn
thata checkwentthroughforanamount“verycloseto $107.56.” They wanttoknow thatthebankis keeping
precisetrackoftheirmoney. Eventhoughtheamountoferrorina givenvalueis verysmall,thesmallerrors
canbecompoundedwhendoinglotsofcalculations,andtheresultingerrorcouldadduptosomerealcash.
That’s nota satisfactorywayofdoingbusiness.
Abetterapproachwouldbetomake surethatourprogramusedexactvaluestorepresentmoney. We
candothatbykeepingtrackofthemoney incentsandusinganint(orlongint)tostoreit. We canthen
convertthisintodollarsandcentsintheoutputstep.Iftotalrepresentsthevalueincents,thenwecan
getthenumberofdollarsbytotal / 100andthecentsfromtotal % 100. Bothoftheseareinteger
calculationsand,hence,willgive usexactresults.Hereis theupdatedprogram:
change2.py
A program to calculatethe value of some change in dollars
This version representsthe total cash in cents.
def main():
print "Change Counter"
print
print "Please enterthe count of each coin type."
quarters = input("Quarters:")
dimes = input("Dimes:")
nickels = input("Nickels:")
pennies = input("Pennies:")
total = quarters 25 + dimes 10 + nickels * 5 + pennies
print
print "The totalvalue of your change is $%d.%02d" \
% (total/100,total%100)
main()
I have splitthefinalprintstatementacrosstwo lines.Normallya statementendsat theendoftheline.
Sometimesit is nicertobreaka longstatementintosmallerpieces.Abackslashattheendofa lineis one
waytoindicatethata statementis continuedonthefollowingline.Noticethatthebackslashmustappear
outsideofthequotes;otherwise,it wouldbeconsideredpartofthestringliteral.
Thestringformattingintheprintstatementcontainstwo slots,onefordollarsasanintandoneforcents
asanint.Thisexamplealsoillustratesoneadditionaltwistonformatspecifiers.Thevalueofcentsis printed
withthespecifier%02d. ThezeroinfrontofthewidthtellsPythontopadthefield(ifnecessary)withzeroes
insteadofspaces.Thisensuresthata valuelike 10dollarsand5 centsprintsas$10.05ratherthan$10.
5.
4.5 FileProcessing
I beganthechapterwitha referencetoword-processingasanapplicationofthestringdatatype.Onecritical
featureofany wordprocessingprogramis theabilitytostoreandretrieve documentsasfilesondisk.Inthis
section,we’ll take a lookatfileinputandoutput,which,asit turnsout,is reallyjustanotherformofstring
processing.
4.5.1 Multi-LineStrings
Conceptually, a fileis a sequenceofdatathatis storedinsecondarymemory(usuallyona diskdrive).Files
cancontainany datatype,buttheeasiestfilestoworkwitharethosethatcontaintext. Filesoftexthave
theadvantagethatthey canbereadandunderstoodbyhumans,andthey areeasilycreatedandeditedusing
general-purposetexteditorsandwordprocessors.InPython,textfilescanbeveryflexible,sinceit is easyto
convertbackandforthbetweenstringsandothertypes.