嵌入式循环奇怪的情况

问题描述 投票:0回答:1

为什么j值最初循环了两次? 代码:

others = 0
for i in range(2):
    print("i:", i)
    for j in range(3):
        print("j:", j)
        if i != j:
            print("i !=j ", i != j)
            others += 1
            print("others: ", others)
else:
    others += 1
    print("others under else: ", others)
print("others on the last line:", others)

输出:

`i: 0
j: 0
j: 1
i !=j  True
others:  1
j: 2
i !=j  True
others:  2
i: 1
j: 0
i !=j  True
others:  3
j: 1
j: 2
i !=j  True
others:  4
others under else:  5
others on the last line: 5

Process finished with exit code 0`

我上面没有代码,下面也没有代码。无法理解 j 发生了什么,为什么第一轮 j 有两个打印输出 0 和 1???请帮忙

for-loop embedded range
1个回答
0
投票

开头的 j 等于变量“i”,因此代码忽略“if”并将 j 递增为 1。之后,j 变为 1 并且它与 i 不同,因此其他递增,这也是j=2 的情况,因为你有范围(3)。然后 i 增加,同样的情况再次发生。现在的区别在于,当 j 等于 1 时,others 变量不会递增,因为现在 i 是 1。

此代码的一般功能是,i 获取值 0,然后获取 1,对于这两个值,j 获取值 0,1,2,当 i 不等于 j 时,其他变量递增。

在 python 中,索引也很重要,因此请确保 else 位于正确的位置及其相关的 if 以及您想要的结果是什么。

© www.soinside.com 2019 - 2024. All rights reserved.