Python Assign value to variable during condition in while Loop [duplicate]

2020 answer:

Since Python 3.8, the “walrus operator” := exists that does exactly what you want:

while data := fgetcsv(fh, 1000, ",") != False:
    pass

(if that fgetcsv function existed)

2013 answer:
You can’t do that in Python, no assignment in expressions. At least that means you won’t accidentally type == instead of = or the other way around and have it work.

Traditional Python style is to just use while True and break:

while True:
    data = fgetcsv(fh, 1000, ",")
    if not data:
        break
    # Use data here

But nowadays I’d put that in a generator:

def data_parts(fh):
    while True:
        data = fgetcsv(fh, 1000, ",")
        if not data:
            break
        yield data

so that in the code that uses the file, the ugliness is hidden away:

for data in data_parts(fh):
    # Use data here

Of course if it’s actually CSV reading that you’re doing, use the csv module.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)