JGFMK
JGFMK

Reputation: 8904

Python 3 Is it possible to reference a variable from outside a loop inside it (without a global)?

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

Answers (2)

Olivier Sohn
Olivier Sohn

Reputation: 1322

I think in your code you meant to write += but wrote =+ which is equivalent to =.

Upvotes: 0

jedzej
jedzej

Reputation: 444

Just change i=+1 to i+=1 and you're good to go:)

Upvotes: 3

Related Questions