Python loop seems not to be iterating

The below code is not acting as expected for me.

class stateClass:
  state = 0

states = []

def populateStates(states):
  for s in states:
    if s.state == 0
      print 'populating'
      s.state = 1


the output is

states array length: 2

this is failing the second time

for s in states:
  if s.state == 0

if conditional is failing the second time although it is a different index in the array and thus the s.state should have been initialized to 0. So I think the loop is not iterating properly.

Anyone know whats wrong?


You don't need the ;'s - this isn't C and co. etc...

class stateClass: 
    state = 0 

Here you're creating a class level attribute - ie, state is shared by all instances of stateClass.

You're appending to your list stateClass itself - ie, the definition of the class, not an actual instance of a class...

As soon as you change state in one of them, all instances of stateClass now have that changed value.

You most likely want to be creating instances:

class State(object):
    def __init__(self, number):
        self.state = number

Hawaii = State(50)  
Kentucky = State(23) # (making state numbers up here...) 

my_states = []

To then show state, do something like:

print Hawaii.state

If you wanted a property so it avoids explicit setting from outside the class then:

class State(object):
    def __init__(self, number):
        self._state = number
    def state(self):
        return self._state

Need Your Help

Can scheduled web request be authorized by MVC controllers?

model-view-controller web request

My web app has to do some calculations in the background. I've investigated multiple solutions and I would like to go for business logic instead of a SQL job that triggers all the calculations. Aft...

How to convert COPYDATASTRUCT's Data to a understandable string in VC++?

c++ winapi sendmessage

I am trying to change poCopyData (PCOPYDATASTRUCT) to a string and also a way to turn a string back into that. So i can send it, poCopyData is where the program copies the messages from another pro...