educative.io

The break Keyword

Hi, for the example below, I don’t understand why it needs to be indented like this. Especially why does if found: need to be aligned with for n2 in num_list: ?

for n1 in num_list:
    for n2 in num_list:
        if(n1 != n2):
            if(n1 + n2 == n):
                found = True  # Set found to True
                break  # Break inner loop if a pair is found
    if found:
        print(n1, n2) # Print the pair
        break  # Break outer loop if a pair is found

Course: https://www.educative.io/courses/python-fundamentals-for-programmers
Lesson: https://www.educative.io/courses/python-fundamentals-for-programmers/qVZYY02mgR3


Course: https://www.educative.io/courses/python-fundamentals-for-programmers
Lesson: https://www.educative.io/courses/python-fundamentals-for-programmers/qVZYY02mgR3

Hi @Yanchen_Shen,

The if found: statement needs to be aligned with for n2 in num_list: because it is meant to execute after the inner loop finishes its iterations. It is intended to check if a pair is found after checking all possible pairs with n1, hence it should be outside the inner loop.

The indentation ensures that the code behaves as expected. If found is set to True within the inner loop, it means a pair has been found for the current n1, and it breaks out of the inner loop. Then, if found: checks if a pair has been found at all. If it has, it prints the pair and breaks out of the outer loop. If it hasn’t, it continues with the next iteration of the outer loop.

So, the indentation maintains the logical flow of the program by grouping statements correctly within loops and conditionals.

1 Like