Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign variable in while loop condition in Python?

I just came across this piece of code

while 1:     line = data.readline()     if not line:         break     #... 

and thought, there must be a better way to do this, than using an infinite loop with break.

So I tried:

while line = data.readline():     #... 

and, obviously, got an error.

Is there any way to avoid using a break in that situation?

Edit:

Ideally, you'd want to avoid saying readline twice... IMHO, repeating is even worse than just a break, especially if the statement is complex.

like image 516
user541686 Avatar asked Jul 08 '11 22:07

user541686


People also ask

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 we assign value in while loop?

Yes, the comma operator has the lowest precedence of all.

How do you update a value in a while loop in Python?

You need to initialize previous guess before while loop Otherwise it will be initialized again and again. You have to set the value of previous guess to x the computer generator and when you move on after loop you have to update the previous guess to next simply like this: Add before while { previous_guess = x }


1 Answers

Starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), it's now possible to capture the condition value (data.readline()) of the while loop as a variable (line) in order to re-use it within the body of the loop:

while line := data.readline():   do_smthg(line) 
like image 95
Xavier Guihot Avatar answered Oct 23 '22 03:10

Xavier Guihot