Assign variable in while loop condition in Python? Assign variable in while loop condition in Python? python python

Assign variable in while loop condition in Python?


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)


Try this one, works for files opened with open('filename')

for line in iter(data.readline, b''):


If you aren't doing anything fancier with data, like reading more lines later on, there's always:

for line in data:    ... do stuff ...