1

I'm writing two nested loop statement inside of a function such that I can use turtles to draw a square of one size through one iteration of the lowest level loop, then increment my square size on the outer loop with the following code:

accumDistance = 0
def drawSquares():
    for i in [1, 2, 3, 4, 5]:
        accumDistance = accumDistance + 20
        for l in [1, 2, 3, 4]:
            greg.forward(accumDistance)
            greg.right(90)

The problem is that I receive an error whenever I try to run the application. The error says that I am trying to use my accumDistance variable before I define it: "UnboundLocalError: local variable 'accumDistance' referenced before assignment". I've isolated the problem to the first for loop where I'm attempting to increment. If I remove the "accumDistance = accumDistance + 20" and set my accumDistance = 20, the program works as intended.

Anybody know why it's having a problem with this statement? Thanks.

1 Answers1

1

Use global if you want to modify a global variable in a function.

  accumDistance = 0
  def drawSquares():
>     global accumDistance
      for i in [1, 2, 3, 4, 5]:
          accumDistance = accumDistance + 20
          for l in [1, 2, 3, 4]:
              greg.forward(accumDistance)
              greg.right(90)

See Using global variables in a function other than the one that created them

iBug
  • 35,554
  • 7
  • 89
  • 134