Skip to content
Advertisement

Invalid syntax using += operator [duplicate]

I keep getting a syntax error when using += in python here is my code. I am also having troule with nonlocal. I am getting lots of errors including syntax errors and unbound local error Thanks in advance!!!

update: more code added this is all the code It now says local variable ‘citizens’ referenced before assignment

JavaScript

Advertisement

Answer

Three things with this code:

  1. the rnum assignment will fail because you are not doing integer division
  2. You actually want global not non-local in this case. Though you should avoid using global variables like this.
  3. You can do the second line as part of the first

This would be what I think you want:

JavaScript

Though I would recommend avoiding nonlocal altogether since it can cause many bugs down the road. I would suggest doing something like this stylistically:

JavaScript

The above code has the benefit of being usable with multiple sets of citizens, so for example:

JavaScript

Here is a good article and a good video on how scope works in python, but a good rule of thumb is to just keep everything you can local.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement