Why does only the inner part of these nested loops work?

I am new to 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 only work when using 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? Thank!

+3


source to share


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 called range

    . (Or more precisely, Python 3 range

    replaces Python 2.x range

    and xrange

    .)

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


You forgot to reset b

both c

the top of the loops for a

and b

respectively. This is why we use loops instead for

.



+6


source


whe while c <= 8

gets looped while c <= 8

, so c

it goes into 8

, and so the program doesn't need to loop anymore.

Try to set the c = 0

end of the cycle, as well as install b

and a

to 0 after cycles or even better use itertools or cycles.

+2


source


After the first loop of the loop, c will be 9. You never reset c, so it c <= 8

will never be true in loops a or b.

If you reset each one before their loops, it will work correctly.

a = 0
while a <= 5:
    b = 0
    while b <=3:
        c = 0
        while c <= 8:
            print a , b , c
            c += 1
        b += 1
    a += 1

      

0


source







All Articles