1

I'm wondering why this code does not work.

loop = -10
loop2 = -10
while loop <= 10:
    while loop2 <= 10:
        if current_block:
            block = turtle.Turtle()
            block.shape("square")
            block.color("white")
            block.shapesize(stretch_wid=0.85, stretch_len=0.85)
            block.penup()
            block.goto(loop*20, loop2*20)
        loop2 += 1
    loop += 1

What I want to do is to create a 20x20 grid of squares centered at (0,0). Right now, only a line of squares are created at x-200

7
  • Why not use for loops? Commented Apr 11, 2020 at 18:29
  • Not sure. Is for loops better in this case? What's the difference? Commented Apr 11, 2020 at 18:37
  • For loops are best when you know how many times you will be iterating in each loop (e.g. 10). While loops are best for indefinite loops where you don't know in advance how many iterations there will be. Commented Apr 11, 2020 at 18:39
  • For example, you could replace your while loops above with for loop in range(-10,11):. Then you don't need the loop += 1 statements. Commented Apr 11, 2020 at 18:40
  • Oh, nice! Thanks, I'll do that! Commented Apr 11, 2020 at 18:51

1 Answer 1

1

The loop2 variable retains its value, so the inner loop is not executed after the first iteration of the outer loop. You need to reinitialize loop2 in every iteration of the outer loop:

loop = -10
while loop <= 10:
    loop2 = -10 # Here!
    while loop2 <= 10:
        if current_block:
            block = turtle.Turtle()
            block.shape("square")
            block.color("white")
            block.shapesize(stretch_wid=0.85, stretch_len=0.85)
            block.penup()
            block.goto(loop*20, loop2*20)
        loop2 += 1
    loop += 1
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, that's some amazing response time! Thanks, that's exactly what I needed. :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.