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
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
You should not reset j
to zero in the loop:
j = 0
for i in range(0,3):
print 'incrementng '
j += 1
print j
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...