Code 1:
iteration = 0
count = 0
while iteration < 5:
for letter in "hello, world":
count += 1
print "Iteration " + str(iteration) + "; count is: " + str(count)
iteration += 1
代码 2:
iteration = 0
while iteration < 5:
count = 0
for letter in "hello, world":
count += 1
print "Iteration " + str(iteration) + "; count is: " + str(count)
iteration += 1
代码 3:
iteration = 0
while iteration < 5:
count = 0
for letter in "hello, world":
count += 1
if iteration % 2 == 0:
break
print "Iteration " + str(iteration) + "; count is: " + str(count)
iteration += 1
对于代码 1,您将继续添加到计数中。因此,在第一次迭代期间,计数变为 12("hello, world"的长度为 12),然后在第二次迭代期间,您永远不会将计数重置为 0,因此计数会不断添加,直到达到 24,因为它再次增加了"hello, world"的长度 (12 + 12 = 24)。
0 + len("hello, world") = 12
12 + len("hello, world") = 24
and so forth
对于代码 2,每次计数重置为 0。这意味着计数将始终等于 12,因为"hello, world"的长度为 12。
0 + len("hello, world") = 12
reset to 0
0 + len("hello, world") = 12
and so forth
对于代码 3,每次迭代为偶数时都会中断。这意味着对于迭代 0、2 和 4,迭代返回值 1,因为 1 在 for 循环开始时添加到迭代中。但是在奇数迭代期间,计数为 12,因为程序没有脱离 for 循环并添加"hello, world"的长度,即 12。
count = 0
For loop
"h" in "hello, world"
Add 1, 0 -> Is it even or odd? Even, Do not add len("ello, world") to count
1
count = 0
For loop
"h" in "hello, world"
Add 1, 0 -> Is it even or odd? Odd, Do add len("ello, world") to count
12
代码 1:
您的计数设置在while
循环之外,因此不受它的影响,因此会增加 12 len(hello, world) = 12
代码 2:
您的计数在while
循环内,因此它仅在每次迭代时重置。这就是为什么count = 12
保持不变,而Iteration
,在循环之外,增加。
代码 3:
当您Iteration
甚至代码在第一次计数后被破坏时。当它很奇怪时,它会很好地运行代码。
在每次迭代的代码 1 中,您都会将 count
的值添加到前一次迭代中。在代码 2 中,在每次迭代开始时,您都会重新分配count = 0
。在每次迭代中,在执行 for 循环后,将 12 添加到之前的计数值中,在代码 2 的情况下,该值始终0
。因此,在这两种情况下,计数值是不同的。
在情况 3 中,在执行 for 循环后,计数值将为 1(如果迭代值为偶数)或 12(如果迭代值为奇数)。这是因为检查 i%2 的 if 条件。因此,在情况 3 中,奇数和偶数的计数值是不同的。由于在每次迭代中您都重新分配count = 0
,因此所有奇数的计数值为 12,所有偶数的计数值为 1。