我在嵌套 for 循环中遇到了这种奇怪的行为,我无法解释这一点。这是特定于 python 的事情还是我只是在监督一些事情?
这是我正在运行的代码:
for i in range(16):
if i == 0:
for j in range(8):
print 'i is (if) ' + str(i)
i = i + 1
else:
print 'i is (else)' + str(i)
这是我得到的输出:
i is (if) 0
i is (if) 1
i is (if) 2
i is (if) 3
i is (if) 4
i is (if) 5
i is (if) 6
i is (if) 7
i is (else)1
i is (else)2
i is (else)3
i is (else)4
i is (else)5
i is (else)6
i is (else)7
i is (else)8
i is (else)9
i is (else)10
i is (else)11
i is (else)12
i is (else)13
i is (else)14
i is (else)15
这是我期待的输出:
i is (if) 0
i is (if) 1
i is (if) 2
i is (if) 3
i is (if) 4
i is (if) 5
i is (if) 6
i is (if) 7
i is (else)8
i is (else)9
i is (else)10
i is (else)11
i is (else)12
i is (else)13
i is (else)14
i is (else)15
看起来外部 for 循环中的 i 和内部 for 循环中的 i 是不同的变量,尽管这对我来说似乎完全违反直觉。
任何输入(我对 python 还很陌生,但找不到关于此的文档)