Question

Here is a loop and I couldn't find an answer to why it is looping 2 times insted of 1.
I hope someone can help me :)


The loop now works. Thank you.

Here is the code:

gridX = 0
gridY = 0
while gridX <= 4 and gridY < 4:
    if gridX == 4:
        gridY += 1
        gridX = 0
        print("Y "+str(gridY))
    else:
        gridX += 1
        print("X "+str(gridX))

It should output this:

X 1
X 2
X 3
X 4
Y 1
X 1
X 2
X 3
X 4
Y 2
X 1
X 2
X 3
X 4
Y 3
X 1
X 2
X 3
X 4
Y 4

Beter ways to get this result are welcome.

Was it helpful?

Solution

A better way of doing this is perhaps a double for loop.

for gridY in range(0,4):
    print gridY
    for gridX in range(0,4):
        print gridX

OTHER TIPS

While Izaaz has given you a better way of doing this, you can expand the output to better see what your code was doing. Stepping through your code like this can help you understand exactly what your code is doing, which you can compare to what you expect it to do.

gridX = 0
gridY = 0
while gridX <= 4 and gridY < 4:
    if gridX == 4:
        gridY += 1
        gridX = 0
        print("IF-   X "+str(gridX)+" Y "+str(gridY))
    else:
        gridX += 1
        print("ELSE- X "+str(gridX)+" Y "+str(gridY))

Which gives you --

ELSE- X 1 Y 0
ELSE- X 2 Y 0
ELSE- X 3 Y 0
ELSE- X 4 Y 0
IF-   X 0 Y 1
ELSE- X 1 Y 1
ELSE- X 2 Y 1
ELSE- X 3 Y 1
ELSE- X 4 Y 1
IF-   X 0 Y 2
ELSE- X 1 Y 2
ELSE- X 2 Y 2
ELSE- X 3 Y 2
ELSE- X 4 Y 2
IF-   X 0 Y 3
ELSE- X 1 Y 3
ELSE- X 2 Y 3
ELSE- X 3 Y 3
ELSE- X 4 Y 3
IF-   X 0 Y 4

Following that through you can see that you are getting the else block four times then one if block then four else blocks....

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top