Home > front end >  Why is my Python nested while loop not working?
Why is my Python nested while loop not working?

Time:06-29

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!

CodePudding user response:

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.

  • Related