简体   繁体   中英

How does this while loop work?

Hoping someone can explain what's going on with this while loop.

x=deque([(1,2,3)])
while x:
    a,b,c = x.popleft()
    do stuff with values in x
    x.append((d,e,f))

I get that x is a deque with 3 items which are constantly being replaced by new values. But I've never encountered a while loop without some kind of condition. How will the loop know when to stop?

x=deque([(1,2,3)]) # create new deque
while x: # while not empty
    a,b,c = x.popleft() # pop values and assign them to a and b and c
    # do stuff with values in x - this is comment too
    x.append((d,e,f)) # assumes produced new values d 
                      #and e and f and pushes them to x
# this assumes there is always d and e and f values and stays forever in loop 

as explained in here Python 2.7: How to check if a deque is empty?

As written, the code is an infinite loop because it adds data at the same rate as it is being removed.

If the size was being whittled down, the while x would terminate the loop when the deque was empty.

The boolean value of x=deque([(1,2,3)]) is True because it has a value and is not equal to None . This is an infite loop like while 1: or while True: .

For this loop to end you would either have to use a break when a condition is met or set x = None to break the loop

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