I’m newbie in Python.
I have this simple code
a = 0
b = 0
c = 0
while a <= 5:
while b <=3:
while c <= 8:
print a , b , c
c += 1
b += 1
a += 1
And work only while with C
0 0 0
0 0 1
0 0 2
0 0 3
0 0 4
0 0 5
0 0 6
0 0 7
0 0 8
Why? How to fix it?
Thanks!
First way
Your way will work, but you have to remember to reset the loop counters on each iteration.
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
forloop over anxrange* iterator:xrangeis now calledrange. (Or more precisely, Python 3rangereplaces Python 2.x’srangeandxrange.)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.For these tricks and more, read Dan Goodger’s “Code Like a Pythonista: Idiomatic Python”.