我的代码如下:
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/