这三种情况下 count 的结果有何不同?

How are the results for count different in all these three cases?

代码 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,迭代 returns 将值 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 添加到 count 的先前值,在代码 2 的情况下,它始终是 0。因此,两种情况下的计数值都不同。

情况3,for循环执行后,要么计数值为1(如果迭代的值为偶数),要么为12(如果迭代的值为奇数)。这是因为检查 i%2 的 if 条件。因此,在情况 3 中,奇数和偶数的计数值不同。并且由于在每次迭代期间您都重新分配 count = 0,所有奇数的计数值为 12,所有偶数的计数值为 1.