c# display pdf in browser : Add and delete pages in pdf online application SDK tool html wpf windows online python-programming-an-introduction-to-computer-science13-part374

8.3. COMMONLOOPPATTERNS
123
The average of f the e numbers is 46.5
Inthisversion,theuserdoesn
'
thavetocountthedatavalues,buttheinterfaceisstillnotgood.Theuser
willalmostcertainlybeannoyedbytheconstantproddingformoredata.Theinteractiveloophasmanygood
applications;thisisnotoneofthem.
8.3.2 SentinelLoops
Abettersolutiontothenumberaveragingproblemistoemployapatterncommonlyknownasasentinel
loop.Asentinelloopcontinuestoprocessdatauntilreachingaspecialvaluethatsignalstheend.Thespecial
valueiscalledthesentinel. Anyvaluemaybechosenforthesentinel. Theonlyrestrictionisthatitbe
distinguishablefromactualdatavalues.Thesentinelisnotprocessedaspartofthedata.
Hereisageneralpatternfordesigningsentinelloops:
get the first t data a item
while item is s not t the sentinel
process the e item
get the next t data a item
Noticehowthispatternavoidsprocessingthesentinelitem.Thefirstitemisretrievedbeforetheloopstarts.
Thisissometimescalledtheprimingread,asitgetstheprocessstarted. Ifthefirstitemisthesentinel,the
loopimmediatelyterminatesandnodataisprocessed.Otherwise,theitemisprocessedandthenextoneis
read.Thelooptestatthetopensuresthisnextitemisnotthesentinelbeforeprocessingit.Whenthesentinel
isreached,theloopterminates.
Wecanapplythesentinelpatterntoournumberaveragingproblem. Thefirststepistopickasentinel.
Supposeweareusingtheprogramtoaverageexamscores.Inthatcase,wecansafelyassumethatnoscore
willbebelow0.Theusercanenteranegativenumbertosignaltheendofthedata.Combiningthesentinel
loopwiththetwoaccumulatorsfromtheinteractiveloopversionyieldsthisprogram.
# average3.py
def main():
sum = 0.0
count = 0
x = input("Enter r a a number (negative to quit) ) >> > ")
while x >= = 0:
sum = sum m + + x
count = count + 1
x = input("Enter r a a number (negative to o quit) ) >> ")
print "\nThe e average e of the numbers is", sum m / / count
Ihavechangedthepromptsothattheuserknowshowtosignaltheendofthedata.Noticethatthepromptis
identicalattheprimingreadandthebottomoftheloopbody.
Nowwehaveausefulformoftheprogram.Hereitisinaction:
Enter a number r (negative e to quit) >> 32
Enter a number r (negative e to quit) >> 45
Enter a number r (negative e to quit) >> 34
Enter a number r (negative e to quit) >> 76
Enter a number r (negative e to quit) >> 45
Enter a number r (negative e to quit) >> -1
The average of f the e numbers is 46.4
Thisversionprovidestheeaseofuseoftheinteractiveloopwithoutthehassleofhavingtotype“yes”allthe
time.Thesentinelloopisaveryhandypatternforsolvingallsortsofdataprocessingproblems.It
'
sanother
clich´ethatyoushouldcommittomemory.
Add and delete pages in pdf online - insert pages into PDF file in C#.net, ASP.NET, MVC, Ajax, WinForms, WPF
Guide C# Users to Insert (Empty) PDF Page or Pages from a Supported File Format
add page to pdf online; adding page to pdf
Add and delete pages in pdf online - VB.NET PDF Page Insert Library: insert pages into PDF file in vb.net, ASP.NET, MVC, Ajax, WinForms, WPF
Easy to Use VB.NET APIs to Add a New Blank Page to PDF Document
adding page numbers in pdf file; add page pdf
124
CHAPTER8. CONTROLSTRUCTURES,PART2
Thissentinelloopsolutionisquitegood,butthereisstillalimitation. Theprogramcan
'
tbeusedto
averageasetofnumberscontainingnegativeaswellaspositivevalues. Let
'
sseeifwecan
'
tgeneralizethe
programabit. Whatweneedisasentinelvaluethatisdistinctfromanypossiblevalidnumber,positiveor
negative.Ofcourse,thisisimpossibleaslongaswerestrictourselvestoworkingwithnumbers. Nomatter
whatnumberorrangeofnumberswepickasasentinel,itisalwayspossiblethatsomedatasetmaycontain
suchanumber.
Inordertohaveatrulyuniquesentinel,weneedtobroadenthepossibleinputs.Supposethatwegetthe
inputfromtheuserasastring. Wecanhaveadistinctive,non-numericstringthatindicatestheendofthe
input;allotherswouldbeconvertedintonumbersandtreatedasdata. Onesimplesolutionistohavethe
sentinelvaluebeanemptystring. Remember,anemptystringisrepresentedinPythonas""(quoteswith
nospacebetween).Iftheusertypesablanklineinresponsetoaraw
input(justhits
Enter
),Python
returnsanemptystring.Wecanusethisasasimplewaytoterminateinput.Thedesignlookslikethis:
Initialize sum m to o 0.0
Initialize count t to o 0
Input data item m as s a string, xStr
while xStr is s not t empty
Convert xStr r to o a number, x
Add x to sum
Add 1 to count
Input next t data a item as a string, xStr
Output sum / count
Comparingthistothepreviousalgorithm,youcanseethatconvertingthestringtoanumberhasbeenadded
totheprocessingsectionofthesentinelloop.
TranslatingintoPythonyieldsthisprogram:
# average4.py
def main():
sum = 0.0
count = 0
xStr = raw_input("Enter r a a number (<Enter> > to o quit) >> ")
while xStr r != = "":
x = eval(xStr)
sum = sum + x
count = = count t + 1
xStr = raw_input("Enter a number (<Enter> > to o quit) >> ")
print "\nThe e average e of the numbers is", sum m / / count
Thiscodemakesuseofeval(fromChapter4)toconverttheinputstringintoanumber.
Hereisanexamplerun,showingthatitisnowpossibletoaveragearbitrarysetsofnumbers:
Enter a number r (<Enter> > to quit) >> 34
Enter a number r (<Enter> > to quit) >> 23
Enter a number r (<Enter> > to quit) >> 0
Enter a number r (<Enter> > to quit) >> -25
Enter a number r (<Enter> > to quit) >> -34.4
Enter a number r (<Enter> > to quit) >> 22.7
Enter a number r (<Enter> > to quit) >>
The average of f the e numbers is 3.38333333333
Wefinallyhaveanexcellentsolutiontoouroriginalproblem.Youshouldstudythissolutionsothatyoucan
incorporatethesetechniquesintoyourownprograms.
VB.NET PDF Page Delete Library: remove PDF pages in vb.net, ASP.
In order to run the sample code, the following steps would be necessary. Add necessary references: How to VB.NET: Delete Consecutive Pages from PDF.
add a page to a pdf document; add page numbers to pdf
C# PDF Page Delete Library: remove PDF pages in C#.net, ASP.NET
XDoc.PDF enables you to delete PDF page(s) with customized options, including a single page, a series of pages, and random pages to be Add necessary references
add pages to pdf preview; add page number to pdf online
8.3. COMMONLOOPPATTERNS
125
8.3.3 FileLoops
Onedisadvantageofalltheaveragingprogramspresentedsofaristhattheyareinteractive.Imagineyouare
tryingtoaverage87numbersandyouhappentomakeatyponeartheend.Withourinteractiveprogram,you
willneedtostartalloveragain.
Abetterapproachtotheproblemmightbetotypeallofthenumbersintoafile.Thedatainthefilecan
beperusedandeditedbeforesendingittoaprogramthatgeneratesareport. Thisfile-orientedapproachis
typicallyusedfordataprocessingapplications.
BackinChapter4,welookedatreadingdatafromfilesusingthePythonreadlinesmethodandafor
loop.Wecanapplythistechniquedirectlytothenumberaveragingproblem.Assumingthatthenumbersare
typedintoafileoneperline,wecancomputetheaveragewiththisprogram.
# average5.py
def main():
fileName = = raw_input("What t file are the numbers s in? ? ")
infile = open(fileName,'r')
sum = 0.0
count = 0
for line in n infile.readlines():
sum = sum + eval(line)
count = = count t + 1
print "\nThe e average e of the numbers is", sum m / / count
Inthiscode,readlinesreadstheentirefileintomemoryasasequenceofstrings.Theloopvariableline
theniteratesthroughthissequence;eachlineisconvertedtoanumberandaddedtotherunningsum.
Onepotentialproblemwiththiskindoffileprocessingloopisthattheentirecontentsofthefilearefirst
readintomainmemoryviathereadlinesmethod. AsyouknowfromChapter1, , secondarymemory
wherefilesresideisusuallymuchlargerthantheprimarymemory. It
'
spossiblethatalargedatafilemay
notfitintomemoryallatonetime.Inthatcase,thisapproachtofileprocessingwillbeveryinefficientand,
perhaps,notworkatall.
Withverylargedatafiles,itisbettertoreadandprocesssmallsectionsofthefileatatime.Inthecaseof
textfiles,asimpleapproachistoprocessthefileonelineatatime.Thisiseasilyaccomplishedbyasentintel
loopandthePythonreadlinemethodonfiles. Recall,thereadlinemethodgetsthenextlinefroma
fileasastring.Whenwecometotheendofthefile,readlinereturnsanemptystring,whichwecanuse
asasentinelvalue.Hereisageneralpatternforanend-of-fileloopinPython.
line = infile.readline()
while line != = "":
# process s line
line = infile.readline()
Atfirstglance,youmaybeconcernedthatthisloopstopsprematurelyifitencountersanemptylinein
thefile.Thisisnotthecase.Remember,ablanklineinatextfilecontainsasinglenewlinecharacter("
n"),
andthereadlinemethodincludesthenewlinecharacterinitsreturnvalue.Since"
n" != "",theloop
willcontinue.
Hereisthecodethatresultsfromapplyingtheend-of-filesentinellooptoournumberaveragingproblem.
# average6.py
def main():
fileName = = raw_input("What t file are the numbers s in? ? ")
infile = open(fileName,'r')
sum = 0.0
count = 0
C# PDF File & Page Process Library SDK for C#.net, ASP.NET, MVC
File: Split PDF; C# Page: Insert PDF pages; C# Page: Delete PDF pages; C# Read C# Read: PDF Image Extract; C# Write: Insert text into PDF; C# Write: Add Image to
add multi page pdf to word document; add page number to pdf hyperlink
VB.NET PDF Password Library: add, remove, edit PDF file password
passwordSetting.IsAssemble = True ' Add password to PDF file. These two demos will help you to delete password for an encrypted PDF file.
add page number to pdf preview; adding page to pdf
126
CHAPTER8. CONTROLSTRUCTURES,PART2
line = infile.readline()
while line e != = "":
sum = sum m + + eval(line)
count = count + 1
line = infile.readline()
print "\nThe e average e of the numbers is", sum m / / count
Obviously,thisversionisnotquiteasconciseastheversionusingreadlinesandaforloop. Ifthe
filesizesareknowntoberelativelymodest,thatapproachisprobablybetter.Whenfilesizesarequitelarge,
however,anend-of-fileloopisinvaluable.
8.3.4 NestedLoops
Inthelastchapter,yousawhowcontrolstructuressuchasdecisionsandloopscouldbenestedinsideone
anothertoproducesophisticatedalgorithms. Oneparticularlyuseful,butsomewhattrickytechniqueisthe
nestingofloops.
Let
'
stakealookatanexampleprogram.Howaboutonelastversionofournumberaveragingproblem?
Honest,IpromisethisisthelasttimeI
'
llusethisexample.
1
Supposewemodifythespecificationofourfile
averagingproblemslightly. Thistime,insteadoftypingthenumbersintothefileone-per-line,we
'
llallow
anynumberofvaluesonaline.Whenmultiplevaluesappearonaline,theywillbeseparatedbycommas.
Atthetoplevel,thebasicalgorithmwillbesomesortoffile-processingloopthatcomputesarunning
sumandcount.Forpractice,let
'
suseanend-of-fileloop.Hereisthecodecomprisingthetop-levelloop.
sum = 0.0
count = 0
line = infile.readline()
while line != = "":
# update sum m and d count for values in line
line = infile.readline()
print "\nThe average e of f the numbers is", sum / / count
Nowweneedtofigureouthowtoupdatethesumandcountinthebodyoftheloop. Sinceeach
individuallineofthefilecontainsoneormorenumbersseparatedbycommas,wecansplitthelineinto
substrings,eachofwhichrepresentsanumber.Thenweneedtoloopthroughthesesubstrings,converteach
toanumber,andaddittosum.Wealsoneedtoadd1tocountforeachnumber.Hereisacodefragment
thatprocessesaline:
for xStr in string.split(line,","):
sum = sum m + + eval(xStr)
count = count t +1
Noticethattheiterationoftheforloopinthisfragmentiscontrolledbythevalueofline,whichjust
happenstobetheloop-controlvariableforthefile-processingloopweoutlinedabove.
Knittingthesetwoloopstogether,hereisourprogram.
# average7.py
import string
def main():
fileName = = raw_input("What t file are the numbers s in? ? ")
infile = open(fileName,'r')
sum = 0.0
count = 0
line = infile.readline()
while line e != = "":
1
untilChapter11...
VB.NET PDF insert image library: insert images into PDF in vb.net
with this sample VB.NET code to add an image to textMgr.SelectChar(page, cursor) ' Delete a selected As String = Program.RootPath + "\\" output.pdf" doc.Save
adding a page to a pdf in preview; adding a page to a pdf document
C# PDF insert image Library: insert images into PDF in C#.net, ASP
Insert images into PDF form field. Access to freeware download and online C#.NET class source code. How to insert and add image, picture, digital photo, scanned
add page numbers pdf files; add pages to pdf document
8.4. COMPUTINGWITHBOOLEANS
127
# update e sum m and count for values in line
for xStr r in n string.split(line):
sum = sum m + + eval(xStr)
count = = count t + 1
line = infile.readline()
print "\nThe e average e of the numbers is", sum m / / count
Asyoucansee,theloopthatprocessesthenumbersinalineisindentedinsideofthefileprocessingloop.
Theouterwhileloopiteratesonceforeachlineofthefile. Oneachiterationoftheouterloop,theinner
forloopiteratesasmanytimesastherearenumbersonthatline.Whentheinnerloopfinishes,thenextline
ofthefileisread,andtheouterloopgoesthroughitsnextiteration.
Theindividualfragmentsofthisproblemarenotcomplexwhentakenseparately,butthefinalresultis
fairlyintricate. Thebestwaytodesignnestedloopsistofollowtheprocesswedidhere. Firstdesignthe
outerloopwithoutworryingaboutwhatgoesinside.Thendesignwhatgoesinside,ignoringtheouterloop(s).
Finally,putthepiecestogether,takingcaretopreservethenesting. Iftheindividualloopsarecorrect,the
nestedresultwillworkjustfine;trustit. Withalittlepractice,you
'
llbeimplementingdouble-,eventriple-
nestedloopswithease.
8.4 ComputingwithBooleans
Wenowhavetwocontrolstructures,ifandwhile,thatuseconditions,whichareBooleanexpressions.
Conceptually,aBooleanexpressionevaluatestooneoftwovalues:falseortrue.InPython,thesevaluesare
representedbytheints0and1. Sofar,wehaveusedsimpleBooleanexpressionsthatcomparetwovalues
(e.g.,while x >= 0).
8.4.1 BooleanOperators
Sometimesthesimpleconditionsthatwehavebeenusingdonotseemexpressiveenough. Forexample,
supposeyouneedtodeterminewhethertwopointobjectsareinthesameposition—thatis,theyhaveequalx
coordinatesandequalycoordinates.Onewayofhandlingthiswouldbeanesteddecision.
if p1.getX() == = p2.getX():
if p1.getY() ) == = p2.getY():
# points s are e the same
else:
# points s are e different
else:
# points are e different
Youcanseehowawkwardthisis.
Insteadofworkingaroundthisproblemwithadecisionstructure,anotherapproachwouldbetoconstruct
amorecomplexexpressionusingBooleanoperations. Likemostprogramminglanguages,Pythonprovides
threeBooleanoperators: and,orandnot.Let
'
stakealookatthesethreeoperatorsandthenseehowthey
canbeusedtosimplifyourproblem.
TheBooleanoperatorsandandorareusedtocombinetwoBooleanexpressionsandproduceaBoolean
result.
<expr> and <expr>
<expr> or <expr>
Theandoftwoexpressionsistrueexactlywhenbothoftheexpressionsaretrue. Wecanrepresentthis
definitioninatruthtable.
C# HTML5 PDF Viewer SDK to view PDF document online in C#.NET
File: Split PDF; C# Page: Insert PDF pages; C# Page: Delete PDF pages; C# Read C# Read: PDF Image Extract; C# Write: Insert text into PDF; C# Write: Add Image to
add page numbers to a pdf file; adding page numbers to a pdf in reader
C# PDF Sticky Note Library: add, delete, update PDF note in C#.net
Allow users to add comments online in ASPX webpage. Able to change font size in PDF comment box. Able to save and print sticky notes in PDF file.
adding pages to a pdf document; add page pdf
128
CHAPTER8. CONTROLSTRUCTURES,PART2
P
Q
PandQ
T
T
T
T
F
F
F
T
F
F
F
F
Inthistable,PandQrepresentsmallerBooleanexpressions.Sinceeachexpressionhastwopossiblevalues,
therearefourpossiblecombinationsofvalues,eachshownasonerowinthetable.Thelastcolumngivesthe
valueofPandQforeachpossiblecombination.Bydefinition,theandistrueonlyinthecasewhereboth
PandQaretrue.
Theoroftwoexpressionsistruewheneitherexpressionistrue.Hereisthetruthtabledefining or:
P
Q
PorQ
T
T
T
T
F
T
F
T
T
F
F
F
Theonlytimetheorisfalseiswhenbothexpressionsarefalse.Noticeespeciallythatoristruewhenboth
expressionsaretrue. Thisisthemathematicaldefinitionofor,buttheword“or”issometimesusedinan
exclusivesenseineverydayEnglish. Ifyourmomsaidthatyoucouldhavecakeorcookiesfordessert,she
wouldprobablyscoldyoufortakingboth.
ThenotoperatorcomputestheoppositeofaBooleanexpression.Itisaunaryoperator,meaningthatit
operatesonasingleexpression.Thetruthtableisverysimple.
P
notP
T
F
F
T
UsingBooleanoperators,itispossibletobuildarbitrarilycomplexBooleanexpressions. Aswitharith-
meticoperators,theexactmeaningofacomplexexpressiondependsontheprecedencerulesfortheoperators.
Considerthisexpression.
a or not b and d c
Howshouldthisbeevaluated?
Pythonfollowsastandardconventionthattheorderofprecedenceisnot,followedbyand,followedby
or.Sotheexpressionwouldbeequivalenttothisparenthesizedversion.
(a or ((not b) ) and d c))
Unlikearithmetic,however,mostpeopledon
'
ttendtoknoworremembertheprecedencerulesforBooleans.
Isuggestthatyoualwaysparenthesizeyourcomplexexpressionstopreventconfusion.
NowthatwehavesomeBooleanoperators,wearereadytoreturntoourexampleproblem. Totestfor
theco-locationoftwopoints,wecoulduseanandoperation.
if p1.getX() == = p2.getX() ) and p2.getY() == p1.getY():
# points are e the e same
else:
# points are e different
Heretheentireexpressionwillonlybetruewhenbothofthesimpleconditionsaretrue. Thisensuresthat
boththexandycoordinateshavetomatchforthepointstobethesame.Obviously,thisismuchsimplerand
clearerthanthenestedifsfromthepreviousversion.
Let
'
slookataslightlymorecomplexexample.Inthenextchapter,wewilldevelopasimulationforthe
gameofracquetball. Partofthesimulationwillneedtodeterminewhenagamehasended. Supposethat
scoreAandscoreBrepresentthescoresoftworacquetballplayers.Thegameisoverassoonaseitherof
theplayershasreached15points.HereisaBooleanexpressionthatistruewhenthegameisover:
8.4. COMPUTINGWITHBOOLEANS
129
scoreA == 15 or r scoreB B == 15
Wheneitherscorereaches15,oneofthetwosimpleconditionsbecomestrue,and,bydefinitionofor,the
entireBooleanexpressionistrue.Aslongasbothconditionsremainfalse(neitherplayerhasreached15)the
entireexpressionisfalse.
Oursimulationwillneedaloopthatcontinuesaslongasthegameisnotover. Wecanconstructan
appropriateloopconditionbytakingthenegationofthegame-overcondition:
while not (scoreA A == = 15 or scoreB == 15):
# continue e playing
WecanalsoconstructmorecomplexBooleanexpressionsthatreflectdifferentpossiblestoppingcondi-
tions. Someracquetballplayersplayshutouts(sometimescalledaskunk). . Fortheseplayers,agamealso
endswhenoneoftheplayersreaches7andtheotherhasnotyetscoredapoint. Forbrevity,I
'
lluseafor
scoreAandbforscoreB.Hereisanexpressionforgame-overwhenshutoutsareincluded:
a == 15 or b == = 15 5 or (a == 7 and b == 0) or (b b == = 7 and a == 0)
DoyouseehowIhaveaddedtwomoresituationstotheoriginalcondition? Thenewpartsreflectthetwo
possiblewaysashutoutcanoccur,andeachrequirescheckingbothscores. Theresultisafairlycomplex
expression.
Whilewe
'
reatit,let
'
stryonemoreexample.Supposewewerewritingasimulationforvolleyball,rather
thanracquetball.Volleyballdoesnothaveshutouts,butitrequiresateamtowinbyatleasttwopoints.Ifthe
scoreis15to14,oreven21to20,thegamecontinues.
Let
'
swriteaconditionthatcomputeswhenavolleyballgameisover.Here
'
soneapproach.
(a >= 15 and a a - - b >= 2) or (b >= 15 and b - a a >= = 2)
Doyouseehowthisexpressionworks? ItbasicallysaysthegameisoverwhenteamAhaswon(scoredat
least15andleadingbyatleast2)orwhenteamBhaswon.
Hereisanotherwaytodoit.
(a >= 15 or b b >= = 15) and abs(a - b) >= 2
Thisversionisabitmoresuccinct. Itstatesthatthegameisoverwhenoneoftheteamshasreacheda
winningtotalandthedifferenceinthescoresisatleast2.Rememberthatabsreturnstheabsolutevalueof
anexpression.
8.4.2 BooleanAlgebra
AlldecisionsincomputerprogramsboildowntoappropriateBooleanexpressions.Theabilitytoformulate,
manipulateandreasonwiththeseexpressionsisanimportantskillforprogrammersandcomputerscientists.
Booleanexpressionsobeycertainalgebraiclawssimilartothosethatapplytonumericoperations. These
lawsarecalledBooleanlogicorBooleanalgebra.
Let
'
slookatafewexamples. Thefollowingtableshowssomerulesofalgebrawiththeircorrelatesin
Booleanalgebra.
Algebra
Booleanalgebra
a
0
0
aandfalse==false
a
1
a
aandtrue==a
a
0
a aorfalse==a
Fromtheseexamples,youcanseethatandhassimilaritiestomultiplication,andorhassimilaritiesto
addition;while0and1correspondtofalseandtrue.
HerearesomeotherinterestingpropertiesofBooleanoperations.Anythingoredwithtrueisjusttrue.
a or true == true
Bothandandordistributeovereachother.
130
CHAPTER8. CONTROLSTRUCTURES,PART2
a or (b and c) ) == = (a or b) and (a or c)
a and (b or c) ) == = (a and b) or (a and c)
Adoublenegativecancelsout.
not(not a) == = a
ThenexttwoidentitiesareknownasDeMorgan
'
slaws.
not(a or b) == = (not t a) and (not b)
not(a and b) == = (not t a) or (not b)
Noticehowtheoperatorchangesbetweenandandorwhenthenotispushedintoanexpression.
OneapplicationofBooleanalgebraistheanalysisandsimplificationofBooleanexpressionsinsideof
programs. Forexample,let
'
sgobacktotheracquetballgameonemoretime. Above,wedevelopedaloop
conditionforcontinuingthegamethatlookedlikethis:
while not (scoreA A == = 15 or scoreB == 15):
# continue e playing
Youcanreadthisconditionassomethinglike:WhileitisnotthecasethatplayerAhas15orplayerBhas15,
continueplaying.We
'
reprettysurethat
'
scorrect,butnegatingcomplexconditionslikethiscanbesomewhat
awkward,tosaytheleast.UsingalittleBooleanalgebra,wecantransformthisresult.
ApplyingDeMorgan
'
slaw,weknowthattheexpressionisequivalenttothis.
(not scoreA == = 15)
and
(not scoreB == 15)
Remember,wehavetochangetheortoandwhen“distributing”thenot. Thisconditionisnobetterthan
thefirst,butwecangoonestepfartherbypushingthenotsintotheconditionsthemselves.
while scoreA != = 15 5 and scoreB != 15:
# continue e playing
Nowwehaveaversionthatismucheasiertounderstand.ThisreadssimplyaswhileplayerAhasnotreached
15andplayerBhasnotreached15,continueplaying.
Thisparticularexampleillustratesagenerallyusefulapproachtoloopconditions.Sometimesit
'
seasier
tofigureoutwhenaloopshouldstop,ratherthanwhentheloopshouldcontinue.Inthatcase,simplywrite
theloopterminationconditionandthenputanotinfrontofit. AnapplicationortwoofDeMorgan
'
slaws
canthengetyoutoasimplerbutequivalentversionsuitableforuseinawhilestatement.
8.5 OtherCommonStructures
Takentogether,thedecisionstructure(if)alongwithapre-testloop(while)provideacompletesetof
controlstructures.Thismeansthateveryalgorithmcanbeexpressedusingjustthese.Onceyou
'
vemastered
thewhile andthe if,thereisnoalgorithmthatyoucannotwrite, inprinciple. . However, , forcertain
kindsofproblems,alternativestructurescansometimesbeconvenient.Thissectionoutlinessomeofthose
alternatives.
8.5.1 Post-TestLoop
Supposeyouarewritinganinputalgorithmthatissupposedtogetanonnegativenumberfromtheuser.Ifthe
usertypesanincorrectinput,theprogramasksforanothervalue.Itcontinuestorepromptuntiltheuserenters
avalidvalue. Thisprocessiscalledinputvalidation. Well-engineeredprogramsvalidateinputswhenever
possible.
Hereisasimplealgorithm.
repeat
get a number r from m the user
until number is s >= = 0
8.5. OTHERCOMMONSTRUCTURES
131
Theideahereisthattheloopkeepsgettinginputsuntilthevalueisacceptable.Theflowchartdepictingthis
designinshowninFigure8.2.Noticehowthisalgorithmcontainsaloopwheretheconditiontestcomesafter
theloopbody. Thisisapost-testloop. Apost-testloopmustalwaysexecutethebodyoftheloopatleast
once.
yes
no
number < 0 ?
Get a number
Figure8.2:Flowchartofapost-testloop.
Unlikesomeotherlanguages,Pythondoesnothaveastatementthatdirectlyimplementsapost-testloop.
However,thisalgorithmcanbeimplementedwithawhileby“seeding”theloopconditionforthefirst
iteration.
number = -1
# Start t with an illegal value to o get t into the loop.
while number < < 0:
number = input("Enter r a a positive number: ")
Thisforcestheloopbodytoexecuteatleastonceandisequivalenttothepost-testalgorithm. Youmight
noticethatthisissimilartothestructuregivenearlierfortheinteractivelooppattern. Interactiveloopsare
naturallysuitedtoapost-testimplementation.
Someprogrammersprefertosimulateapost-testloopmoredirectlybyusingaPythonbreakstatement.
ExecutingbreakcausesPythontoimmediatelyexittheenclosingloop. Oftenabreakstatementisused
toleavewhatlookssyntacticallylikeaninfiniteloop.
Hereisthesamealgorithmimplementedwithabreak.
while 1:
number = input("Enter r a a positive number: ")
if x >= 0: : break k # Exit loop if number is s valid.
Thefirstlinemaylookabitstrangetoyou.RememberthatconditionsinPythonevaluatetoeithera0forfalse
ora1fortrue.Theheadingwhile 1appearstobeaninfiniteloop,sincetheexpressionalwaysevaluates
to1(i.e.,itisalwaystrue). However,whenthevalueofxisnonnegative,thebreakstatementexecutes,
whichterminatestheloop. Noticethebreakisplacedonthesamelineastheif. . Thisislegalwhenthe
bodyoftheifonlycontainsonestatement.It
'
scommontoseeaone-lineif-breakcombinationusedas
aloopexit.
Eventhissmallexamplecanbeimproved.Itwouldbeniceiftheprogramissuedawarningexplaining
whytheinputwasinvalid.Inthewhileversionofthepost-testloop,thisisabitawkward.Weneedtoadd
anifsothatthewarningisnotdisplayedforvalidinputs.
132
CHAPTER8. CONTROLSTRUCTURES,PART2
number = -1
# Start t with an illegal value to o get t into the loop.
while number < < 0:
number = input("Enter r a a positive number: ")
if number r < < 0:
print "The number you entered was not t positive"
Seehowthevaliditycheckgetsrepeatedintwoplaces?
Addingawarningtotheversionusingbreakonlyrequiresaddinganelsetotheexistingif.
while 1:
number = input("Enter r a a positive number: ")
if x >= 0:
break # Exit loop if number is valid.
else:
print "The number you entered was not t positive"
8.5.2 LoopandaHalf
Someprogrammerswouldsolvethewarningproblemfromtheprevioussectionusingaslightlydifferent
style.
while 1:
number = input("Enter r a a positive number: ")
if x >= 0: : break
# Loop exit
print "The e number r you entered was not positive"
Heretheloopexitisactuallyinthemiddleoftheloopbody.Thisiscalledaloopandahalf. Somepurists
frownonexitsinthemidstofalooplikethis,butthepatterncanbequitehandy.
Theloopandahalfisanelegantwaytoavoidtheprimingreadinasentinelloop. Hereisthegeneral
patternofasentinelloopimplementedasaloopandahalf.
while 1:
Get next data a item
if the item m is s the sentinel: break
process the e item
Figure8.3showsaflowchartofthisapproachtosentinelloops. Youcanseethatthisimplementationis
faithfultothefirstruleofsentinelloops:avoidprocessingthesentinelvalue.
Thechoiceofwhethertousebreakstatementsornotislargelyamatteroftaste.Eitherstyleisaccept-
able.Onetemptationthatshouldgenerallybeavoidedispepperingthebodyofaloopwithmultiplebreak
statements. Thelogicofaloopiseasilylostwhentherearemultipleexits. However,therearetimeswhen
eventhisruleshouldbebrokentoprovidethemostelegantsolutiontoaproblem.
8.5.3 BooleanExpressionsasDecisions
Sofar,wehavetalkedaboutBooleanexpressionsonlywithinthecontextofothercontrolstructures.Some-
times,Booleanexpressionsthemselvescanactascontrolstructures. Infact, , Booleanexpressionsareso
flexibleinPythonthattheycansometimesleadtosubtleprogrammingerrors.
Considerwritinganinteractiveloopthatkeepsgoingaslongastheuserresponsestartswitha“y.” To
allowtheusertotypeeitheranupperorlowercaseresponse,youcouldusealooplikethis:
while response[0] ] == = "y" or response[0] == "Y":
YoumustbebecarefulnottoabbreviatethisconditionasyoumightthinkofitinEnglish:“Whilethefirst
letteris
'
y
'
or
'
Y”
'
.Thefollowingformdoesnotwork.
while response[0] ] == = "y" or "Y":
Documents you may be interested
Documents you may be interested