简体   繁体   中英

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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM