Python Programming: An Introduction to Computer Science

(Nora) #1
8.5.OTHERCOMMONSTRUCTURES 131

Theideahereis thattheloopkeepsgettinginputsuntilthevalueis acceptable.Theflowchartdepictingthis
designin shownin Figure8.2.Noticehow thisalgorithmcontainsa loopwheretheconditiontestcomesafter
theloopbody. Thisis apost-testloop. Apost-testloopmustalwaysexecutethebodyoftheloopatleast
once.


yes

no

number < 0?

Get a number

Figure8.2:Flowchartofa post-testloop.

Unlike someotherlanguages,Pythondoesnothave a statementthatdirectlyimplementsa post-testloop.
However, thisalgorithmcanbeimplementedwithawhileby“seeding”theloopconditionforthefirst
iteration.


number = -1 # Startwith an illegal value to get into the loop.
while number < 0:
number = input("Entera positive number: ")


Thisforcestheloopbodytoexecuteatleastonceandis equivalenttothepost-testalgorithm. Youmight
noticethatthisis similartothestructuregivenearlierfortheinteractive looppattern.Interactive loopsare
naturallysuitedtoa post-testimplementation.
Someprogrammerspreferto simulatea post-testloopmoredirectlybyusinga Pythonbreakstatement.
ExecutingbreakcausesPythontoimmediatelyexittheenclosingloop.Oftenabreakstatementis used
toleave whatlookssyntacticallylike aninfiniteloop.
Hereis thesamealgorithmimplementedwithabreak.


while 1:
number = input("Entera positive number: ")
if x >= 0: break# Exit loop if number is valid.


Thefirstlinemaylooka bitstrangeto you.Rememberthatconditionsin Pythonevaluateto eithera 0 forfalse
ora 1 fortrue.Theheadingwhile 1 appearstobeaninfiniteloop,sincetheexpressionalwaysevaluates
to1 (i.e.,it is alwaystrue). However, whenthevalueofxis nonnegative, thebreakstatementexecutes,
whichterminatestheloop.Noticethebreakis placedonthesamelineastheif. Thisis legalwhenthe
bodyoftheifonlycontainsonestatement.It’s commontoseea one-lineif-breakcombinationusedas
a loopexit.
Eventhissmallexamplecanbeimproved.It wouldbeniceif theprogramissueda warningexplaining
whytheinputwasinvalid.Inthewhileversionofthepost-testloop,thisis a bitawkward.We needtoadd
anifsothatthewarningis notdisplayedforvalidinputs.

Free download pdf