dimanche 5 septembre 2021

while inside else inside while not breaking in Python

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

Aucun commentaire:

Enregistrer un commentaire