0

I've got some nested functions and I'm trying to sum the total number of times that something occurs using:

if C[city_cell_x][city_cell_y] == 1:
  cityCount +=1

but as this is within a function:

    # Animate

fig = plt.figure()
plt.axis("on")
ims = []
for t in range(totalTime):
    print(str(r), " Time = " + str(t))
    ims.append((plt.imshow(C, cmap="Accent"),))
    C = mapRun(C)
if C[city_cell_x][city_cell_y] == 1:
  cityCount +=1
im_ani = animation.ArtistAnimation(
    fig, ims, interval=interval, repeat_delay=3000, blit=True
)

# Save the animation?
if save:
  print("Saving...")
  im_ani.save(("Repeat" + str(r) + ".html"), writer="html", fps=60, dpi=75)

which I am then looping over, it is either not successfully counting and just returning zero at the end, of it is raising "cityCount referenced before assignment" even though it is referenced at the start of the code (outside of the function)

I can provide the entire code if that is easier

martineau
  • 119,623
  • 25
  • 170
  • 301
Wilf Chun
  • 25
  • 5
  • Sounds like a scope issue - maybe if you had `cityCount` as an instance variable on an object, you could keep track of it better? – Random Davis Mar 01 '19 at 20:09
  • 2
    This is currently unanswerable. You say the code is inside a function, but you don't define any function in the question, so it's not possible to know what name is in what scope. Please give an [mcve] – roganjosh Mar 01 '19 at 20:09
  • It is unclear to me what you are trying to do, but shouldn't the two lines where you do the counting be part of the `for` loop? – Thierry Lathuille Mar 01 '19 at 20:10

1 Answers1

1

It looks like the problem may be a what is described here.

If you created cityCount outside your function and are now trying to assign to it inside, what you are getting is a new local variable.

If the if statement is never true, cityCount is never incremented but the code runs fine. If the if statement is true, you get the error because there is no local cityCount to add to.

The solution would be to add global cityCount to the beginning of the function.

Lev M.
  • 6,088
  • 1
  • 10
  • 23