0
votes

I have a while loop inside an else statement which is contained in another while loop. Something like this: while->else->while. I am updating some variables in the inner while loop, and those variables also form the condition of outer while loop. What I expect is as soon as the variables in inner while loop take values that break the condition of outer while loop, the outer while loop should break. But that doesn't seem to happen and inner while loop keeps running. And eventually I get an error because the loop didn't stop and condition is still invalid (IndexError: list index out of range)

            nums=[0,0,0]
            i=0
            j=i+1
            k=len(nums)-1
            while(k>j):               
                s=nums[i]+nums[j]+nums[k]

              #greater than 0
                if s>0:    
                   #do something
              
                else:
                    #do something

                    while(nums[k]==nums[k-1]):#<<<<<<<------ here I get IndexError: list index out of range
                        print("2nd wihile ",k,j)
                        k-=1
                    k-=1
                    while(nums[j]==nums[j+1]):
                        
                        j+=1
                    j+=1

the print statement inside inner while prints following before giving an error:

2nd wihile  2 1
2nd wihile  1 1
2nd wihile  0 1
2nd wihile  -1 1
2nd wihile  -2 1
IndexError: list index out of range

1

1 Answers

0
votes

Take a look at the following:

>>> x = 1
>>> while x == 1:
...  while True:
...   print("x", x)
...   x = 2

It sums up your issue, which is the outer loop is not tested during the internal sub-loop.
The test is applied for each iteration, once you introduce an internal loop, the outer loops iterations and therefore checks, stop until the next iteration of the outer loop.