Python Programming: An Introduction to Computer Science

(Nora) #1
8.3.COMMONLOOPPATTERNS 121

<body>

yes

<condition>? no

Figure8.1:Flowchartofawhileloop.

for i in range(11):
print i


Noticethatthewhileversionrequiresustotake careofinitializingibeforetheloopandincrementingiat
thebottomoftheloopbody. Intheforloop,theloopvariableis handledautomatically.
Thesimplicityofthewhilestatementmakesit bothpowerfulanddangerous.Becauseit is lessrigid,it
is moreversatile;it candomorethanjustiteratethroughsequences.Butit is alsoa commonsourceoferrors.
Supposeweforgettoincrementiat thebottomoftheloopbodyinthecountingexample.


i = 0
while i <= 10:
print i


Whatwilltheoutputfromthisprogrambe?WhenPythongetstotheloop,iwillbe0,whichis lessthan
10,sotheloopbodyexecutes,printinga 0. Nowcontrolreturnstothecondition;iis still0,sotheloop
bodyexecutesagain,printinga 0.Now controlreturnstothecondition;iis still0, sotheloopbodyexecutes
again,printinga 0....
Yougetthepicture.Thisis anexampleofaninfiniteloop. Usually, infiniteloopsarea badthing.Clearly
thisversionoftheprogramdoesnothinguseful.Thatremindsme,didyouhearaboutthecomputerscientist
whodiedofexhaustionwhilewashinghishair?Theinstructionsonthebottlesaid:“Lather. Rinse.Repeat.”
Asa beginningprogrammer, it wouldsurprisingif youdidnotaccidentlywritea fewprogramswith
infiniteloops—it’s a riteofpassageforprogrammers.Evenmoreexperiencedprogrammershave beenknown
todothisfromtimetotime.Usually, youcanbreakoutofa loopbypressing Ctrl -c(holdingdownthe
Ctrl key andpressing“c”).If yourloopis reallytight,thismightnotwork,andyou’ll have toresortto
moredrasticmeans(suchas Ctrl - Alt - Delete ona PC).If allelsefails,thereis alwaysthetrusty
resetbuttononyourcomputer. Thebestideais toavoidwritinginfiniteloopsinthefirstplace.


8.3 CommonLoopPatterns.


8.3.1 Interactive Loops.


Onegooduseoftheindefiniteloopis towriteinteractiveloops. Theideabehindaninteractive loopis that
it allowstheusertorepeatcertainportionsofa programondemand.Let’s take a lookat thislooppatternin
thecontextofournumberaveragingproblem.

Free download pdf