for 循环有 7 个值可以滚动,但我得到 8 个输出

for loop has 7 values to scroll through, but I get 8 outputs

我的代码如下:

smallest_so_far = -1
print("Before:", smallest_so_far)
for the_num in [9, 41, 12, 3, 74, 15, -3]:
    if the_num < smallest_so_far:
        print(the_num, "is smaller than", smallest_so_far)
        smallest_so_far = the_num
    print(the_num, "is not smaller than", smallest_so_far)

print("After:", smallest_so_far)

但是如果它之前已经检查过一行,为什么最后还要用-3检查-3呢?我认为它应该滚动一次“in”中的每个值。

输出:

Before: -1
9 is not smaller than -1
41 is not smaller than -1
12 is not smaller than -1
3 is not smaller than -1
74 is not smaller than -1
15 is not smaller than -1
-3 is smaller than -1
-3 is not smaller than -3
After: -3

在 else 子句中插入打印:

smallest_so_far = 40
print("Before:", smallest_so_far)
for the_num in [9, 41, 12, 3, 74, 15, -3]:
    if the_num < smallest_so_far:
        print(the_num, "is smaller than", smallest_so_far)
        smallest_so_far = the_num
    else:
        print(the_num, "is not smaller than", smallest_so_far)

print("After:", smallest_so_far)

您需要 else。该代码仍将 运行

print(the_num, "is not smaller than", smallest_so_far)

无论如何。

因此您可以将代码更改为

smallest_so_far = -1
print("Before:", smallest_so_far)
for the_num in [9, 41, 12, 3, 74, 15, -3]:
    if the_num < smallest_so_far:
        print(the_num, "is smaller than", smallest_so_far)
        smallest_so_far = the_num
    else:
        print(the_num, "is not smaller than", smallest_so_far)

print("After:", smallest_so_far)

您在没有ELSE语句的循环中使用了IF语句,因此它正在打印这两个语句。 使用以下

if the_num < smallest_so_far:
    print(the_num, "is smaller than", smallest_so_far)
    smallest_so_far = the_num
else:
    print(the_num, "is not smaller than", smallest_so_far)

I thought it was supposed to scroll through each and every value inside the "in" once.

确实如此,但是对于每个值,在任何情况下都会执行一个 print,如果条件 (the_num < smallest_so_far) 为真,则会执行另一个 print。因此对于每个值,您会得到 1 行或可能 2 行输出。

在你的例子中,你得到了 2 行输出只有一个值,所以总共有 8 行输出 7 个值。但是如果输入值的顺序不同,可能会有更多的输出行(最多 14 行)。

如果您希望在执行第一个 print 时不执行第二个 print ,则需要为 if 语句使用 else 部分(以便 if 部分 else 部分被执行),或者你可以使用 continue 语句如果条件为真,则跳过循环迭代的其余部分。

选项 1,使用 else

for the_num in [9, 41, 12, 3, 74, 15, -3]:
    if the_num < smallest_so_far:
        print(the_num, "is smaller than", smallest_so_far)
        smallest_so_far = the_num
    else:
        print(the_num, "is not smaller than", smallest_so_far)

选项 2,使用 continue

for the_num in [9, 41, 12, 3, 74, 15, -3]:
    if the_num < smallest_so_far:
        print(the_num, "is smaller than", smallest_so_far)
        smallest_so_far = the_num
        continue
    print(the_num, "is not smaller than", smallest_so_far)