Search code examples
pythonloopsfor-loopnew-operator

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


My code is the following:

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)

But why does it check -3 with -3 again in the end, if it already did one line before? I thought it was supposed to scroll through each and every value inside the "in" once.

Output:

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

Solution

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

    It does, but for each value there is one print that is executed in any case, plus another print that is executed if the condition (the_num < smallest_so_far) is true. So for each value, you get 1 or possibly 2 lines of output.

    In your case, you got 2 lines of output only one of the values, so in total 8 lines of output for 7 values. But if the order of input values was different, there could have been even more lines of output (up to 14).

    If you want that the second print is not executed if the first was executed, you need to either use an else part for the if statement (so that either the if part or the else part is executed), or you can use a continue statement that skips the rest of the loop iteration if the condition was true.

    Option 1, using 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)
    

    Option 2, using 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)