PePe
PePe

Reputation: 443

Why is only the innermost of these nested while loops working?

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!

Upvotes: 3

Views: 211

Answers (4)

Li-aung Yip
Li-aung Yip

Reputation: 12486

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".

Upvotes: 7

Brigand
Brigand

Reputation: 86240

After the first while loop c will equal 9. You never reset c so, c <= 8 will never be true on the a or b loops.

If you reset each of them 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

Upvotes: 0

jamylak
jamylak

Reputation: 133564

whe while c <= 8 gets looped while c <= 8 so c gets to 8 and therefore the program never has to execute that loop again.

Try setting c = 0 at the end of the loop, as well as setting b and a to 0 after their loops or better yet make use of itertools or for loops.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

You forgot to reset b and c at the top of the loops for a and b respectively. This is why we use for loops instead.

Upvotes: 6

Related Questions