Python 3是否可以从其内部的循环外引用变量(没有全局变量)?

时间:2018-05-24 18:52:28

标签: scope python-3.6

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()

试过一本字典:

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()

定义一个空类:

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()

得到了这个输出:

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

想:

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

是否存在解决问题,而没有诉诸global所以引用的'i'不是每个循环范围的本地?

2 个答案:

答案 0 :(得分:3)

只需将i = + 1改为i + = 1就可以了:)

答案 1 :(得分:0)

我认为在你的代码中你打算写+=但是写了=+,这相当于=