Python,UnboundLocalError:赋值前引用的局部变量'i'

时间:2016-02-03 08:16:37

标签: python

我正在尝试运行以下脚本:

i = 0
numbers = []

def number_includer(max_num):        

    while i < max_num:
        print "At the top i is %d" % i
        numbers.append(i)

        i = i + 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i

number_includer(7)


print "The numbers: "    

for num in numbers:
    print num

但当我这样做时:

numbers = []

def number_includer(max_num):
    # Used i equals 0 inside the function here.
    i = 0

    while i < max_num:
        print "At the top i is %d" % i
        numbers.append(i)

        i = i + 1
        print "Numbers now: ", numbers
        print "At the bottom i is %d" % i

number_includer(7)


print "The numbers: "    

for num in numbers:
    print num

我不想要回答而是一个解释,如果问题是在外部预定义的def内部使用局部变量,那么列表'数字'是全局的没有问题吗?

0 个答案:

没有答案