Let's say I have to loop over something and keep counters of various characteristics as the loop progresses. Before the loop, I could create these various counter variables with initial values.
count1 = 0
count2 = 0
for index in range(0, 10):
count1 += 1
count2 += 2
print count1, count2
Alternatively, I could create the counter variable when it is first actually used by using a conditional statement in the loop that creates the variable if it doesn't exist and then the variable is incremented.
for index in range(0, 10):
if "count1" not in locals():
count1 = 0
if "count2" not in locals():
count2 = 0
count1 += 1
count2 += 2
print count1, count2
Is there a more compact or efficient way to do this?