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, the easier way to specify a loop over a range of numbers is to use a for loop over an xrange* iterator:
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 is now called range. (Or more precisely, Python 3 range replaces Python 2.x's range and xrange.)
Third way (best)
The second way can be simplified by application of itertools.product(), which takes in a number of iterables (lists) and returns every possible combination of each element from each 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 and more, read Dan Goodger's "Code Like a Pythonista: Idiomatic Python".
for a in range(6). – georg Mar 31 '12 at 13:37