Python Assign value to variable during condition in while Loop

前端 未结 4 1142
误落风尘
误落风尘 2020-12-16 11:29

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 functio

4条回答
  •  無奈伤痛
    2020-12-16 12:12

    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.

提交回复
热议问题