letsc
letsc

Reputation: 2567

Python : Exit while loop when condition is met

Im trying to iterate over my list and calculate the diff between each element and the element following it. If the difference is greater than 0 ( or positive ) then increment up and decrease down by 1 ( if it is greater than 0 ). Similarly if difference is less than 0 then increment down and decrease up by 1 ( if greater than 0 ) . I want to exit out of the loop if either the up or down exceeds limit which is set to 3.

My code:

my_list = [13.04, 12.46, 13.1, 13.43, 13.76, 13.23, 12.15, 12.0, 11.55, 14.63]

up = 0
down = 0
limit = 3

while (up < limit) or (down < limit) :
    for i in range(len(my_list)-1):
        diff = my_list[i] - my_list[i+1]
        print (diff)
        if diff > 0:
            up +=1
            if down > 0:
                down -=1
        elif diff < 0:
            down +=1
            if up > 0:
                up -=1

Obviously this is not working since I keep getting caught up in an infinite loop and cant figure out what I am doing wrong.

Upvotes: 2

Views: 1163

Answers (3)

husam i
husam i

Reputation: 74

do not use while , you can use if condition in last of for loop for break it :

for i in range(len(my_list)-1):
    diff = my_list[i] - my_list[i+1]
    #print (diff)
    if diff > 0:
        up +=1
        if down > 0:
            down -=1
    elif diff < 0:
        down +=1
        if up > 0:
            up -=1
    if (up > limit)or (down > limit) :print(up);print(down);break

Upvotes: 1

Iftieaq
Iftieaq

Reputation: 1964

The problem is with your condition. You said you want to exit the program if either the up or down exceeds the limit which is set to 3. So the condition on the while loop needs to be set as while up is less than limit AND down is also less than limit, only then execute the body of the loop. Something like this.

while up < limit and down < limit:

or you can also use brackets (doesn't matter in this case)

while (up < limit) and (down < limit):

So the full program will be

my_list = [13.04, 12.46, 13.1, 13.43, 13.76, 13.23, 12.15, 12.0, 11.55, 14.63]

up = 0
down = 0
limit = 3

while up < limit and down < limit:
    for i in range(len(my_list)-1):
        diff = my_list[i] - my_list[i+1]
        print (diff)
        if diff > 0:
            up +=1
            if down > 0:
                down -=1
        elif diff < 0:
            down +=1
            if up > 0:
                up -=1

Upvotes: 0

fblthp
fblthp

Reputation: 98

The while condition is wrong. The loop keeps going while either up or down is below limit, so it will not stop even when up=1000, as long as down<3. What you want is while (up < limit) and (down < limit) instead.

Upvotes: 3

Related Questions