首页 > 解决方案 > python中嵌套循环的范围规则

问题描述

def temp():
    temparray = ['a','b']
    temparray_2 = ['c','d','e']
    for i in temparray:
        print('i:' + str(i))
        for i in temparray_2:
            print('first: ' + str(i))
        print('Second: ' + str(i))

    print('final: ' + str(i))

为什么上面的代码输出如下?变量 i 似乎被内部循环中最后分配的任何内容覆盖。python 不遵守 Java 或 C 之类的范围规则吗?

i:a
first: c
first: d
first: e
Second: e
i:b
first: c
first: d
first: e
Second: e
final: e

标签: python

解决方案


与任何函数局部赋值一样,循环索引在循环出现的整个函数的范围内。循环本身不会创建新范围。forfor


推荐阅读