How to do variable assignment inside a while(expression) loop in Python?

前端 未结 6 1855
离开以前
离开以前 2020-12-08 22:30

I have the variable assignment in order to return the assigned value and compare that to an empty string, directly in the while loop.

Here is how I\'m doing it in PH

6条回答
  •  爱一瞬间的悲伤
    2020-12-08 22:56

    I'm only 7 years late, but there's another solution. It's not the best solution I can think of, but it highlights an interesting use of the StopIteration exception. You can do a similar loop for chunk reading files/sockets and handle Timeouts and whatnot nicely.

    names=[]
    try:
        while True:
            f = raw_input()
            if not f:
                raise StopIteration
            else:
                names.append(f)
    except StopIteration:
        pass
    
    print names
    

提交回复
热议问题