简体   繁体   中英

How can I get out of while loop?

def solution(ingredient):
    ingredient=np.array(ingredient)
    answer = 0
    while True:
        try:
            for i in range(len(ingredient)-3):
                if (ingredient[0+i:4+i] == [1,2,3,1]).all():
                        answer+=1
                        del_ingredient=np.delete(ingredient,(0+i,1+i,2+i,3+i))

                        if len(del_ingredient)!=len(ingredient):
                            ingredient=del_ingredient
                            break

                        else:
                            raise
        
        except:
            return answer
            break

When I stopped the loop by ctrl c, I obtained the value of answer. But why I can't get out of the loop???

it because you don't have any terminal condition

while True simply means run forever so that is the reason why it is running until you hit ctrl+c

if you want to stop it at some point the use terminal condition in while statement while (your condition to stop)

thank you

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