Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Assign value to variable during condition in while Loop

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.

like image 921
Borut Flis Avatar asked Nov 04 '13 12:11

Borut Flis


People also ask

Can we assign value in while loop?

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()) !=

Can you declare a variable in a while loop condition?

Yes. you can declare a variable inside any loop(includes do while loop.

How do you put a condition in a while loop in Python?

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.

Can you assign a variable in an if statement Python?

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.


1 Answers

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.

like image 146
RemcoGerlich Avatar answered Sep 21 '22 14:09

RemcoGerlich