views:

233

answers:

2
for i in range(0,3):
    j = 0
    print 'incrementing '
    j += 1
    print j

prints

incrementing 
1
incrementing 
1
incrementing 
1

How can I persist the value of 'j' so that it prints:

1
2
3
+16  A: 

You should not reset j to zero in the loop:

j = 0
for i in range(0,3):
    print 'incrementng '
    j += 1
    print j
unbeknown
A: 

A very dirty hack if you want to put this in a function: default arguments! In Python, if a default argument is an array, it becomes "static" and mutable, you can keep it through different calls, like this:

def f(j = [0]):
    j[0] += 1
    print('incrementing', j[0])

f() # prints "incrementing 1"
f() # prints "incrementing 2"
f() # prints "incrementing 3"

Have fun!

Edit:

Amazing, downmoded without any explanation why this hack is bad or off-topic. Default arguments in Python are evaluated at parse-time, am I wrong? I don't think I am, I just expected intelligent answers instead of negative points on my post...

random
Why would you want to do this? I don't know about the dirty hack part. However, it appears to me that you have misunderstood the question. He wants to print 1,2,3 and thus he must not reset j in the loop...
batbrat
As I said, it's a dirty hack if you want to mix all the code inside a function. I have not misunderstood the question, I just "emulated" a static function member, that's the dirty hack...
random
I think the point being made is that the OP is obviously a beginner and was making a simple mistake that can be easily fixed, this "solution" is totally irrelevant to the scope of the question.
Paolo Bergantino
I thought the point of StackOverflow was to expand the solutions, and discuss more deeply about the questions. I am mistaken, this sucks huge balls...
random
@Paolo: Agreed. While this does do what it states (and is a dirty hack), it does not address the actual question asked.
Mike Boers
-1: giving complex code to beginners that misses the point of the question won't help.
nosklo