0

I'm learning Python and have a hard time understanding what's wrong with my logic in this nested loop.

numbers = [4, 3, 1, 3, 5]
sum = 0
    
while sum < 10:
 for n in numbers:
   sum += n
    
print(sum)

While sum is less than 10, iterate through the next object in a list and add it to the sum. Thus, it's supposed to print 11 (4+3+1+3, then it stops), but instead it prints 16. I have tried changing the order of loops:

for n in numbers:
 while sum < 10:
  sum += n

But then it prints 12, which further confuses me.

Can anybody please help? Thank you!

4
  • 1
    You simply do not understand how nested loops work. Put enough print() statements inside your loops to actually trace the execution. Commented Jun 28, 2022 at 22:22
  • Please avoid using the built-in sum as variable name. Commented Jun 28, 2022 at 22:26
  • Tim's Answer already explains it pretty well imo. I'd just like to add that in most such cases of confusion a debugger is very helpful. Since you are new to python you have perhaps not yet heard of that - if not, I recommend looking it up. It would allow you to see how the code affects the variables step by step. Commented Jun 28, 2022 at 22:26
  • Easier to run such small program in a visual platform - pythontutor Commented Jun 28, 2022 at 22:28

1 Answer 1

2

It's because the outer while loop cannot test the sum value until the inner loop has totally completed. You would need something like this:

for n in numbers:
   sum += n
   if sum >= 10:
      break

As for your second sample, trace through it:

for n in numbers:
 while sum < 10:
  sum += n

To start with, n will be set to 4. You then stay in the inner loop for a while. sum will become 4, then 8, then 12, then that loop exits. As the outer loop goes through the rest of the numbers, sum is already greater than 10, so the while loop never runs.

You can't use two nested loops to accomplish your task. It must be one loop with an extra exit condition.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.