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.
You can pretty well use it anywhere a normal expression can be used (that comma inside your function calls is not a comma operator, for example) and it's very useful in writing compact source code, if that's what you like. In that way, it's part of the family that allows things like: while ((c= getchar()) !=
Yes. you can declare a variable inside any loop(includes do while loop.
You initiate the loop with the while keyword, then set the condition to be any conditional expression. A conditional expression is a statement that evaluates to True or False . As long as the condition is true, the loop body (the indented block that follows) will execute any statements it contains.
For example, assignment expressions using the := syntax allow variables to be assigned inside of if statements, which can often produce shorter and more compact sections of Python code by eliminating variable assignments in lines preceding or following the if statement.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With