educative.io

Why is this the output in my nested loop?

n = 50

num_list = [10, 4, 23, 6, 18, 27, 47]

found = False 

for n1 in num_list:

    for n2 in num_list:

        if(n1 + n2 == n):
        found = True  
        break  

if found:
    print(n1, n2)

Why do I not get output as “23 47”, but instead various outputs for this actually? I do not understand how the program is flowing such that multiple outputs are produced. Would greatly appreciate any help to understand this, thank you!

This is the output I get (see below). I am confused because some of the combination of numbers don’t even add up to 50. Am wondering why…

23 27
6 47
18 47
27 23
47 47

You are getting the wrong output because you are not applying break after print(n1,n2) statement. We’ve got the desire pair and don’t want any further comparisons and it will also not check the if(n1 + n2 == n) condition after this break.