简体   繁体   中英

Persisting variable value in Python

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM