for循环有7个值需要滚动,但我得到了8个输出

wxclj1h5  于 2021-09-08  发布在  Java
关注(0)|答案(4)|浏览(278)

我的代码如下:

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
lyfkaqu1

lyfkaqu11#

我认为它应该在“in”中的每个值上滚动一次。
确实如此,但每个值都有一个 print 这是在任何情况下执行的,再加上另一种情况 print 如果条件( the_num < smallest_so_far )这是真的。因此,对于每个值,可以得到1行或2行输出。
在您的例子中,只有一个值有两行输出,因此总共有8行7个值的输出。但如果输入值的顺序不同,可能会有更多的输出行(最多14行)。
如果你想要第二个 print 如果第一个已执行,则需要使用 else 角色 if 语句(以便 if 部分 else 部分已执行),或者您可以使用 continue 语句,如果条件为true,则跳过循环迭代的其余部分。
备选案文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)
tuwxkamq

tuwxkamq2#

你需要另一个。代码仍将运行

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)
v09wglhw

v09wglhw3#

在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)
lf5gs5x2

lf5gs5x24#

您在循环中使用了if语句,而没有使用else语句,因此它同时打印这两条语句。使用下列内容

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)

相关问题