2.6.DEFINITELOOPS 21
eachsuccessive valueinthesequence, andthestatementsinthebodyareexecutedonceforeachvalue.
Usually, thesequenceportionisa listofvalues. Youcanbuilda simplelistbyplacinga sequenceof
expressionsinsquarebrackets.Someinteractive exampleshelptoillustratethepoint:
for i in [0,1,2,3]:
print i
0
1
2
3
for odd in [1, 3, 5, 7, 9]:
print odd * odd
1
9
25
49
81
Youcanseewhatishappeninginthesetwo examples. Thebodyoftheloopisexecutedusingeach
successive valueinthelist.Thelengthofthelistdeterminesthenumberoftimestheloopwillexecute.In
thefirstexample,thelistcontainsthefourvalues0 through3,andthesesuccessive valuesofiaresimply
printed.Inthesecondexample,oddtakesonthevaluesofthefirstfive oddnaturalnumbers,andthebody
oftheloopprintsthesquaresofthesenumbers.
Now, let’s gobacktotheexamplewhichbeganthissection(fromchaos.py) Lookagainattheloop
heading:
for i in range(10):
Comparingthistothetemplatefortheforloopshowsthatthelastportion,range(10)mustbesomekind
ofsequence.Let’s seewhatthePythoninterpretertellsus.
range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Doyouseewhatis happeninghere?Therangefunctionis a built-inPythoncommandthatsimplyproduces
a listofnumbers.Theloopusingrange(10)is exactlyequivalenttooneusinga listof 10 numbers.
for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:
Ingeneral,range(
including,thevalueof
thenumberofitemsintheresultinglist. Inchaos.pywedidnotevencarewhatvaluestheloopindex
variableused(sincethevalueofiwasnotreferredtoanywhereintheloopbody).We justneededa listof
length 10 tomake thebodyexecute 10 times.
AsI mentionedabove, thispatternis calledacountedloop, andit is a verycommonwaytousedefinite
loops.Whenyouwanttodosomethinginyourprograma certainnumberoftimes,useaforloopwitha
suitablerange.
for <variable> in range(<expr>):
Thevalueoftheexpressiondetermineshow many timestheloopexecutes.Thenameoftheindex variable
doesn’t reallymattermuch;programmersoftenuseiorjastheloopindex variableforcountedloops.Just
besuretouseanidentifierthatyouarenotusingforany otherpurpose.Otherwiseyoumightaccidentally
wipeouta valuethatyouwillneedlater.