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

标签 python loops for-loop new-operator

我的代码如下:

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 .代码仍将运行

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)

关于python - for 循环有 7 个值可以滚动,但我得到 8 个输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68321717/

相关文章:

Python-socket.error : Cannot assign requested address

python - 遍历列表直到找到值然后中断?

JavaScript For 循环,用户输入错误

scala - 具有多个生成器的 for 循环如何在 Scala 中工作?

c - 为什么我的 for 循环没有进入嵌套的 for 循环?

python - 用于谐波分析的快速傅里叶变换

python - 如何删除文件中两个重复 block 之一?

python - Python 解释器在处理.py 文件时,与处理单个语句有区别吗?

javascript - 用于启动/停止无限循环的按钮,每个函数之间有延迟

python - 更改文件中的数字,无法使用 .split