Why does only the inner part of these nested loops work?
4 answers
The first way
Your way will work, but you have to remember to reset the loop counters on each iteration.
a = 0
b = 0
c = 0
while a <= 5:
while b <=3:
while c <= 8:
print a , b , c
c += 1
b += 1
c = 0 # reset
a += 1
b = 0 # reset
c = 0 # reset
Second way (Pythonic)
The first way involves a lot of bookkeeping. In Python, an easier way to specify a loop over a range of numbers is to use a loop for
over an iterator xrange
*:
for a in xrange(5+1): # Note xrange(n) produces 0,1,2...(n-1) and does not include n.
for b in xrange (3+1):
for c in xrange (8+1):
print a,b,c
- Note. In Python 3
xrange
it is now calledrange
. (Or more precisely, Python 3range
replaces Python 2.xrange
andxrange
.)
Third way (best)
The second way can be simplified with an application itertools.product()
that takes multiple iterations (lists) and returns every possible combination of every item from every list.
import itertools
for a,b,c in itertools.product(xrange(5+1),xrange(3+1),xrange(8+1)):
print a,b,c
For these tricks, etc. read Dan Goodger's "Code As Pythonista: An Idiomatic Python" .
+7
source to share