Reputation: 8904
def test():
i = 0
for e in range(5):
i=+1
print('i in for loop {}'.format(i))
while True:
print ('i in while {}'.format(i))
break
test()
Tried a dictionary:
def test():
ns = {}
ns['i'] = 0
for e in range(5):
ns['i']=+1
print('i in for loop {}'.format(ns['i']))
while True:
print ('i in while {}'.format(ns['i']))
break
test()
And defining a an empty class:
class Namespace:pass
def test():
ns = Namespace()
ns.i = 0
for e in range(5):
ns.i =+1
print('i in for loop {}'.format(ns.i))
while True:
print ('i in while {}'.format(ns,i))
break
test()
Got this output:
i in for loop 1
i in while 1
i in for loop 1
i in while 1
i in for loop 1
i in while 1
i in for loop 1
i in while 1
i in for loop 1
i in while 1
wanted:
i in for loop 1
i in while 1
i in for loop 2
i in while 2
i in for loop 3
i in while 3
i in for loop 4
i in while 4
i in for loop 5
i in while 5
Are there work arounds, without resorting to global
so the 'i', that's referenced isn't local to each loop scope?
Upvotes: 1
Views: 33
Reputation: 1322
I think in your code you meant to write +=
but wrote =+
which is equivalent to =
.
Upvotes: 0