Assign variable in while loop condition in Python?

前端 未结 11 1501
名媛妹妹
名媛妹妹 2020-12-08 03:39

I just came across this piece of code

while 1:
    line = data.readline()
    if not line:
        break
    #...

and thought, there must

11条回答
  •  离开以前
    2020-12-08 04:34

    Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), it's now possible to capture the condition value (data.readline()) of the while loop as a variable (line) in order to re-use it within the body of the loop:

    while line := data.readline():
      do_smthg(line)
    

提交回复
热议问题