Python Assign value to variable during condition in while Loop

Borut Flis picture Borut Flis · Nov 4, 2013 · Viewed 41.7k times · Source

A simple question about Python syntax. I want to assign a value from a function to a variable during the condition for a while loop. When the value returned from the function is false, the loop should break. I know how to do it in PHP.

while (($data = fgetcsv($fh, 1000, ",")) !== FALSE) 

However when I try a similar syntax in Python I get a syntax error.

Answer

Martijn Pieters picture Martijn Pieters · Nov 4, 2013

You cannot use assignment in an expression. Assignment is itself a statement, and you cannot combine Python statements.

This is an explicit choice made by the language designers; it is all too easy to accidentally use one = and assign, where you meant to use two == and test for equality.

Move the assignment into the loop, or assign before the loop, and assign new values in the loop itself.

For your specific example, the Python csv module gives you a higher-level API and you'd be looping over the csv.reader() instead:

with open(csvfilename, 'rb') as csvfh:
    reader = csv.reader(csvfh)
    for row in reader:

I rarely, if ever, need to assign in a loop construct. Usually there is a (much) better way of solving the problem at hand.

That said, as of Python 3.8 the language will actually have assignment expressions, using := as the assignment operator. See PEP 572. Assignment expressions are actually useful in list comprehensions, for example, when you need to both include a method return value in the list you are building and need to be able to use that value in a test.

Now, you'd have to use a generator expression:

absolute = (os.path.abspath(p) for p in files)
filtered = [abs for abs in absolute if included(abs)]

but with assignment expressions you can inline the os.path.abspath() call:

filtered = [abs for p in files if included(abs := os.path.abspath(p))]